blob: efda6608e44d1a67d44ead393a6f611c730ab34e [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
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000480/// ShouldChangeType - Return true if it is desirable to convert a computation
481/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
482/// type for example, or from a smaller to a larger illegal type.
483static bool ShouldChangeType(const Type *From, const Type *To,
484 const TargetData *TD) {
485 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
486
487 // If we don't have TD, we don't know if the source/dest are legal.
488 if (!TD) return false;
489
490 unsigned FromWidth = From->getPrimitiveSizeInBits();
491 unsigned ToWidth = To->getPrimitiveSizeInBits();
492 bool FromLegal = TD->isLegalInteger(FromWidth);
493 bool ToLegal = TD->isLegalInteger(ToWidth);
494
495 // If this is a legal integer from type, and the result would be an illegal
496 // type, don't do the transformation.
497 if (FromLegal && !ToLegal)
498 return false;
499
500 // Otherwise, if both are illegal, do not increase the size of the result. We
501 // do allow things like i160 -> i64, but not i64 -> i160.
502 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
503 return false;
504
505 return true;
506}
507
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000508/// getBitCastOperand - If the specified operand is a CastInst, a constant
509/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
510/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000511static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000512 if (Operator *O = dyn_cast<Operator>(V)) {
513 if (O->getOpcode() == Instruction::BitCast)
514 return O->getOperand(0);
515 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
516 if (GEP->hasAllZeroIndices())
517 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000518 }
Chris Lattnereed48272005-09-13 00:40:14 +0000519 return 0;
520}
521
Reid Spencer3da59db2006-11-27 01:05:10 +0000522/// This function is a wrapper around CastInst::isEliminableCastPair. It
523/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000524static Instruction::CastOps
525isEliminableCastPair(
526 const CastInst *CI, ///< The first cast instruction
527 unsigned opcode, ///< The opcode of the second cast instruction
528 const Type *DstTy, ///< The target type for the second cast instruction
529 TargetData *TD ///< The target data for pointer size
530) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000531
Reid Spencer3da59db2006-11-27 01:05:10 +0000532 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
533 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000534
Reid Spencer3da59db2006-11-27 01:05:10 +0000535 // Get the opcodes of the two Cast instructions
536 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
537 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000538
Chris Lattnera0e69692009-03-24 18:35:40 +0000539 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000540 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000541 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000542
543 // We don't want to form an inttoptr or ptrtoint that converts to an integer
544 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000545 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000546 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000547 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000548 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000549 Res = 0;
550
551 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000552}
553
554/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
555/// in any code being generated. It does not require codegen if V is simple
556/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000557static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
558 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000559 if (V->getType() == Ty || isa<Constant>(V)) return false;
560
Chris Lattner01575b72006-05-25 23:24:33 +0000561 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000562 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000563 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000564 return false;
565 return true;
566}
567
Chris Lattner4f98c562003-03-10 21:43:22 +0000568// SimplifyCommutative - This performs a few simplifications for commutative
569// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000570//
Chris Lattner4f98c562003-03-10 21:43:22 +0000571// 1. Order operands such that they are listed from right (least complex) to
572// left (most complex). This puts constants before unary operators before
573// binary operators.
574//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
576// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000577//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000579 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000580 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000581 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000582
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 if (!I.isAssociative()) return Changed;
584 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
586 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
587 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000589 cast<Constant>(I.getOperand(1)),
590 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 I.setOperand(0, Op->getOperand(0));
592 I.setOperand(1, Folded);
593 return true;
594 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
595 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
596 isOnlyUse(Op) && isOnlyUse(Op1)) {
597 Constant *C1 = cast<Constant>(Op->getOperand(1));
598 Constant *C2 = cast<Constant>(Op1->getOperand(1));
599
600 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000602 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603 Op1->getOperand(0),
604 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000605 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000606 I.setOperand(0, New);
607 I.setOperand(1, Folded);
608 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000609 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000610 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000611 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000612}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000613
Chris Lattner8d969642003-03-10 23:06:50 +0000614// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
615// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000616//
Dan Gohman186a6362009-08-12 16:04:34 +0000617static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000618 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000619 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000620
Chris Lattner0ce85802004-12-14 20:08:06 +0000621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000623 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000624
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000627 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000628
Chris Lattner8d969642003-03-10 23:06:50 +0000629 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000630}
631
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000632// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
633// instruction if the LHS is a constant negative zero (which is the 'negate'
634// form).
635//
Dan Gohman186a6362009-08-12 16:04:34 +0000636static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000637 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000638 return BinaryOperator::getFNegArgument(V);
639
640 // Constants can be considered to be negated values if they can be folded.
641 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000642 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000643
644 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
645 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000646 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000647
648 return 0;
649}
650
Chris Lattner48b59ec2009-10-26 15:40:07 +0000651/// isFreeToInvert - Return true if the specified value is free to invert (apply
652/// ~ to). This happens in cases where the ~ can be eliminated.
653static inline bool isFreeToInvert(Value *V) {
654 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000655 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000656 return true;
657
658 // Constants can be considered to be not'ed values.
659 if (isa<ConstantInt>(V))
660 return true;
661
662 // Compares can be inverted if they have a single use.
663 if (CmpInst *CI = dyn_cast<CmpInst>(V))
664 return CI->hasOneUse();
665
666 return false;
667}
668
669static inline Value *dyn_castNotVal(Value *V) {
670 // If this is not(not(x)) don't return that this is a not: we want the two
671 // not's to be folded first.
672 if (BinaryOperator::isNot(V)) {
673 Value *Operand = BinaryOperator::getNotArgument(V);
674 if (!isFreeToInvert(Operand))
675 return Operand;
676 }
Chris Lattner8d969642003-03-10 23:06:50 +0000677
678 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000679 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000680 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000681 return 0;
682}
683
Chris Lattner48b59ec2009-10-26 15:40:07 +0000684
685
Chris Lattnerc8802d22003-03-11 00:12:48 +0000686// dyn_castFoldableMul - If this value is a multiply that can be folded into
687// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000688// non-constant operand of the multiply, and set CST to point to the multiplier.
689// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000690//
Dan Gohman186a6362009-08-12 16:04:34 +0000691static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000692 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000693 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000694 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000695 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000696 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000697 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000698 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000699 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000700 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000701 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000702 CST = ConstantInt::get(V->getType()->getContext(),
703 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000704 return I->getOperand(0);
705 }
706 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000707 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000708}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000709
Reid Spencer7177c3a2007-03-25 05:33:51 +0000710/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000711static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000712 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000713 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000714}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000715/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000716static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000717 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000718 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000719}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000720/// MultiplyOverflows - True if the multiply can not be expressed in an int
721/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000722static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000723 uint32_t W = C1->getBitWidth();
724 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
725 if (sign) {
726 LHSExt.sext(W * 2);
727 RHSExt.sext(W * 2);
728 } else {
729 LHSExt.zext(W * 2);
730 RHSExt.zext(W * 2);
731 }
732
733 APInt MulExt = LHSExt * RHSExt;
734
735 if (sign) {
736 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
737 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
738 return MulExt.slt(Min) || MulExt.sgt(Max);
739 } else
740 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
741}
Chris Lattner955f3312004-09-28 21:48:02 +0000742
Reid Spencere7816b52007-03-08 01:52:58 +0000743
Chris Lattner255d8912006-02-11 09:31:47 +0000744/// ShrinkDemandedConstant - Check to see if the specified operand of the
745/// specified instruction is a constant integer. If so, check to see if there
746/// are any bits set in the constant that are not demanded. If so, shrink the
747/// constant and return true.
748static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000749 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000750 assert(I && "No instruction?");
751 assert(OpNo < I->getNumOperands() && "Operand index too large");
752
753 // If the operand is not a constant integer, nothing to do.
754 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755 if (!OpC) return false;
756
757 // If there are no bits set that aren't demanded, nothing to do.
758 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
759 if ((~Demanded & OpC->getValue()) == 0)
760 return false;
761
762 // This instruction is producing bits that are not demanded. Shrink the RHS.
763 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000764 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000765 return true;
766}
767
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000768// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
769// set of known zero and one bits, compute the maximum and minimum values that
770// could have the specified known zero and known one bits, returning them in
771// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000772static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000773 const APInt& KnownOne,
774 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000775 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
776 KnownZero.getBitWidth() == Min.getBitWidth() &&
777 KnownZero.getBitWidth() == Max.getBitWidth() &&
778 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000779 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000780
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000781 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
782 // bit if it is unknown.
783 Min = KnownOne;
784 Max = KnownOne|UnknownBits;
785
Dan Gohman1c8491e2009-04-25 17:12:48 +0000786 if (UnknownBits.isNegative()) { // Sign bit is unknown
787 Min.set(Min.getBitWidth()-1);
788 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000789 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000790}
791
792// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793// a set of known zero and one bits, compute the maximum and minimum values that
794// could have the specified known zero and known one bits, returning them in
795// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000796static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000797 const APInt &KnownOne,
798 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000799 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
800 KnownZero.getBitWidth() == Min.getBitWidth() &&
801 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000802 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000803 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000804
805 // The minimum value is when the unknown bits are all zeros.
806 Min = KnownOne;
807 // The maximum value is when the unknown bits are all ones.
808 Max = KnownOne|UnknownBits;
809}
Chris Lattner255d8912006-02-11 09:31:47 +0000810
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
812/// SimplifyDemandedBits knows about. See if the instruction has any
813/// properties that allow us to simplify its operands.
814bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000815 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
817 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
818
819 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
820 KnownZero, KnownOne, 0);
821 if (V == 0) return false;
822 if (V == &Inst) return true;
823 ReplaceInstUsesWith(Inst, V);
824 return true;
825}
826
827/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
828/// specified instruction operand if possible, updating it in place. It returns
829/// true if it made any change and false otherwise.
830bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
831 APInt &KnownZero, APInt &KnownOne,
832 unsigned Depth) {
833 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
834 KnownZero, KnownOne, Depth);
835 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000836 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 return true;
838}
839
840
841/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
842/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000843/// that only the bits set in DemandedMask of the result of V are ever used
844/// downstream. Consequently, depending on the mask and V, it may be possible
845/// to replace V with a constant or one of its operands. In such cases, this
846/// function does the replacement and returns true. In all other cases, it
847/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000849/// to be zero in the expression. These are provided to potentially allow the
850/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
851/// the expression. KnownOne and KnownZero always follow the invariant that
852/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
853/// the bits in KnownOne and KnownZero may only be accurate for those bits set
854/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
855/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000856///
857/// This returns null if it did not change anything and it permits no
858/// simplification. This returns V itself if it did some simplification of V's
859/// operands based on the information about what bits are demanded. This returns
860/// some other non-null value if it found out that V is equal to another value
861/// in the context where the specified bits are demanded, but not for all users.
862Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
863 APInt &KnownZero, APInt &KnownOne,
864 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000865 assert(V != 0 && "Null pointer of Value???");
866 assert(Depth <= 6 && "Limit Search Depth");
867 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000868 const Type *VTy = V->getType();
869 assert((TD || !isa<PointerType>(VTy)) &&
870 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000871 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
872 (!VTy->isIntOrIntVector() ||
873 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000874 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000875 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000876 "Value *V, DemandedMask, KnownZero and KnownOne "
877 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000878 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
879 // We know all of the bits for a constant!
880 KnownOne = CI->getValue() & DemandedMask;
881 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000882 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000883 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000884 if (isa<ConstantPointerNull>(V)) {
885 // We know all of the bits for a constant!
886 KnownOne.clear();
887 KnownZero = DemandedMask;
888 return 0;
889 }
890
Chris Lattner08d2cc72009-01-31 07:26:06 +0000891 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000892 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000893 if (DemandedMask == 0) { // Not demanding any bits from V.
894 if (isa<UndefValue>(V))
895 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000896 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000897 }
898
Chris Lattner4598c942009-01-31 08:24:16 +0000899 if (Depth == 6) // Limit search depth.
900 return 0;
901
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000902 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
903 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
904
Dan Gohman1c8491e2009-04-25 17:12:48 +0000905 Instruction *I = dyn_cast<Instruction>(V);
906 if (!I) {
907 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908 return 0; // Only analyze instructions.
909 }
910
Chris Lattner4598c942009-01-31 08:24:16 +0000911 // If there are multiple uses of this value and we aren't at the root, then
912 // we can't do any simplifications of the operands, because DemandedMask
913 // only reflects the bits demanded by *one* of the users.
914 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000915 // Despite the fact that we can't simplify this instruction in all User's
916 // context, we can at least compute the knownzero/knownone bits, and we can
917 // do simplifications that apply to *just* the one user if we know that
918 // this instruction has a simpler value in that context.
919 if (I->getOpcode() == Instruction::And) {
920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), DemandedMask,
922 RHSKnownZero, RHSKnownOne, Depth+1);
923 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
924 LHSKnownZero, LHSKnownOne, Depth+1);
925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and' in this
928 // context.
929 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
930 (DemandedMask & ~LHSKnownZero))
931 return I->getOperand(0);
932 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
933 (DemandedMask & ~RHSKnownZero))
934 return I->getOperand(1);
935
936 // If all of the demanded bits in the inputs are known zeros, return zero.
937 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000938 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000939
940 } else if (I->getOpcode() == Instruction::Or) {
941 // We can simplify (X|Y) -> X or Y in the user's context if we know that
942 // only bits from X or Y are demanded.
943
944 // If either the LHS or the RHS are One, the result is One.
945 ComputeMaskedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1);
947 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
948 LHSKnownZero, LHSKnownOne, Depth+1);
949
950 // If all of the demanded bits are known zero on one side, return the
951 // other. These bits cannot contribute to the result of the 'or' in this
952 // context.
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
958 return I->getOperand(1);
959
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
964 return I->getOperand(0);
965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
967 return I->getOperand(1);
968 }
969
Chris Lattner4598c942009-01-31 08:24:16 +0000970 // Compute the KnownZero/KnownOne bits to simplify things downstream.
971 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
972 return 0;
973 }
974
975 // If this is the root being simplified, allow it to have multiple uses,
976 // just set the DemandedMask to all bits so that we can try to simplify the
977 // operands. This allows visitTruncInst (for example) to simplify the
978 // operand of a trunc without duplicating all the logic below.
979 if (Depth == 0 && !V->hasOneUse())
980 DemandedMask = APInt::getAllOnesValue(BitWidth);
981
Reid Spencer8cb68342007-03-12 17:25:59 +0000982 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000983 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000985 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000986 case Instruction::And:
987 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // If all of the demanded bits are known 1 on one side, return the other.
997 // These bits cannot contribute to the result of the 'and'.
998 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
999 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001001 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1002 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
1005 // If all of the demanded bits in the inputs are known zeros, return zero.
1006 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001007 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001010 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001012
1013 // Output known-1 bits are only known if set in both the LHS & RHS.
1014 RHSKnownOne &= LHSKnownOne;
1015 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1016 RHSKnownZero |= LHSKnownZero;
1017 break;
1018 case Instruction::Or:
1019 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1021 RHSKnownZero, RHSKnownOne, Depth+1) ||
1022 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I;
1025 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1026 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
1028 // If all of the demanded bits are known zero on one side, return the other.
1029 // These bits cannot contribute to the result of the 'or'.
1030 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1031 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1034 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001036
1037 // If all of the potentially set bits on one side are known to be set on
1038 // the other side, just use the 'other' side.
1039 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1040 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1043 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
1046 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // Output known-0 bits are only known if clear in both the LHS & RHS.
1051 RHSKnownZero &= LHSKnownZero;
1052 // Output known-1 are known to be set if set in either the LHS | RHS.
1053 RHSKnownOne |= LHSKnownOne;
1054 break;
1055 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If all of the demanded bits are known zero on one side, return the other.
1065 // These bits cannot contribute to the result of the 'xor'.
1066 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1072 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1073 (RHSKnownOne & LHSKnownOne);
1074 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1075 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1076 (RHSKnownOne & LHSKnownZero);
1077
1078 // If all of the demanded bits are known to be zero on one side or the
1079 // other, turn this into an *inclusive* or.
1080 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001081 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1082 Instruction *Or =
1083 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1084 I->getName());
1085 return InsertNewInstBefore(Or, *I);
1086 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001087
1088 // If all of the demanded bits on one side are known, and all of the set
1089 // bits on that side are also known to be set on the other side, turn this
1090 // into an AND, as we know the bits will be cleared.
1091 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1092 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1093 // all known
1094 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001095 Constant *AndC = Constant::getIntegerValue(VTy,
1096 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001098 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 }
1101 }
1102
1103 // If the RHS is a constant, see if we can simplify it.
1104 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001105 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001107
Chris Lattnerd0883142009-10-11 22:22:13 +00001108 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1109 // are flipping are known to be set, then the xor is just resetting those
1110 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1111 // simplifying both of them.
1112 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1113 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1114 isa<ConstantInt>(I->getOperand(1)) &&
1115 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1116 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1117 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1118 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1119 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1120
1121 Constant *AndC =
1122 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1123 Instruction *NewAnd =
1124 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1125 InsertNewInstBefore(NewAnd, *I);
1126
1127 Constant *XorC =
1128 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1129 Instruction *NewXor =
1130 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1131 return InsertNewInstBefore(NewXor, *I);
1132 }
1133
1134
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 RHSKnownZero = KnownZeroOut;
1136 RHSKnownOne = KnownOneOut;
1137 break;
1138 }
1139 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
1145 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1146 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001147
1148 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001149 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1150 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
1153 // Only known if known in both the LHS and RHS.
1154 RHSKnownOne &= LHSKnownOne;
1155 RHSKnownZero &= LHSKnownZero;
1156 break;
1157 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001158 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 DemandedMask.zext(truncBf);
1160 RHSKnownZero.zext(truncBf);
1161 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 DemandedMask.trunc(BitWidth);
1166 RHSKnownZero.trunc(BitWidth);
1167 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 break;
1170 }
1171 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001172 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001174
1175 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1176 if (const VectorType *SrcVTy =
1177 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1178 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1179 // Don't touch a bitcast between vectors of different element counts.
1180 return false;
1181 } else
1182 // Don't touch a scalar-to-vector bitcast.
1183 return false;
1184 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1185 // Don't touch a vector-to-scalar bitcast.
1186 return false;
1187
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return I;
1191 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 break;
1193 case Instruction::ZExt: {
1194 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001195 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
Zhou Shengd48653a2007-03-29 04:45:55 +00001197 DemandedMask.trunc(SrcBitWidth);
1198 RHSKnownZero.trunc(SrcBitWidth);
1199 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001201 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 DemandedMask.zext(BitWidth);
1204 RHSKnownZero.zext(BitWidth);
1205 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 break;
1210 }
1211 case Instruction::SExt: {
1212 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001213 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 // If any of the sign extended bits are demanded, we know that the sign
1220 // bit is demanded.
1221 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001222 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001223
Zhou Shengd48653a2007-03-29 04:45:55 +00001224 InputDemandedBits.trunc(SrcBitWidth);
1225 RHSKnownZero.trunc(SrcBitWidth);
1226 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 InputDemandedBits.zext(BitWidth);
1231 RHSKnownZero.zext(BitWidth);
1232 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001234
1235 // If the sign bit of the input is known set or clear, then we know the
1236 // top bits of the result.
1237
1238 // If the input sign bit is known zero, or if the NewBits are not demanded
1239 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1243 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 }
1247 break;
1248 }
1249 case Instruction::Add: {
1250 // Figure out what the input bits are. If the top bits of the and result
1251 // are not demanded, then the add doesn't demand them from its input
1252 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001254
1255 // If there is a constant on the RHS, there are a variety of xformations
1256 // we can do.
1257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 // If null, this should be simplified elsewhere. Some of the xforms here
1259 // won't work if the RHS is zero.
1260 if (RHS->isZero())
1261 break;
1262
1263 // If the top bit of the output is demanded, demand everything from the
1264 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001266
1267 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001271
1272 // If the RHS of the add has bits set that can't affect the input, reduce
1273 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001274 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001276
1277 // Avoid excess work.
1278 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1279 break;
1280
1281 // Turn it into OR if input bits are zero.
1282 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1283 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001284 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 }
1288
1289 // We can say something about the output known-zero and known-one bits,
1290 // depending on potential carries from the input constant and the
1291 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1292 // bits set and the RHS constant is 0x01001, then we know we have a known
1293 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1294
1295 // To compute this, we first compute the potential carry bits. These are
1296 // the bits which may be modified. I'm not aware of a better way to do
1297 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001299 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
1301 // Now that we know which bits have carries, compute the known-1/0 sets.
1302
1303 // Bits are known one if they are known zero in one operand and one in the
1304 // other, and there is no input carry.
1305 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1306 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1307
1308 // Bits are known zero if they are known zero in both operands and there
1309 // is no input carry.
1310 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1311 } else {
1312 // If the high-bits of this ADD are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Right fill the mask of bits for this ADD to demand the most
1316 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 }
1324 }
1325 break;
1326 }
1327 case Instruction::Sub:
1328 // If the high-bits of this SUB are not demanded, then it does not demand
1329 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001330 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 // Right fill the mask of bits for this SUB to demand the most
1332 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001333 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1336 LHSKnownZero, LHSKnownOne, Depth+1) ||
1337 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001341 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1342 // the known zeros and ones.
1343 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 break;
1345 case Instruction::Shl:
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001347 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001348 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 return I;
1352 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 RHSKnownZero <<= ShiftAmt;
1354 RHSKnownOne <<= ShiftAmt;
1355 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001356 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001357 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001358 }
1359 break;
1360 case Instruction::LShr:
1361 // For a logical shift right
1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001363 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001364
Reid Spencer8cb68342007-03-12 17:25:59 +00001365 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001366 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 return I;
1370 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001373 if (ShiftAmt) {
1374 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001376 RHSKnownZero |= HighBits; // high bits known zero.
1377 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001378 }
1379 break;
1380 case Instruction::AShr:
1381 // If this is an arithmetic shift right and only the low-bit is set, we can
1382 // always convert this into a logical shr, even if the shift amount is
1383 // variable. The low bit of the shift cannot be an input sign bit unless
1384 // the shift amount is >= the size of the datatype, which is undefined.
1385 if (DemandedMask == 1) {
1386 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001387 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001391
1392 // If the sign bit is the only bit demanded by this ashr, then there is no
1393 // need to do it, the shift doesn't change the high bit.
1394 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001395 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001396
1397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001398 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001399
Reid Spencer8cb68342007-03-12 17:25:59 +00001400 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001402 // If any of the "high bits" are demanded, we should set the sign bit as
1403 // demanded.
1404 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1405 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001406 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001408 return I;
1409 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001411 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1413 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1414
1415 // Handle the sign bits.
1416 APInt SignBit(APInt::getSignBit(BitWidth));
1417 // Adjust to where it is now in the mask.
1418 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1419
1420 // If the input sign bit is known to be zero, or if none of the top bits
1421 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001422 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001423 (HighBits & ~DemandedMask) == HighBits) {
1424 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001425 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001428 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1429 RHSKnownOne |= HighBits;
1430 }
1431 }
1432 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001433 case Instruction::SRem:
1434 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001435 APInt RA = Rem->getValue().abs();
1436 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001437 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001438 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001439
Nick Lewycky8e394322008-11-02 02:41:50 +00001440 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001441 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001442 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001443 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001444 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001445
1446 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1447 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001448
1449 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001450
Chris Lattner886ab6c2009-01-31 08:15:18 +00001451 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001452 }
1453 }
1454 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001455 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001456 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1457 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001458 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1459 KnownZero2, KnownOne2, Depth+1) ||
1460 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001461 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001462 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001463
Chris Lattner455e9ab2009-01-21 18:09:24 +00001464 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001465 Leaders = std::max(Leaders,
1466 KnownZero2.countLeadingOnes());
1467 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001468 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001470 case Instruction::Call:
1471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1472 switch (II->getIntrinsicID()) {
1473 default: break;
1474 case Intrinsic::bswap: {
1475 // If the only bits demanded come from one byte of the bswap result,
1476 // just shift the input byte into position to eliminate the bswap.
1477 unsigned NLZ = DemandedMask.countLeadingZeros();
1478 unsigned NTZ = DemandedMask.countTrailingZeros();
1479
1480 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1481 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1482 // have 14 leading zeros, round to 8.
1483 NLZ &= ~7;
1484 NTZ &= ~7;
1485 // If we need exactly one byte, we can do this transformation.
1486 if (BitWidth-NLZ-NTZ == 8) {
1487 unsigned ResultBit = NTZ;
1488 unsigned InputBit = BitWidth-NTZ-8;
1489
1490 // Replace this with either a left or right shift to get the byte into
1491 // the right place.
1492 Instruction *NewVal;
1493 if (InputBit > ResultBit)
1494 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001495 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001496 else
1497 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001498 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001499 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001500 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001501 }
1502
1503 // TODO: Could compute known zero/one bits based on the input.
1504 break;
1505 }
1506 }
1507 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001508 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001509 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001510 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
1512 // If the client is only demanding bits that we know, return the known
1513 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001514 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 return false;
1517}
1518
Chris Lattner867b99f2006-10-05 06:55:50 +00001519
Mon P Wangaeb06d22008-11-10 04:46:22 +00001520/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001521/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001522/// actually used by the caller. This method analyzes which elements of the
1523/// operand are undef and returns that information in UndefElts.
1524///
1525/// If the information about demanded elements can be used to simplify the
1526/// operation, the operation is simplified, then the resultant value is
1527/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001528Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1529 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001532 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001533 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 if (isa<UndefValue>(V)) {
1536 // If the entire vector is undefined, just return this info.
1537 UndefElts = EltMask;
1538 return 0;
1539 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1540 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001541 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001542 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001543
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1546 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001547 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001548
1549 std::vector<Constant*> Elts;
1550 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001551 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001552 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001553 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001554 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1555 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001556 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001557 } else { // Otherwise, defined.
1558 Elts.push_back(CP->getOperand(i));
1559 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001560
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001562 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001563 return NewCP != CP ? NewCP : 0;
1564 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001565 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001566 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001567
1568 // Check if this is identity. If so, return 0 since we are not simplifying
1569 // anything.
1570 if (DemandedElts == ((1ULL << VWidth) -1))
1571 return 0;
1572
Reid Spencer9d6565a2007-02-15 02:26:10 +00001573 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001574 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001575 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001576 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001577 for (unsigned i = 0; i != VWidth; ++i) {
1578 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1579 Elts.push_back(Elt);
1580 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001582 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 }
1584
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 // Limit search depth.
1586 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001587 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588
1589 // If multiple users are using the root value, procede with
1590 // simplification conservatively assuming that all elements
1591 // are needed.
1592 if (!V->hasOneUse()) {
1593 // Quit if we find multiple users of a non-root value though.
1594 // They'll be handled when it's their turn to be visited by
1595 // the main instcombine process.
1596 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001598 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001599
1600 // Conservatively assume that all elements are needed.
1601 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001602 }
1603
1604 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001605 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001606
1607 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001608 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 Value *TmpV;
1610 switch (I->getOpcode()) {
1611 default: break;
1612
1613 case Instruction::InsertElement: {
1614 // If this is a variable index, we don't know which element it overwrites.
1615 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001616 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001617 if (Idx == 0) {
1618 // Note that we can't propagate undef elt info, because we don't know
1619 // which elt is getting updated.
1620 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1621 UndefElts2, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623 break;
1624 }
1625
1626 // If this is inserting an element that isn't demanded, remove this
1627 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001628 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001629 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1630 Worklist.Add(I);
1631 return I->getOperand(0);
1632 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001633
1634 // Otherwise, the element inserted overwrites whatever was there, so the
1635 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001636 APInt DemandedElts2 = DemandedElts;
1637 DemandedElts2.clear(IdxNo);
1638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001639 UndefElts, Depth+1);
1640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
1642 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001643 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001644 break;
1645 }
1646 case Instruction::ShuffleVector: {
1647 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001648 uint64_t LHSVWidth =
1649 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001650 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001651 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001652 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001653 unsigned MaskVal = Shuffle->getMaskValue(i);
1654 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001655 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001656 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001657 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001658 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001659 else
Evan Cheng388df622009-02-03 10:05:09 +00001660 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001661 }
1662 }
1663 }
1664
Nate Begeman7b254672009-02-11 22:36:25 +00001665 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001667 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
Nate Begeman7b254672009-02-11 22:36:25 +00001670 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1672 UndefElts3, Depth+1);
1673 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1674
1675 bool NewUndefElts = false;
1676 for (unsigned i = 0; i < VWidth; i++) {
1677 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001678 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001679 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001680 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001681 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001682 NewUndefElts = true;
1683 UndefElts.set(i);
1684 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001685 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001686 if (UndefElts3[MaskVal - LHSVWidth]) {
1687 NewUndefElts = true;
1688 UndefElts.set(i);
1689 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001690 }
1691 }
1692
1693 if (NewUndefElts) {
1694 // Add additional discovered undefs.
1695 std::vector<Constant*> Elts;
1696 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001697 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001698 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001699 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001700 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001701 Shuffle->getMaskValue(i)));
1702 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001703 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001704 MadeChange = true;
1705 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001706 break;
1707 }
Chris Lattner69878332007-04-14 22:29:23 +00001708 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001709 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001710 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1711 if (!VTy) break;
1712 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001713 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001714 unsigned Ratio;
1715
1716 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001717 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001718 // elements as are demanded of us.
1719 Ratio = 1;
1720 InputDemandedElts = DemandedElts;
1721 } else if (VWidth > InVWidth) {
1722 // Untested so far.
1723 break;
1724
1725 // If there are more elements in the result than there are in the source,
1726 // then an input element is live if any of the corresponding output
1727 // elements are live.
1728 Ratio = VWidth/InVWidth;
1729 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001730 if (DemandedElts[OutIdx])
1731 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001732 }
1733 } else {
1734 // Untested so far.
1735 break;
1736
1737 // If there are more elements in the source than there are in the result,
1738 // then an input element is live if the corresponding output element is
1739 // live.
1740 Ratio = InVWidth/VWidth;
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001742 if (DemandedElts[InIdx/Ratio])
1743 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001744 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001745
Chris Lattner69878332007-04-14 22:29:23 +00001746 // div/rem demand all inputs, because they don't want divide by zero.
1747 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1748 UndefElts2, Depth+1);
1749 if (TmpV) {
1750 I->setOperand(0, TmpV);
1751 MadeChange = true;
1752 }
1753
1754 UndefElts = UndefElts2;
1755 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001756 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001757 // If there are more elements in the result than there are in the source,
1758 // then an output element is undef if the corresponding input element is
1759 // undef.
1760 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001761 if (UndefElts2[OutIdx/Ratio])
1762 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001763 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001764 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001765 // If there are more elements in the source than there are in the result,
1766 // then a result element is undef if all of the corresponding input
1767 // elements are undef.
1768 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1769 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001770 if (!UndefElts2[InIdx]) // Not undef?
1771 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001772 }
1773 break;
1774 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001775 case Instruction::And:
1776 case Instruction::Or:
1777 case Instruction::Xor:
1778 case Instruction::Add:
1779 case Instruction::Sub:
1780 case Instruction::Mul:
1781 // div/rem demand all inputs, because they don't want divide by zero.
1782 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1788
1789 // Output elements are undefined if both are undefined. Consider things
1790 // like undef&0. The result is known zero, not undef.
1791 UndefElts &= UndefElts2;
1792 break;
1793
1794 case Instruction::Call: {
1795 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1796 if (!II) break;
1797 switch (II->getIntrinsicID()) {
1798 default: break;
1799
1800 // Binary vector operations that work column-wise. A dest element is a
1801 // function of the corresponding input elements from the two inputs.
1802 case Intrinsic::x86_sse_sub_ss:
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse_min_ss:
1805 case Intrinsic::x86_sse_max_ss:
1806 case Intrinsic::x86_sse2_sub_sd:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 case Intrinsic::x86_sse2_min_sd:
1809 case Intrinsic::x86_sse2_max_sd:
1810 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1811 UndefElts, Depth+1);
1812 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1813 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1816
1817 // If only the low elt is demanded and this is a scalarizable intrinsic,
1818 // scalarize it now.
1819 if (DemandedElts == 1) {
1820 switch (II->getIntrinsicID()) {
1821 default: break;
1822 case Intrinsic::x86_sse_sub_ss:
1823 case Intrinsic::x86_sse_mul_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
1825 case Intrinsic::x86_sse2_mul_sd:
1826 // TODO: Lower MIN/MAX/ABS/etc
1827 Value *LHS = II->getOperand(1);
1828 Value *RHS = II->getOperand(2);
1829 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001830 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001831 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001832 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001833 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001834
1835 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001836 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 case Intrinsic::x86_sse_sub_ss:
1838 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001839 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 II->getName()), *II);
1841 break;
1842 case Intrinsic::x86_sse_mul_ss:
1843 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001844 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001845 II->getName()), *II);
1846 break;
1847 }
1848
1849 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001850 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001851 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001852 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001854 return New;
1855 }
1856 }
1857
1858 // Output elements are undefined if both are undefined. Consider things
1859 // like undef&0. The result is known zero, not undef.
1860 UndefElts &= UndefElts2;
1861 break;
1862 }
1863 break;
1864 }
1865 }
1866 return MadeChange ? I : 0;
1867}
1868
Dan Gohman45b4e482008-05-19 22:14:15 +00001869
Chris Lattner564a7272003-08-13 19:01:45 +00001870/// AssociativeOpt - Perform an optimization on an associative operator. This
1871/// function is designed to check a chain of associative operators for a
1872/// potential to apply a certain optimization. Since the optimization may be
1873/// applicable if the expression was reassociated, this checks the chain, then
1874/// reassociates the expression as necessary to expose the optimization
1875/// opportunity. This makes use of a special Functor, which must define
1876/// 'shouldApply' and 'apply' methods.
1877///
1878template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001879static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001880 unsigned Opcode = Root.getOpcode();
1881 Value *LHS = Root.getOperand(0);
1882
1883 // Quick check, see if the immediate LHS matches...
1884 if (F.shouldApply(LHS))
1885 return F.apply(Root);
1886
1887 // Otherwise, if the LHS is not of the same opcode as the root, return.
1888 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001889 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001890 // Should we apply this transform to the RHS?
1891 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1892
1893 // If not to the RHS, check to see if we should apply to the LHS...
1894 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1895 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1896 ShouldApply = true;
1897 }
1898
1899 // If the functor wants to apply the optimization to the RHS of LHSI,
1900 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1901 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001902 // Now all of the instructions are in the current basic block, go ahead
1903 // and perform the reassociation.
1904 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1905
1906 // First move the selected RHS to the LHS of the root...
1907 Root.setOperand(0, LHSI->getOperand(1));
1908
1909 // Make what used to be the LHS of the root be the user of the root...
1910 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001911 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001912 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001913 return 0;
1914 }
Chris Lattner65725312004-04-16 18:08:07 +00001915 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001916 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001917 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001918 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001919 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001920
1921 // Now propagate the ExtraOperand down the chain of instructions until we
1922 // get to LHSI.
1923 while (TmpLHSI != LHSI) {
1924 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001925 // Move the instruction to immediately before the chain we are
1926 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001927 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001928 ARI = NextLHSI;
1929
Chris Lattner564a7272003-08-13 19:01:45 +00001930 Value *NextOp = NextLHSI->getOperand(1);
1931 NextLHSI->setOperand(1, ExtraOperand);
1932 TmpLHSI = NextLHSI;
1933 ExtraOperand = NextOp;
1934 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001935
Chris Lattner564a7272003-08-13 19:01:45 +00001936 // Now that the instructions are reassociated, have the functor perform
1937 // the transformation...
1938 return F.apply(Root);
1939 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001940
Chris Lattner564a7272003-08-13 19:01:45 +00001941 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1942 }
1943 return 0;
1944}
1945
Dan Gohman844731a2008-05-13 00:00:25 +00001946namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001947
Nick Lewycky02d639f2008-05-23 04:34:58 +00001948// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001949struct AddRHS {
1950 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001951 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1953 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001954 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001955 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001956 }
1957};
1958
1959// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1960// iff C1&C2 == 0
1961struct AddMaskingAnd {
1962 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001963 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001964 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001965 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001966 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001967 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001968 }
1969 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001970 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001971 }
1972};
1973
Dan Gohman844731a2008-05-13 00:00:25 +00001974}
1975
Chris Lattner6e7ba452005-01-01 16:22:27 +00001976static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001977 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001978 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001979 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001980
Chris Lattner2eefe512004-04-09 19:05:30 +00001981 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001982 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1983 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001984
Chris Lattner2eefe512004-04-09 19:05:30 +00001985 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1986 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001987 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1988 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001989 }
1990
1991 Value *Op0 = SO, *Op1 = ConstOperand;
1992 if (!ConstIsRHS)
1993 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001994
Chris Lattner6e7ba452005-01-01 16:22:27 +00001995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001996 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1997 SO->getName()+".op");
1998 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1999 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2000 SO->getName()+".cmp");
2001 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2002 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2003 SO->getName()+".cmp");
2004 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002005}
2006
2007// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2008// constant as the other operand, try to fold the binary operator into the
2009// select arguments. This also works for Cast instructions, which obviously do
2010// not have a second operand.
2011static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2012 InstCombiner *IC) {
2013 // Don't modify shared select instructions
2014 if (!SI->hasOneUse()) return 0;
2015 Value *TV = SI->getOperand(1);
2016 Value *FV = SI->getOperand(2);
2017
2018 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002019 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002020 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002021
Chris Lattner6e7ba452005-01-01 16:22:27 +00002022 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2023 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2024
Gabor Greif051a9502008-04-06 20:25:17 +00002025 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2026 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002027 }
2028 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002029}
2030
Chris Lattner4e998b22004-09-29 05:07:12 +00002031
Chris Lattner5d1704d2009-09-27 19:57:57 +00002032/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2033/// has a PHI node as operand #0, see if we can fold the instruction into the
2034/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002035///
2036/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2037/// that would normally be unprofitable because they strongly encourage jump
2038/// threading.
2039Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2040 bool AllowAggressive) {
2041 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002042 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002043 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002044 if (NumPHIValues == 0 ||
2045 // We normally only transform phis with a single use, unless we're trying
2046 // hard to make jump threading happen.
2047 (!PN->hasOneUse() && !AllowAggressive))
2048 return 0;
2049
2050
Chris Lattner5d1704d2009-09-27 19:57:57 +00002051 // Check to see if all of the operands of the PHI are simple constants
2052 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002053 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2054 // bail out. We don't do arbitrary constant expressions here because moving
2055 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002056 BasicBlock *NonConstBB = 0;
2057 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002058 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2059 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002060 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002061 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002062 NonConstBB = PN->getIncomingBlock(i);
2063
2064 // If the incoming non-constant value is in I's block, we have an infinite
2065 // loop.
2066 if (NonConstBB == I.getParent())
2067 return 0;
2068 }
2069
2070 // If there is exactly one non-constant value, we can insert a copy of the
2071 // operation in that block. However, if this is a critical edge, we would be
2072 // inserting the computation one some other paths (e.g. inside a loop). Only
2073 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002074 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002075 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2076 if (!BI || !BI->isUnconditional()) return 0;
2077 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002078
2079 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002080 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002081 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002082 InsertNewInstBefore(NewPN, *PN);
2083 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002084
2085 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002086 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2087 // We only currently try to fold the condition of a select when it is a phi,
2088 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002089 Value *TrueV = SI->getTrueValue();
2090 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002091 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002092 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002093 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002094 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2095 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002096 Value *InV = 0;
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002098 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002101 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2102 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002103 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002104 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002105 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002106 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002107 }
2108 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002109 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002111 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002113 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002114 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002115 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002116 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002117 } else {
2118 assert(PN->getIncomingBlock(i) == NonConstBB);
2119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002120 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002121 PN->getIncomingValue(i), C, "phitmp",
2122 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002123 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002124 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002125 CI->getPredicate(),
2126 PN->getIncomingValue(i), C, "phitmp",
2127 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002129 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002130
2131 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002132 }
2133 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002134 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002135 } else {
2136 CastInst *CI = cast<CastInst>(&I);
2137 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002138 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002139 Value *InV;
2140 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002141 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002142 } else {
2143 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002144 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002145 I.getType(), "phitmp",
2146 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002147 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002148 }
2149 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002150 }
2151 }
2152 return ReplaceInstUsesWith(I, NewPN);
2153}
2154
Chris Lattner2454a2e2008-01-29 06:52:45 +00002155
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002156/// WillNotOverflowSignedAdd - Return true if we can prove that:
2157/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2158/// This basically requires proving that the add in the original type would not
2159/// overflow to change the sign bit or have a carry out.
2160bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2161 // There are different heuristics we can use for this. Here are some simple
2162 // ones.
2163
2164 // Add has the property that adding any two 2's complement numbers can only
2165 // have one carry bit which can change a sign. As such, if LHS and RHS each
2166 // have at least two sign bits, we know that the addition of the two values will
2167 // sign extend fine.
2168 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2169 return true;
2170
2171
2172 // If one of the operands only has one non-zero bit, and if the other operand
2173 // has a known-zero bit in a more significant place than it (not including the
2174 // sign bit) the ripple may go up to and fill the zero, but won't change the
2175 // sign. For example, (X & ~4) + 1.
2176
2177 // TODO: Implement.
2178
2179 return false;
2180}
2181
Chris Lattner2454a2e2008-01-29 06:52:45 +00002182
Chris Lattner7e708292002-06-25 16:13:24 +00002183Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002184 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002185 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002186
Chris Lattner66331a42004-04-10 22:01:55 +00002187 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002188 // X + undef -> undef
2189 if (isa<UndefValue>(RHS))
2190 return ReplaceInstUsesWith(I, RHS);
2191
Chris Lattner66331a42004-04-10 22:01:55 +00002192 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002193 if (RHSC->isNullValue())
2194 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002195
Chris Lattner66331a42004-04-10 22:01:55 +00002196 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002197 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002198 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002199 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002200 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002201 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002202
2203 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2204 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002205 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002206 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002207
Eli Friedman709b33d2009-07-13 22:27:52 +00002208 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002209 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002210 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002211 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002212 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002213
2214 if (isa<PHINode>(LHS))
2215 if (Instruction *NV = FoldOpIntoPhi(I))
2216 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002217
Chris Lattner4f637d42006-01-06 17:59:59 +00002218 ConstantInt *XorRHS = 0;
2219 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002220 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002221 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002222 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002223 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002224
Zhou Sheng4351c642007-04-02 08:20:41 +00002225 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002226 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2227 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002228 do {
2229 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002230 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2231 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002232 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2233 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002234 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002235 if (!MaskedValueIsZero(XorLHS,
2236 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002237 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002238 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002239 }
2240 }
2241 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002242 C0080Val = APIntOps::lshr(C0080Val, Size);
2243 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2244 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002245
Reid Spencer35c38852007-03-28 01:36:16 +00002246 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002247 // with funny bit widths then this switch statement should be removed. It
2248 // is just here to get the size of the "middle" type back up to something
2249 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002250 const Type *MiddleType = 0;
2251 switch (Size) {
2252 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002253 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2254 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2255 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002256 }
2257 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002258 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002259 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002260 }
2261 }
Chris Lattner66331a42004-04-10 22:01:55 +00002262 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002263
Owen Anderson1d0be152009-08-13 21:58:54 +00002264 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002265 return BinaryOperator::CreateXor(LHS, RHS);
2266
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002267 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002268 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002269 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002270 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002271
2272 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2273 if (RHSI->getOpcode() == Instruction::Sub)
2274 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2275 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2276 }
2277 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2278 if (LHSI->getOpcode() == Instruction::Sub)
2279 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2280 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2281 }
Robert Bocchino71698282004-07-27 21:02:21 +00002282 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002283
Chris Lattner5c4afb92002-05-08 22:46:53 +00002284 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002285 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002286 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002287 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002288 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002289 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002290 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002291 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002292 }
2293
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002294 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002295 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002296
2297 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002298 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002299 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002300 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002301
Misha Brukmanfd939082005-04-21 23:48:37 +00002302
Chris Lattner50af16a2004-11-13 19:50:12 +00002303 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002304 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002305 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002306 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002307
2308 // X*C1 + X*C2 --> X * (C1+C2)
2309 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002310 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002311 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002312 }
2313
2314 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002315 if (dyn_castFoldableMul(RHS, C2) == LHS)
2316 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002317
Chris Lattnere617c9e2007-01-05 02:17:46 +00002318 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002319 if (dyn_castNotVal(LHS) == RHS ||
2320 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002321 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002322
Chris Lattnerad3448c2003-02-18 19:57:07 +00002323
Chris Lattner564a7272003-08-13 19:01:45 +00002324 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002325 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2326 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002327 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002328
2329 // A+B --> A|B iff A and B have no bits set in common.
2330 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2331 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2332 APInt LHSKnownOne(IT->getBitWidth(), 0);
2333 APInt LHSKnownZero(IT->getBitWidth(), 0);
2334 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2335 if (LHSKnownZero != 0) {
2336 APInt RHSKnownOne(IT->getBitWidth(), 0);
2337 APInt RHSKnownZero(IT->getBitWidth(), 0);
2338 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2339
2340 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002341 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002342 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002343 }
2344 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002345
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002346 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002347 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002348 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002349 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2350 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002351 if (W != Y) {
2352 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002353 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002354 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002355 std::swap(W, X);
2356 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002357 std::swap(Y, Z);
2358 std::swap(W, X);
2359 }
2360 }
2361
2362 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002363 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002365 }
2366 }
2367 }
2368
Chris Lattner6b032052003-10-02 15:11:26 +00002369 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002370 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002371 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002372 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002373
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002374 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002375 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002376 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002377 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002378 if (Anded == CRHS) {
2379 // See if all bits from the first bit set in the Add RHS up are included
2380 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002381 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002382
2383 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002384 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002385
2386 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002387 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002388
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002389 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2390 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002391 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002392 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002393 }
2394 }
2395 }
2396
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002397 // Try to fold constant add into select arguments.
2398 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002399 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002400 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002401 }
2402
Chris Lattner42790482007-12-20 01:56:58 +00002403 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002404 {
2405 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002406 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002407 if (!SI) {
2408 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002409 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002410 }
Chris Lattner42790482007-12-20 01:56:58 +00002411 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002412 Value *TV = SI->getTrueValue();
2413 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002414 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002415
2416 // Can we fold the add into the argument of the select?
2417 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002418 if (match(FV, m_Zero()) &&
2419 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002420 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002421 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002422 if (match(TV, m_Zero()) &&
2423 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002424 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002425 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002426 }
2427 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002428
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002429 // Check for (add (sext x), y), see if we can merge this into an
2430 // integer add followed by a sext.
2431 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2432 // (add (sext x), cst) --> (sext (add x, cst'))
2433 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2434 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002435 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002436 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002437 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002438 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2439 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002440 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2441 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002442 return new SExtInst(NewAdd, I.getType());
2443 }
2444 }
2445
2446 // (add (sext x), (sext y)) --> (sext (add int x, y))
2447 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2448 // Only do this if x/y have the same type, if at last one of them has a
2449 // single use (so we don't increase the number of sexts), and if the
2450 // integer add will not overflow.
2451 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2452 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2453 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2454 RHSConv->getOperand(0))) {
2455 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002456 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2457 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002458 return new SExtInst(NewAdd, I.getType());
2459 }
2460 }
2461 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002462
2463 return Changed ? &I : 0;
2464}
2465
2466Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2467 bool Changed = SimplifyCommutative(I);
2468 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2469
2470 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2471 // X + 0 --> X
2472 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002473 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002474 (I.getType())->getValueAPF()))
2475 return ReplaceInstUsesWith(I, LHS);
2476 }
2477
2478 if (isa<PHINode>(LHS))
2479 if (Instruction *NV = FoldOpIntoPhi(I))
2480 return NV;
2481 }
2482
2483 // -A + B --> B - A
2484 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002485 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002486 return BinaryOperator::CreateFSub(RHS, LHSV);
2487
2488 // A + -B --> A - B
2489 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002490 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002491 return BinaryOperator::CreateFSub(LHS, V);
2492
2493 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2494 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2495 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2496 return ReplaceInstUsesWith(I, LHS);
2497
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002498 // Check for (add double (sitofp x), y), see if we can merge this into an
2499 // integer add followed by a promotion.
2500 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2501 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2502 // ... if the constant fits in the integer value. This is useful for things
2503 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2504 // requires a constant pool load, and generally allows the add to be better
2505 // instcombined.
2506 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2507 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002508 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002509 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002510 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002511 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2512 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002513 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2514 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002515 return new SIToFPInst(NewAdd, I.getType());
2516 }
2517 }
2518
2519 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2520 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2521 // Only do this if x/y have the same type, if at last one of them has a
2522 // single use (so we don't increase the number of int->fp conversions),
2523 // and if the integer add will not overflow.
2524 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2525 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2526 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2527 RHSConv->getOperand(0))) {
2528 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002529 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002530 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002531 return new SIToFPInst(NewAdd, I.getType());
2532 }
2533 }
2534 }
2535
Chris Lattner7e708292002-06-25 16:13:24 +00002536 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002537}
2538
Chris Lattner092543c2009-11-04 08:05:20 +00002539
2540/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2541/// code necessary to compute the offset from the base pointer (without adding
2542/// in the base pointer). Return the result as a signed integer of intptr size.
2543static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2544 TargetData &TD = *IC.getTargetData();
2545 gep_type_iterator GTI = gep_type_begin(GEP);
2546 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2547 Value *Result = Constant::getNullValue(IntPtrTy);
2548
2549 // Build a mask for high order bits.
2550 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2551 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2552
2553 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2554 ++i, ++GTI) {
2555 Value *Op = *i;
2556 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2557 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2558 if (OpC->isZero()) continue;
2559
2560 // Handle a struct index, which adds its field offset to the pointer.
2561 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2562 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2563
2564 Result = IC.Builder->CreateAdd(Result,
2565 ConstantInt::get(IntPtrTy, Size),
2566 GEP->getName()+".offs");
2567 continue;
2568 }
2569
2570 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2571 Constant *OC =
2572 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2573 Scale = ConstantExpr::getMul(OC, Scale);
2574 // Emit an add instruction.
2575 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2576 continue;
2577 }
2578 // Convert to correct type.
2579 if (Op->getType() != IntPtrTy)
2580 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2581 if (Size != 1) {
2582 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2583 // We'll let instcombine(mul) convert this to a shl if possible.
2584 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2585 }
2586
2587 // Emit an add instruction.
2588 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2589 }
2590 return Result;
2591}
2592
2593
2594/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2595/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2596/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2597/// be complex, and scales are involved. The above expression would also be
2598/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2599/// This later form is less amenable to optimization though, and we are allowed
2600/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2601///
2602/// If we can't emit an optimized form for this expression, this returns null.
2603///
2604static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2605 InstCombiner &IC) {
2606 TargetData &TD = *IC.getTargetData();
2607 gep_type_iterator GTI = gep_type_begin(GEP);
2608
2609 // Check to see if this gep only has a single variable index. If so, and if
2610 // any constant indices are a multiple of its scale, then we can compute this
2611 // in terms of the scale of the variable index. For example, if the GEP
2612 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2613 // because the expression will cross zero at the same point.
2614 unsigned i, e = GEP->getNumOperands();
2615 int64_t Offset = 0;
2616 for (i = 1; i != e; ++i, ++GTI) {
2617 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2618 // Compute the aggregate offset of constant indices.
2619 if (CI->isZero()) continue;
2620
2621 // Handle a struct index, which adds its field offset to the pointer.
2622 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2623 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2624 } else {
2625 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2626 Offset += Size*CI->getSExtValue();
2627 }
2628 } else {
2629 // Found our variable index.
2630 break;
2631 }
2632 }
2633
2634 // If there are no variable indices, we must have a constant offset, just
2635 // evaluate it the general way.
2636 if (i == e) return 0;
2637
2638 Value *VariableIdx = GEP->getOperand(i);
2639 // Determine the scale factor of the variable element. For example, this is
2640 // 4 if the variable index is into an array of i32.
2641 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2642
2643 // Verify that there are no other variable indices. If so, emit the hard way.
2644 for (++i, ++GTI; i != e; ++i, ++GTI) {
2645 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2646 if (!CI) return 0;
2647
2648 // Compute the aggregate offset of constant indices.
2649 if (CI->isZero()) continue;
2650
2651 // Handle a struct index, which adds its field offset to the pointer.
2652 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2653 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2654 } else {
2655 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2656 Offset += Size*CI->getSExtValue();
2657 }
2658 }
2659
2660 // Okay, we know we have a single variable index, which must be a
2661 // pointer/array/vector index. If there is no offset, life is simple, return
2662 // the index.
2663 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2664 if (Offset == 0) {
2665 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2666 // we don't need to bother extending: the extension won't affect where the
2667 // computation crosses zero.
2668 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2669 VariableIdx = new TruncInst(VariableIdx,
2670 TD.getIntPtrType(VariableIdx->getContext()),
2671 VariableIdx->getName(), &I);
2672 return VariableIdx;
2673 }
2674
2675 // Otherwise, there is an index. The computation we will do will be modulo
2676 // the pointer size, so get it.
2677 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2678
2679 Offset &= PtrSizeMask;
2680 VariableScale &= PtrSizeMask;
2681
2682 // To do this transformation, any constant index must be a multiple of the
2683 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2684 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2685 // multiple of the variable scale.
2686 int64_t NewOffs = Offset / (int64_t)VariableScale;
2687 if (Offset != NewOffs*(int64_t)VariableScale)
2688 return 0;
2689
2690 // Okay, we can do this evaluation. Start by converting the index to intptr.
2691 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2692 if (VariableIdx->getType() != IntPtrTy)
2693 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2694 true /*SExt*/,
2695 VariableIdx->getName(), &I);
2696 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2697 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2698}
2699
2700
2701/// Optimize pointer differences into the same array into a size. Consider:
2702/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2703/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2704///
2705Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2706 const Type *Ty) {
2707 assert(TD && "Must have target data info for this");
2708
2709 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2710 // this.
2711 bool Swapped;
2712 GetElementPtrInst *GEP;
2713
2714 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2715 GEP->getOperand(0) == RHS)
2716 Swapped = false;
2717 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2718 GEP->getOperand(0) == LHS)
2719 Swapped = true;
2720 else
2721 return 0;
2722
2723 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2724
2725 // Emit the offset of the GEP and an intptr_t.
2726 Value *Result = EmitGEPOffset(GEP, *this);
2727
2728 // If we have p - gep(p, ...) then we have to negate the result.
2729 if (Swapped)
2730 Result = Builder->CreateNeg(Result, "diff.neg");
2731
2732 return Builder->CreateIntCast(Result, Ty, true);
2733}
2734
2735
Chris Lattner7e708292002-06-25 16:13:24 +00002736Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002738
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002739 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002740 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002741
Chris Lattner092543c2009-11-04 08:05:20 +00002742 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002743 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002744 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002745
Chris Lattnere87597f2004-10-16 18:11:37 +00002746 if (isa<UndefValue>(Op0))
2747 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2748 if (isa<UndefValue>(Op1))
2749 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002750 if (I.getType() == Type::getInt1Ty(*Context))
2751 return BinaryOperator::CreateXor(Op0, Op1);
2752
Chris Lattnerd65460f2003-11-05 01:06:05 +00002753 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002754 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002755 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002756 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002757
Chris Lattnerd65460f2003-11-05 01:06:05 +00002758 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002759 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002760 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002761 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002762
Chris Lattner76b7a062007-01-15 07:02:54 +00002763 // -(X >>u 31) -> (X >>s 31)
2764 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002765 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002766 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002767 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002768 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002769 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002770 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002771 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002772 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002773 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002774 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002775 }
2776 }
Chris Lattner092543c2009-11-04 08:05:20 +00002777 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002778 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2779 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002780 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002781 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002782 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002784 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002785 }
2786 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002787 }
2788 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002789 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002790
2791 // Try to fold constant sub into select arguments.
2792 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002793 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002794 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002795
2796 // C - zext(bool) -> bool ? C - 1 : C
2797 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002798 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002799 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002800 }
2801
Chris Lattner43d84d62005-04-07 16:15:25 +00002802 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002803 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002804 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002805 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002806 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002807 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002808 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002809 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002810 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2811 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2812 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002813 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002814 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002815 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002816 }
2817
Chris Lattnerfd059242003-10-15 16:48:29 +00002818 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002819 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2820 // is not used by anyone else...
2821 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002822 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002823 // Swap the two operands of the subexpr...
2824 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2825 Op1I->setOperand(0, IIOp1);
2826 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002827
Chris Lattnera2881962003-02-18 19:28:33 +00002828 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002829 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002830 }
2831
2832 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2833 //
2834 if (Op1I->getOpcode() == Instruction::And &&
2835 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2836 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2837
Chris Lattner74381062009-08-30 07:44:24 +00002838 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002839 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002840 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002841
Reid Spencerac5209e2006-10-16 23:08:08 +00002842 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002843 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002844 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002845 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002846 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002847 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002848 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002849
Chris Lattnerad3448c2003-02-18 19:57:07 +00002850 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002851 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002852 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002853 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002854 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002855 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002856 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002857 }
Chris Lattner40371712002-05-09 01:29:19 +00002858 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002859 }
Chris Lattnera2881962003-02-18 19:28:33 +00002860
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002861 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2862 if (Op0I->getOpcode() == Instruction::Add) {
2863 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2864 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2865 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2866 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2867 } else if (Op0I->getOpcode() == Instruction::Sub) {
2868 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002869 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002870 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002871 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002872 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002873
Chris Lattner50af16a2004-11-13 19:50:12 +00002874 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002875 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002876 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002877 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002878
Chris Lattner50af16a2004-11-13 19:50:12 +00002879 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002880 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002881 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002882 }
Chris Lattner092543c2009-11-04 08:05:20 +00002883
2884 // Optimize pointer differences into the same array into a size. Consider:
2885 // &A[10] - &A[0]: we should compile this to "10".
2886 if (TD) {
2887 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2888 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2889 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2890 RHS->getOperand(0),
2891 I.getType()))
2892 return ReplaceInstUsesWith(I, Res);
2893
2894 // trunc(p)-trunc(q) -> trunc(p-q)
2895 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2896 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2897 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2898 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2899 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2900 RHS->getOperand(0),
2901 I.getType()))
2902 return ReplaceInstUsesWith(I, Res);
2903 }
2904
Chris Lattner3f5b8772002-05-06 16:14:14 +00002905 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002906}
2907
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002908Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2909 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2910
2911 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002912 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002913 return BinaryOperator::CreateFAdd(Op0, V);
2914
2915 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2916 if (Op1I->getOpcode() == Instruction::FAdd) {
2917 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002918 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002919 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002920 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002921 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002922 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002923 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002924 }
2925
2926 return 0;
2927}
2928
Chris Lattnera0141b92007-07-15 20:42:37 +00002929/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2930/// comparison only checks the sign bit. If it only checks the sign bit, set
2931/// TrueIfSigned if the result of the comparison is true when the input value is
2932/// signed.
2933static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2934 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002935 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002936 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2937 TrueIfSigned = true;
2938 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002939 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2940 TrueIfSigned = true;
2941 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002942 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2943 TrueIfSigned = false;
2944 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002945 case ICmpInst::ICMP_UGT:
2946 // True if LHS u> RHS and RHS == high-bit-mask - 1
2947 TrueIfSigned = true;
2948 return RHS->getValue() ==
2949 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2950 case ICmpInst::ICMP_UGE:
2951 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2952 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002953 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002954 default:
2955 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002956 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002957}
2958
Chris Lattner7e708292002-06-25 16:13:24 +00002959Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002960 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002962
Chris Lattnera2498472009-10-11 21:36:10 +00002963 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002965
Chris Lattner8af304a2009-10-11 07:53:15 +00002966 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002967 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2968 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002969
2970 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002971 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002972 if (SI->getOpcode() == Instruction::Shl)
2973 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002974 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002975 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002976
Zhou Sheng843f07672007-04-19 05:39:12 +00002977 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002978 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002979 if (CI->equalsInt(1)) // X * 1 == X
2980 return ReplaceInstUsesWith(I, Op0);
2981 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002982 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002983
Zhou Sheng97b52c22007-03-29 01:57:21 +00002984 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002985 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002987 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002988 }
Chris Lattnera2498472009-10-11 21:36:10 +00002989 } else if (isa<VectorType>(Op1C->getType())) {
2990 if (Op1C->isNullValue())
2991 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002992
Chris Lattnera2498472009-10-11 21:36:10 +00002993 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002994 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002995 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002996
2997 // As above, vector X*splat(1.0) -> X in all defined cases.
2998 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002999 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3000 if (CI->equalsInt(1))
3001 return ReplaceInstUsesWith(I, Op0);
3002 }
3003 }
Chris Lattnera2881962003-02-18 19:28:33 +00003004 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003005
3006 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3007 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003008 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003009 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003010 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3011 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003012 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003013
3014 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003015
3016 // Try to fold constant mul into select arguments.
3017 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003018 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003019 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003020
3021 if (isa<PHINode>(Op0))
3022 if (Instruction *NV = FoldOpIntoPhi(I))
3023 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003024 }
3025
Dan Gohman186a6362009-08-12 16:04:34 +00003026 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003027 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003029
Nick Lewycky0c730792008-11-21 07:33:58 +00003030 // (X / Y) * Y = X - (X % Y)
3031 // (X / Y) * -Y = (X % Y) - X
3032 {
Chris Lattnera2498472009-10-11 21:36:10 +00003033 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003034 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3035 if (!BO ||
3036 (BO->getOpcode() != Instruction::UDiv &&
3037 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003038 Op1C = Op0;
3039 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003040 }
Chris Lattnera2498472009-10-11 21:36:10 +00003041 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003042 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003043 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003044 (BO->getOpcode() == Instruction::UDiv ||
3045 BO->getOpcode() == Instruction::SDiv)) {
3046 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3047
Dan Gohmanfa94b942009-08-12 16:33:09 +00003048 // If the division is exact, X % Y is zero.
3049 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3050 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003051 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003052 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003053 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003054 }
3055
Chris Lattner74381062009-08-30 07:44:24 +00003056 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003057 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003058 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003059 else
Chris Lattner74381062009-08-30 07:44:24 +00003060 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003061 Rem->takeName(BO);
3062
Chris Lattnera2498472009-10-11 21:36:10 +00003063 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003064 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003065 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003066 }
3067 }
3068
Chris Lattner8af304a2009-10-11 07:53:15 +00003069 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003070 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003071 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003072
Chris Lattner8af304a2009-10-11 07:53:15 +00003073 // X*(1 << Y) --> X << Y
3074 // (1 << Y)*X --> X << Y
3075 {
3076 Value *Y;
3077 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003078 return BinaryOperator::CreateShl(Op1, Y);
3079 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003080 return BinaryOperator::CreateShl(Op0, Y);
3081 }
3082
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003083 // If one of the operands of the multiply is a cast from a boolean value, then
3084 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003085 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3086 if (!isa<VectorType>(I.getType())) {
3087 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003088 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003089
Chris Lattnerd2c58362009-10-11 21:29:45 +00003090 Value *BoolCast = 0, *OtherOp = 0;
3091 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003092 BoolCast = Op0, OtherOp = Op1;
3093 else if (MaskedValueIsZero(Op1, Negative2))
3094 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003095
Chris Lattner0036e3a2009-10-11 21:22:21 +00003096 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003097 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3098 BoolCast, "tmp");
3099 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003100 }
3101 }
3102
Chris Lattner7e708292002-06-25 16:13:24 +00003103 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003104}
3105
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003106Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3107 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003108 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003109
3110 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003111 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3112 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003113 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3114 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3115 if (Op1F->isExactlyValue(1.0))
3116 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003117 } else if (isa<VectorType>(Op1C->getType())) {
3118 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003119 // As above, vector X*splat(1.0) -> X in all defined cases.
3120 if (Constant *Splat = Op1V->getSplatValue()) {
3121 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3122 if (F->isExactlyValue(1.0))
3123 return ReplaceInstUsesWith(I, Op0);
3124 }
3125 }
3126 }
3127
3128 // Try to fold constant mul into select arguments.
3129 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3130 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3131 return R;
3132
3133 if (isa<PHINode>(Op0))
3134 if (Instruction *NV = FoldOpIntoPhi(I))
3135 return NV;
3136 }
3137
Dan Gohman186a6362009-08-12 16:04:34 +00003138 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003139 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003140 return BinaryOperator::CreateFMul(Op0v, Op1v);
3141
3142 return Changed ? &I : 0;
3143}
3144
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003145/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3146/// instruction.
3147bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3148 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3149
3150 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3151 int NonNullOperand = -1;
3152 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3153 if (ST->isNullValue())
3154 NonNullOperand = 2;
3155 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3156 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3157 if (ST->isNullValue())
3158 NonNullOperand = 1;
3159
3160 if (NonNullOperand == -1)
3161 return false;
3162
3163 Value *SelectCond = SI->getOperand(0);
3164
3165 // Change the div/rem to use 'Y' instead of the select.
3166 I.setOperand(1, SI->getOperand(NonNullOperand));
3167
3168 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3169 // problem. However, the select, or the condition of the select may have
3170 // multiple uses. Based on our knowledge that the operand must be non-zero,
3171 // propagate the known value for the select into other uses of it, and
3172 // propagate a known value of the condition into its other users.
3173
3174 // If the select and condition only have a single use, don't bother with this,
3175 // early exit.
3176 if (SI->use_empty() && SelectCond->hasOneUse())
3177 return true;
3178
3179 // Scan the current block backward, looking for other uses of SI.
3180 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3181
3182 while (BBI != BBFront) {
3183 --BBI;
3184 // If we found a call to a function, we can't assume it will return, so
3185 // information from below it cannot be propagated above it.
3186 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3187 break;
3188
3189 // Replace uses of the select or its condition with the known values.
3190 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3191 I != E; ++I) {
3192 if (*I == SI) {
3193 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003194 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003195 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003196 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3197 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003198 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003199 }
3200 }
3201
3202 // If we past the instruction, quit looking for it.
3203 if (&*BBI == SI)
3204 SI = 0;
3205 if (&*BBI == SelectCond)
3206 SelectCond = 0;
3207
3208 // If we ran out of things to eliminate, break out of the loop.
3209 if (SelectCond == 0 && SI == 0)
3210 break;
3211
3212 }
3213 return true;
3214}
3215
3216
Reid Spencer1628cec2006-10-26 06:15:43 +00003217/// This function implements the transforms on div instructions that work
3218/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3219/// used by the visitors to those instructions.
3220/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003221Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003223
Chris Lattner50b2ca42008-02-19 06:12:18 +00003224 // undef / X -> 0 for integer.
3225 // undef / X -> undef for FP (the undef could be a snan).
3226 if (isa<UndefValue>(Op0)) {
3227 if (Op0->getType()->isFPOrFPVector())
3228 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003229 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003230 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003231
3232 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003233 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003234 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003235
Reid Spencer1628cec2006-10-26 06:15:43 +00003236 return 0;
3237}
Misha Brukmanfd939082005-04-21 23:48:37 +00003238
Reid Spencer1628cec2006-10-26 06:15:43 +00003239/// This function implements the transforms common to both integer division
3240/// instructions (udiv and sdiv). It is called by the visitors to those integer
3241/// division instructions.
3242/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003243Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003244 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3245
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003246 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003247 if (Op0 == Op1) {
3248 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003249 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003250 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003251 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003252 }
3253
Owen Andersoneed707b2009-07-24 23:12:02 +00003254 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003255 return ReplaceInstUsesWith(I, CI);
3256 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003257
Reid Spencer1628cec2006-10-26 06:15:43 +00003258 if (Instruction *Common = commonDivTransforms(I))
3259 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003260
3261 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3262 // This does not apply for fdiv.
3263 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3264 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003265
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3267 // div X, 1 == X
3268 if (RHS->equalsInt(1))
3269 return ReplaceInstUsesWith(I, Op0);
3270
3271 // (X / C1) / C2 -> X / (C1*C2)
3272 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3273 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3274 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003275 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003276 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003277 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003278 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003279 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003280 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003281 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003282
Reid Spencerbca0e382007-03-23 20:05:17 +00003283 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003284 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3285 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3286 return R;
3287 if (isa<PHINode>(Op0))
3288 if (Instruction *NV = FoldOpIntoPhi(I))
3289 return NV;
3290 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003291 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003292
Chris Lattnera2881962003-02-18 19:28:33 +00003293 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003294 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003295 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003297
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003298 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003299 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003300 return ReplaceInstUsesWith(I, Op0);
3301
Nick Lewycky895f0852008-11-27 20:21:08 +00003302 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3303 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3304 // div X, 1 == X
3305 if (X->isOne())
3306 return ReplaceInstUsesWith(I, Op0);
3307 }
3308
Reid Spencer1628cec2006-10-26 06:15:43 +00003309 return 0;
3310}
3311
3312Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3313 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3314
3315 // Handle the integer div common cases
3316 if (Instruction *Common = commonIDivTransforms(I))
3317 return Common;
3318
Reid Spencer1628cec2006-10-26 06:15:43 +00003319 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003320 // X udiv C^2 -> X >> C
3321 // Check to see if this is an unsigned division with an exact power of 2,
3322 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003323 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003324 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003325 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003326
3327 // X udiv C, where C >= signbit
3328 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003329 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003330 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003331 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003332 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003333 }
3334
3335 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003336 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003337 if (RHSI->getOpcode() == Instruction::Shl &&
3338 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003339 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003340 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003341 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003342 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003343 if (uint32_t C2 = C1.logBase2())
3344 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003345 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003346 }
3347 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003348 }
3349
Reid Spencer1628cec2006-10-26 06:15:43 +00003350 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3351 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003352 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003353 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003354 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003355 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003356 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003357 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003358 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003359 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003360 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003361 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003362
3363 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003364 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003365 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003366
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003367 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003368 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003369 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003370 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003371 return 0;
3372}
3373
Reid Spencer1628cec2006-10-26 06:15:43 +00003374Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3376
3377 // Handle the integer div common cases
3378 if (Instruction *Common = commonIDivTransforms(I))
3379 return Common;
3380
3381 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3382 // sdiv X, -1 == -X
3383 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003384 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003385
Dan Gohmanfa94b942009-08-12 16:33:09 +00003386 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003387 if (cast<SDivOperator>(&I)->isExact() &&
3388 RHS->getValue().isNonNegative() &&
3389 RHS->getValue().isPowerOf2()) {
3390 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3391 RHS->getValue().exactLogBase2());
3392 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3393 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003394
3395 // -X/C --> X/-C provided the negation doesn't overflow.
3396 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3397 if (isa<Constant>(Sub->getOperand(0)) &&
3398 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003399 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003400 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3401 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003402 }
3403
3404 // If the sign bits of both operands are zero (i.e. we can prove they are
3405 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003406 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003407 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003408 if (MaskedValueIsZero(Op0, Mask)) {
3409 if (MaskedValueIsZero(Op1, Mask)) {
3410 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3411 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3412 }
3413 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003414 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003415 ShiftedInt->getValue().isPowerOf2()) {
3416 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3417 // Safe because the only negative value (1 << Y) can take on is
3418 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3419 // the sign bit set.
3420 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3421 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003422 }
Eli Friedman8be17392009-07-18 09:53:21 +00003423 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003424
3425 return 0;
3426}
3427
3428Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3429 return commonDivTransforms(I);
3430}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003431
Reid Spencer0a783f72006-11-02 01:53:59 +00003432/// This function implements the transforms on rem instructions that work
3433/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3434/// is used by the visitors to those instructions.
3435/// @brief Transforms common to all three rem instructions
3436Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003438
Chris Lattner50b2ca42008-02-19 06:12:18 +00003439 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3440 if (I.getType()->isFPOrFPVector())
3441 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003442 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003443 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003444 if (isa<UndefValue>(Op1))
3445 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003446
3447 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003448 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3449 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003450
Reid Spencer0a783f72006-11-02 01:53:59 +00003451 return 0;
3452}
3453
3454/// This function implements the transforms common to both integer remainder
3455/// instructions (urem and srem). It is called by the visitors to those integer
3456/// remainder instructions.
3457/// @brief Common integer remainder transforms
3458Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3459 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3460
3461 if (Instruction *common = commonRemTransforms(I))
3462 return common;
3463
Dale Johannesened6af242009-01-21 00:35:19 +00003464 // 0 % X == 0 for integer, we don't need to preserve faults!
3465 if (Constant *LHS = dyn_cast<Constant>(Op0))
3466 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003467 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003468
Chris Lattner857e8cd2004-12-12 21:48:58 +00003469 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003470 // X % 0 == undef, we don't need to preserve faults!
3471 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003472 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003473
Chris Lattnera2881962003-02-18 19:28:33 +00003474 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003475 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003476
Chris Lattner97943922006-02-28 05:49:21 +00003477 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3480 return R;
3481 } else if (isa<PHINode>(Op0I)) {
3482 if (Instruction *NV = FoldOpIntoPhi(I))
3483 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003484 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003485
3486 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003487 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003488 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003489 }
Chris Lattnera2881962003-02-18 19:28:33 +00003490 }
3491
Reid Spencer0a783f72006-11-02 01:53:59 +00003492 return 0;
3493}
3494
3495Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3496 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3497
3498 if (Instruction *common = commonIRemTransforms(I))
3499 return common;
3500
3501 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3502 // X urem C^2 -> X and C
3503 // Check to see if this is an unsigned remainder with an exact power of 2,
3504 // if so, convert to a bitwise and.
3505 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003506 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003507 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003508 }
3509
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003510 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003511 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3512 if (RHSI->getOpcode() == Instruction::Shl &&
3513 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003514 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003515 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003516 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003518 }
3519 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003520 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003521
Reid Spencer0a783f72006-11-02 01:53:59 +00003522 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3523 // where C1&C2 are powers of two.
3524 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3525 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3526 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3527 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003528 if ((STO->getValue().isPowerOf2()) &&
3529 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003530 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3531 SI->getName()+".t");
3532 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3533 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003534 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003535 }
3536 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003537 }
3538
Chris Lattner3f5b8772002-05-06 16:14:14 +00003539 return 0;
3540}
3541
Reid Spencer0a783f72006-11-02 01:53:59 +00003542Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3544
Dan Gohmancff55092007-11-05 23:16:33 +00003545 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003546 if (Instruction *Common = commonIRemTransforms(I))
3547 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003548
Dan Gohman186a6362009-08-12 16:04:34 +00003549 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003550 if (!isa<Constant>(RHSNeg) ||
3551 (isa<ConstantInt>(RHSNeg) &&
3552 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003553 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003554 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003555 I.setOperand(1, RHSNeg);
3556 return &I;
3557 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003558
Dan Gohmancff55092007-11-05 23:16:33 +00003559 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003560 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003561 if (I.getType()->isInteger()) {
3562 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3563 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3564 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003566 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003567 }
3568
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003569 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003570 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3571 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003572
Nick Lewycky9dce8732008-12-20 16:48:00 +00003573 bool hasNegative = false;
3574 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3575 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3576 if (RHS->getValue().isNegative())
3577 hasNegative = true;
3578
3579 if (hasNegative) {
3580 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003581 for (unsigned i = 0; i != VWidth; ++i) {
3582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3583 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003584 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003585 else
3586 Elts[i] = RHS;
3587 }
3588 }
3589
Owen Andersonaf7ec972009-07-28 21:19:26 +00003590 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003591 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003592 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003593 I.setOperand(1, NewRHSV);
3594 return &I;
3595 }
3596 }
3597 }
3598
Reid Spencer0a783f72006-11-02 01:53:59 +00003599 return 0;
3600}
3601
3602Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003603 return commonRemTransforms(I);
3604}
3605
Chris Lattner457dd822004-06-09 07:59:58 +00003606// isOneBitSet - Return true if there is exactly one bit set in the specified
3607// constant.
3608static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003609 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003610}
3611
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003612// isHighOnes - Return true if the constant is of the form 1+0+.
3613// This is the same as lowones(~X).
3614static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003615 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003616}
3617
Reid Spencere4d87aa2006-12-23 06:05:41 +00003618/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003619/// are carefully arranged to allow folding of expressions such as:
3620///
3621/// (A < B) | (A > B) --> (A != B)
3622///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003623/// Note that this is only valid if the first and second predicates have the
3624/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003625///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626/// Three bits are used to represent the condition, as follows:
3627/// 0 A > B
3628/// 1 A == B
3629/// 2 A < B
3630///
3631/// <=> Value Definition
3632/// 000 0 Always false
3633/// 001 1 A > B
3634/// 010 2 A == B
3635/// 011 3 A >= B
3636/// 100 4 A < B
3637/// 101 5 A != B
3638/// 110 6 A <= B
3639/// 111 7 Always true
3640///
3641static unsigned getICmpCode(const ICmpInst *ICI) {
3642 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003643 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644 case ICmpInst::ICMP_UGT: return 1; // 001
3645 case ICmpInst::ICMP_SGT: return 1; // 001
3646 case ICmpInst::ICMP_EQ: return 2; // 010
3647 case ICmpInst::ICMP_UGE: return 3; // 011
3648 case ICmpInst::ICMP_SGE: return 3; // 011
3649 case ICmpInst::ICMP_ULT: return 4; // 100
3650 case ICmpInst::ICMP_SLT: return 4; // 100
3651 case ICmpInst::ICMP_NE: return 5; // 101
3652 case ICmpInst::ICMP_ULE: return 6; // 110
3653 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003654 // True -> 7
3655 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003656 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003657 return 0;
3658 }
3659}
3660
Evan Cheng8db90722008-10-14 17:15:11 +00003661/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3662/// predicate into a three bit mask. It also returns whether it is an ordered
3663/// predicate by reference.
3664static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3665 isOrdered = false;
3666 switch (CC) {
3667 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3668 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003669 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3670 case FCmpInst::FCMP_UGT: return 1; // 001
3671 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3672 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003673 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3674 case FCmpInst::FCMP_UGE: return 3; // 011
3675 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3676 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003677 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3678 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003679 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3680 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003681 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003682 default:
3683 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003684 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003685 return 0;
3686 }
3687}
3688
Reid Spencere4d87aa2006-12-23 06:05:41 +00003689/// getICmpValue - This is the complement of getICmpCode, which turns an
3690/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003691/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003692/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003693static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003694 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003696 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003697 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 case 1:
3699 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003700 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003702 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3703 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 case 3:
3705 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003706 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003708 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 case 4:
3710 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003711 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003713 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3714 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003715 case 6:
3716 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003718 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003719 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003720 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003721 }
3722}
3723
Evan Cheng8db90722008-10-14 17:15:11 +00003724/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3725/// opcode and two operands into either a FCmp instruction. isordered is passed
3726/// in to determine which kind of predicate to use in the new fcmp instruction.
3727static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003728 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003729 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003730 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003731 case 0:
3732 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003733 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003734 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003736 case 1:
3737 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003738 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003739 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003740 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003741 case 2:
3742 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003743 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003744 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003746 case 3:
3747 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003748 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003749 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003751 case 4:
3752 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003753 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003754 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003755 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003756 case 5:
3757 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003758 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003759 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003760 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003761 case 6:
3762 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003763 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003764 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003765 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003766 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003767 }
3768}
3769
Chris Lattnerb9553d62008-11-16 04:55:20 +00003770/// PredicatesFoldable - Return true if both predicates match sign or if at
3771/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003772static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003773 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3774 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3775 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003776}
3777
3778namespace {
3779// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3780struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003781 InstCombiner &IC;
3782 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003783 ICmpInst::Predicate pred;
3784 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3785 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3786 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003787 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3789 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003790 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3791 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003792 return false;
3793 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794 Instruction *apply(Instruction &Log) const {
3795 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3796 if (ICI->getOperand(0) != LHS) {
3797 assert(ICI->getOperand(1) == LHS);
3798 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003799 }
3800
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003801 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003802 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003803 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003804 unsigned Code;
3805 switch (Log.getOpcode()) {
3806 case Instruction::And: Code = LHSCode & RHSCode; break;
3807 case Instruction::Or: Code = LHSCode | RHSCode; break;
3808 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003809 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003810 }
3811
Nick Lewycky4a134af2009-10-25 05:20:17 +00003812 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003813 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003814 if (Instruction *I = dyn_cast<Instruction>(RV))
3815 return I;
3816 // Otherwise, it's a constant boolean value...
3817 return IC.ReplaceInstUsesWith(Log, RV);
3818 }
3819};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003820} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003821
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003822// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3823// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003824// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003826 ConstantInt *OpRHS,
3827 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 BinaryOperator &TheAnd) {
3829 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003830 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003831 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003832 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003833
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003834 switch (Op->getOpcode()) {
3835 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003836 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003837 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003838 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003839 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003840 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003841 }
3842 break;
3843 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003844 if (Together == AndRHS) // (X | C) & C --> C
3845 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003846
Chris Lattner6e7ba452005-01-01 16:22:27 +00003847 if (Op->hasOneUse() && Together != OpRHS) {
3848 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003849 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003850 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003851 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003852 }
3853 break;
3854 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003855 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003856 // Adding a one to a single bit bit-field should be turned into an XOR
3857 // of the bit. First thing to check is to see if this AND is with a
3858 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003859 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003860
3861 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003862 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003863 // Ok, at this point, we know that we are masking the result of the
3864 // ADD down to exactly one bit. If the constant we are adding has
3865 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003866 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003867
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003868 // Check to see if any bits below the one bit set in AndRHSV are set.
3869 if ((AddRHS & (AndRHSV-1)) == 0) {
3870 // If not, the only thing that can effect the output of the AND is
3871 // the bit specified by AndRHSV. If that bit is set, the effect of
3872 // the XOR is to toggle the bit. If it is clear, then the ADD has
3873 // no effect.
3874 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3875 TheAnd.setOperand(0, X);
3876 return &TheAnd;
3877 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003878 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003879 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003880 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003881 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003882 }
3883 }
3884 }
3885 }
3886 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003887
3888 case Instruction::Shl: {
3889 // We know that the AND will not produce any of the bits shifted in, so if
3890 // the anded constant includes them, clear them now!
3891 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003892 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003893 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003894 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003895 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003896
Zhou Sheng290bec52007-03-29 08:15:12 +00003897 if (CI->getValue() == ShlMask) {
3898 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003899 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3900 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003901 TheAnd.setOperand(1, CI);
3902 return &TheAnd;
3903 }
3904 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003905 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003906 case Instruction::LShr:
3907 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003908 // We know that the AND will not produce any of the bits shifted in, so if
3909 // the anded constant includes them, clear them now! This only applies to
3910 // unsigned shifts, because a signed shr may bring in set bits!
3911 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003912 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003913 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003914 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003915 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003916
Zhou Sheng290bec52007-03-29 08:15:12 +00003917 if (CI->getValue() == ShrMask) {
3918 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003919 return ReplaceInstUsesWith(TheAnd, Op);
3920 } else if (CI != AndRHS) {
3921 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3922 return &TheAnd;
3923 }
3924 break;
3925 }
3926 case Instruction::AShr:
3927 // Signed shr.
3928 // See if this is shifting in some sign extension, then masking it out
3929 // with an and.
3930 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003931 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003932 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003933 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003934 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003935 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003936 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003937 // Make the argument unsigned.
3938 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003939 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003940 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003941 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003942 }
3943 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003944 }
3945 return 0;
3946}
3947
Chris Lattner8b170942002-08-09 23:47:40 +00003948
Chris Lattnera96879a2004-09-29 17:40:11 +00003949/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3950/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003951/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3952/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003953/// insert new instructions.
3954Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003955 bool isSigned, bool Inside,
3956 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003957 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003958 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003959 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003960
Chris Lattnera96879a2004-09-29 17:40:11 +00003961 if (Inside) {
3962 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003963 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003964
Reid Spencere4d87aa2006-12-23 06:05:41 +00003965 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003966 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003967 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003968 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003969 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003970 }
3971
3972 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003973 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003974 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003975 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003976 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003977 }
3978
3979 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003980 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003981
Reid Spencere4e40032007-03-21 23:19:50 +00003982 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003983 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003984 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 ICmpInst::Predicate pred = (isSigned ?
3986 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003987 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003989
Reid Spencere4e40032007-03-21 23:19:50 +00003990 // Emit V-Lo >u Hi-1-Lo
3991 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003992 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003993 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003994 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003995 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003996}
3997
Chris Lattner7203e152005-09-18 07:22:02 +00003998// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3999// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4000// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4001// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004002static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004003 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004004 uint32_t BitWidth = Val->getType()->getBitWidth();
4005 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004006
4007 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004008 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004009 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004010 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004011 return true;
4012}
4013
Chris Lattner7203e152005-09-18 07:22:02 +00004014/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4015/// where isSub determines whether the operator is a sub. If we can fold one of
4016/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004017///
4018/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4019/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4020/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4021///
4022/// return (A +/- B).
4023///
4024Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004025 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 Instruction &I) {
4027 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4028 if (!LHSI || LHSI->getNumOperands() != 2 ||
4029 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4030
4031 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4032
4033 switch (LHSI->getOpcode()) {
4034 default: return 0;
4035 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004036 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004037 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004038 if ((Mask->getValue().countLeadingZeros() +
4039 Mask->getValue().countPopulation()) ==
4040 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004041 break;
4042
4043 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4044 // part, we don't need any explicit masks to take them out of A. If that
4045 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004046 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004047 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004048 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004049 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004050 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004051 break;
4052 }
4053 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004054 return 0;
4055 case Instruction::Or:
4056 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004057 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004058 if ((Mask->getValue().countLeadingZeros() +
4059 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004060 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004061 break;
4062 return 0;
4063 }
4064
Chris Lattnerc8e77562005-09-18 04:24:45 +00004065 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004066 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4067 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004068}
4069
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004070/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4071Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4072 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004073 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004074 ConstantInt *LHSCst, *RHSCst;
4075 ICmpInst::Predicate LHSCC, RHSCC;
4076
Chris Lattnerea065fb2008-11-16 05:10:52 +00004077 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004078 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004079 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004080 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004081 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004082 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004083
4084 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4085 // where C is a power of 2
4086 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4087 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00004088 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004089 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00004090 }
4091
4092 // From here on, we only handle:
4093 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4094 if (Val != Val2) return 0;
4095
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004096 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4097 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4098 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4099 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4100 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4101 return 0;
4102
4103 // We can't fold (ugt x, C) & (sgt x, C2).
4104 if (!PredicatesFoldable(LHSCC, RHSCC))
4105 return 0;
4106
4107 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004108 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004109 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004110 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004111 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004112 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004113 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004114 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4115
4116 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004117 std::swap(LHS, RHS);
4118 std::swap(LHSCst, RHSCst);
4119 std::swap(LHSCC, RHSCC);
4120 }
4121
4122 // At this point, we know we have have two icmp instructions
4123 // comparing a value against two constants and and'ing the result
4124 // together. Because of the above check, we know that we only have
4125 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4126 // (from the FoldICmpLogical check above), that the two constants
4127 // are not equal and that the larger constant is on the RHS
4128 assert(LHSCst != RHSCst && "Compares not folded above?");
4129
4130 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004131 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004132 case ICmpInst::ICMP_EQ:
4133 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004134 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004135 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4136 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4137 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004138 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004139 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4140 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4141 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4142 return ReplaceInstUsesWith(I, LHS);
4143 }
4144 case ICmpInst::ICMP_NE:
4145 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004146 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004147 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004148 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004149 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004150 break; // (X != 13 & X u< 15) -> no change
4151 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004152 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004153 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004154 break; // (X != 13 & X s< 15) -> no change
4155 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4156 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4157 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4158 return ReplaceInstUsesWith(I, RHS);
4159 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004160 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004161 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004162 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004163 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004164 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004165 }
4166 break; // (X != 13 & X != 15) -> no change
4167 }
4168 break;
4169 case ICmpInst::ICMP_ULT:
4170 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004171 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004172 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4173 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004174 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004175 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4176 break;
4177 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4178 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4179 return ReplaceInstUsesWith(I, LHS);
4180 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4181 break;
4182 }
4183 break;
4184 case ICmpInst::ICMP_SLT:
4185 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004186 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004187 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4188 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004189 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004190 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4191 break;
4192 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4193 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4194 return ReplaceInstUsesWith(I, LHS);
4195 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4196 break;
4197 }
4198 break;
4199 case ICmpInst::ICMP_UGT:
4200 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004201 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004202 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4203 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4204 return ReplaceInstUsesWith(I, RHS);
4205 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4206 break;
4207 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004208 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004209 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004210 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004211 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004212 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004213 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004214 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4215 break;
4216 }
4217 break;
4218 case ICmpInst::ICMP_SGT:
4219 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004220 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004221 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4222 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4223 return ReplaceInstUsesWith(I, RHS);
4224 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4225 break;
4226 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004227 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004228 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004229 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004230 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004231 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004232 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004233 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4234 break;
4235 }
4236 break;
4237 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004238
4239 return 0;
4240}
4241
Chris Lattner42d1be02009-07-23 05:14:02 +00004242Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4243 FCmpInst *RHS) {
4244
4245 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4246 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4247 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4248 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4249 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4250 // If either of the constants are nans, then the whole thing returns
4251 // false.
4252 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004253 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004254 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004255 LHS->getOperand(0), RHS->getOperand(0));
4256 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004257
4258 // Handle vector zeros. This occurs because the canonical form of
4259 // "fcmp ord x,x" is "fcmp ord x, 0".
4260 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4261 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004262 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004263 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004264 return 0;
4265 }
4266
4267 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4268 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4269 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4270
4271
4272 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4273 // Swap RHS operands to match LHS.
4274 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4275 std::swap(Op1LHS, Op1RHS);
4276 }
4277
4278 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4279 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4280 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004281 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004282
4283 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004284 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004285 if (Op0CC == FCmpInst::FCMP_TRUE)
4286 return ReplaceInstUsesWith(I, RHS);
4287 if (Op1CC == FCmpInst::FCMP_TRUE)
4288 return ReplaceInstUsesWith(I, LHS);
4289
4290 bool Op0Ordered;
4291 bool Op1Ordered;
4292 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4293 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4294 if (Op1Pred == 0) {
4295 std::swap(LHS, RHS);
4296 std::swap(Op0Pred, Op1Pred);
4297 std::swap(Op0Ordered, Op1Ordered);
4298 }
4299 if (Op0Pred == 0) {
4300 // uno && ueq -> uno && (uno || eq) -> ueq
4301 // ord && olt -> ord && (ord && lt) -> olt
4302 if (Op0Ordered == Op1Ordered)
4303 return ReplaceInstUsesWith(I, RHS);
4304
4305 // uno && oeq -> uno && (ord && eq) -> false
4306 // uno && ord -> false
4307 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004308 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004309 // ord && ueq -> ord && (uno || eq) -> oeq
4310 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4311 Op0LHS, Op0RHS, Context));
4312 }
4313 }
4314
4315 return 0;
4316}
4317
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004318
Chris Lattner7e708292002-06-25 16:13:24 +00004319Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004320 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004322
Chris Lattnerd06094f2009-11-10 00:55:12 +00004323 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4324 return ReplaceInstUsesWith(I, V);
4325
Chris Lattner3f5b8772002-05-06 16:14:14 +00004326
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004327 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004328 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004329 if (SimplifyDemandedInstructionBits(I))
4330 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004331
Dan Gohman6de29f82009-06-15 22:12:54 +00004332
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004333 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004334 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004335 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004336
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004337 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004338 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004339 Value *Op0LHS = Op0I->getOperand(0);
4340 Value *Op0RHS = Op0I->getOperand(1);
4341 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004342 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004343 case Instruction::Xor:
4344 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004345 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004346 if (!Op0I->hasOneUse()) break;
4347
4348 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4349 // Not masking anything out for the LHS, move to RHS.
4350 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4351 Op0RHS->getName()+".masked");
4352 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4353 }
4354 if (!isa<Constant>(Op0RHS) &&
4355 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4356 // Not masking anything out for the RHS, move to LHS.
4357 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4358 Op0LHS->getName()+".masked");
4359 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004360 }
4361
Chris Lattner6e7ba452005-01-01 16:22:27 +00004362 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004363 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004364 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4365 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4366 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4367 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004368 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004369 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004370 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004371 break;
4372
4373 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004374 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4375 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4376 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4377 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004378 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004379
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004380 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4381 // has 1's for all bits that the subtraction with A might affect.
4382 if (Op0I->hasOneUse()) {
4383 uint32_t BitWidth = AndRHSMask.getBitWidth();
4384 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4385 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4386
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004387 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004388 if (!(A && A->isZero()) && // avoid infinite recursion.
4389 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004390 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004391 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4392 }
4393 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004394 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004395
4396 case Instruction::Shl:
4397 case Instruction::LShr:
4398 // (1 << x) & 1 --> zext(x == 0)
4399 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004400 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004401 Value *NewICmp =
4402 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004403 return new ZExtInst(NewICmp, I.getType());
4404 }
4405 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004406 }
4407
Chris Lattner58403262003-07-23 19:25:52 +00004408 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004409 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004410 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004411 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004412 // If this is an integer truncation or change from signed-to-unsigned, and
4413 // if the source is an and/or with immediate, transform it. This
4414 // frequently occurs for bitfield accesses.
4415 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004416 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004417 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004418 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004419 if (CastOp->getOpcode() == Instruction::And) {
4420 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004421 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4422 // This will fold the two constants together, which may allow
4423 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004424 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004425 CastOp->getOperand(0), I.getType(),
4426 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004427 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004428 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004429 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004430 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004431 } else if (CastOp->getOpcode() == Instruction::Or) {
4432 // Change: and (cast (or X, C1) to T), C2
4433 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004434 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004435 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004436 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004437 return ReplaceInstUsesWith(I, AndRHS);
4438 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004439 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004440 }
Chris Lattner06782f82003-07-23 19:36:21 +00004441 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004442
4443 // Try to fold constant and into select arguments.
4444 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004446 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004447 if (isa<PHINode>(Op0))
4448 if (Instruction *NV = FoldOpIntoPhi(I))
4449 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004450 }
4451
Chris Lattner5b62aa72004-06-18 06:07:51 +00004452
Misha Brukmancb6267b2004-07-30 12:50:08 +00004453 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004454 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4455 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4456 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4457 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4458 I.getName()+".demorgan");
4459 return BinaryOperator::CreateNot(Or);
4460 }
4461
Chris Lattner2082ad92006-02-13 23:07:23 +00004462 {
Chris Lattner003b6202007-06-15 05:58:24 +00004463 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004464 // (A|B) & ~(A&B) -> A^B
4465 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4466 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4467 ((A == C && B == D) || (A == D && B == C)))
4468 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004469
Chris Lattnerd06094f2009-11-10 00:55:12 +00004470 // ~(A&B) & (A|B) -> A^B
4471 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4472 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4473 ((A == C && B == D) || (A == D && B == C)))
4474 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004475
4476 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004477 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004478 if (A == Op1) { // (A^B)&A -> A&(A^B)
4479 I.swapOperands(); // Simplify below
4480 std::swap(Op0, Op1);
4481 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4482 cast<BinaryOperator>(Op0)->swapOperands();
4483 I.swapOperands(); // Simplify below
4484 std::swap(Op0, Op1);
4485 }
4486 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004487
Chris Lattner64daab52006-04-01 08:03:55 +00004488 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004489 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004490 if (B == Op0) { // B&(A^B) -> B&(B^A)
4491 cast<BinaryOperator>(Op1)->swapOperands();
4492 std::swap(A, B);
4493 }
Chris Lattner74381062009-08-30 07:44:24 +00004494 if (A == Op0) // A&(A^B) -> A & ~B
4495 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004496 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004497
4498 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004499 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4500 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004501 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004502 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4503 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004504 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004505 }
4506
Reid Spencere4d87aa2006-12-23 06:05:41 +00004507 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4508 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004509 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004510 return R;
4511
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004512 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4513 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4514 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004515 }
4516
Chris Lattner6fc205f2006-05-05 06:39:07 +00004517 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004518 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4519 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4520 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4521 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004522 if (SrcTy == Op1C->getOperand(0)->getType() &&
4523 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004524 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004525 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4526 I.getType(), TD) &&
4527 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4528 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004529 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4530 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004531 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004532 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004533 }
Chris Lattnere511b742006-11-14 07:46:50 +00004534
4535 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004536 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4537 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4538 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004539 SI0->getOperand(1) == SI1->getOperand(1) &&
4540 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004541 Value *NewOp =
4542 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4543 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004544 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004545 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004546 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004547 }
4548
Evan Cheng8db90722008-10-14 17:15:11 +00004549 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004550 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004551 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4552 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4553 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004554 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004555
Chris Lattner7e708292002-06-25 16:13:24 +00004556 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004557}
4558
Chris Lattner8c34cd22008-10-05 02:13:19 +00004559/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4560/// capable of providing pieces of a bswap. The subexpression provides pieces
4561/// of a bswap if it is proven that each of the non-zero bytes in the output of
4562/// the expression came from the corresponding "byte swapped" byte in some other
4563/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4564/// we know that the expression deposits the low byte of %X into the high byte
4565/// of the bswap result and that all other bytes are zero. This expression is
4566/// accepted, the high byte of ByteValues is set to X to indicate a correct
4567/// match.
4568///
4569/// This function returns true if the match was unsuccessful and false if so.
4570/// On entry to the function the "OverallLeftShift" is a signed integer value
4571/// indicating the number of bytes that the subexpression is later shifted. For
4572/// example, if the expression is later right shifted by 16 bits, the
4573/// OverallLeftShift value would be -2 on entry. This is used to specify which
4574/// byte of ByteValues is actually being set.
4575///
4576/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4577/// byte is masked to zero by a user. For example, in (X & 255), X will be
4578/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4579/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4580/// always in the local (OverallLeftShift) coordinate space.
4581///
4582static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4583 SmallVector<Value*, 8> &ByteValues) {
4584 if (Instruction *I = dyn_cast<Instruction>(V)) {
4585 // If this is an or instruction, it may be an inner node of the bswap.
4586 if (I->getOpcode() == Instruction::Or) {
4587 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4588 ByteValues) ||
4589 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4590 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004591 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004592
4593 // If this is a logical shift by a constant multiple of 8, recurse with
4594 // OverallLeftShift and ByteMask adjusted.
4595 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4596 unsigned ShAmt =
4597 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4598 // Ensure the shift amount is defined and of a byte value.
4599 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4600 return true;
4601
4602 unsigned ByteShift = ShAmt >> 3;
4603 if (I->getOpcode() == Instruction::Shl) {
4604 // X << 2 -> collect(X, +2)
4605 OverallLeftShift += ByteShift;
4606 ByteMask >>= ByteShift;
4607 } else {
4608 // X >>u 2 -> collect(X, -2)
4609 OverallLeftShift -= ByteShift;
4610 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004611 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004612 }
4613
4614 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4615 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4616
4617 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4618 ByteValues);
4619 }
4620
4621 // If this is a logical 'and' with a mask that clears bytes, clear the
4622 // corresponding bytes in ByteMask.
4623 if (I->getOpcode() == Instruction::And &&
4624 isa<ConstantInt>(I->getOperand(1))) {
4625 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4626 unsigned NumBytes = ByteValues.size();
4627 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4628 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4629
4630 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4631 // If this byte is masked out by a later operation, we don't care what
4632 // the and mask is.
4633 if ((ByteMask & (1 << i)) == 0)
4634 continue;
4635
4636 // If the AndMask is all zeros for this byte, clear the bit.
4637 APInt MaskB = AndMask & Byte;
4638 if (MaskB == 0) {
4639 ByteMask &= ~(1U << i);
4640 continue;
4641 }
4642
4643 // If the AndMask is not all ones for this byte, it's not a bytezap.
4644 if (MaskB != Byte)
4645 return true;
4646
4647 // Otherwise, this byte is kept.
4648 }
4649
4650 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4651 ByteValues);
4652 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004653 }
4654
Chris Lattner8c34cd22008-10-05 02:13:19 +00004655 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4656 // the input value to the bswap. Some observations: 1) if more than one byte
4657 // is demanded from this input, then it could not be successfully assembled
4658 // into a byteswap. At least one of the two bytes would not be aligned with
4659 // their ultimate destination.
4660 if (!isPowerOf2_32(ByteMask)) return true;
4661 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004662
Chris Lattner8c34cd22008-10-05 02:13:19 +00004663 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4664 // is demanded, it needs to go into byte 0 of the result. This means that the
4665 // byte needs to be shifted until it lands in the right byte bucket. The
4666 // shift amount depends on the position: if the byte is coming from the high
4667 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4668 // low part, it must be shifted left.
4669 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4670 if (InputByteNo < ByteValues.size()/2) {
4671 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4672 return true;
4673 } else {
4674 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4675 return true;
4676 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004677
4678 // If the destination byte value is already defined, the values are or'd
4679 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004680 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004681 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004682 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004683 return false;
4684}
4685
4686/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4687/// If so, insert the new bswap intrinsic and return it.
4688Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004689 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004690 if (!ITy || ITy->getBitWidth() % 16 ||
4691 // ByteMask only allows up to 32-byte values.
4692 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004693 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004694
4695 /// ByteValues - For each byte of the result, we keep track of which value
4696 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004697 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004698 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004699
4700 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004701 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4702 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004703 return 0;
4704
4705 // Check to see if all of the bytes come from the same value.
4706 Value *V = ByteValues[0];
4707 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4708
4709 // Check to make sure that all of the bytes come from the same value.
4710 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4711 if (ByteValues[i] != V)
4712 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004713 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004714 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004715 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004716 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004717}
4718
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004719/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4720/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4721/// we can simplify this expression to "cond ? C : D or B".
4722static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004723 Value *C, Value *D,
4724 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004725 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004726 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004727 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004728 return 0;
4729
Chris Lattnera6a474d2008-11-16 04:26:55 +00004730 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004731 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004732 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004733 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004734 return SelectInst::Create(Cond, C, B);
4735 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004736 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004737 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004738 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004739 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004740 return 0;
4741}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004742
Chris Lattner69d4ced2008-11-16 05:20:07 +00004743/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4744Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4745 ICmpInst *LHS, ICmpInst *RHS) {
4746 Value *Val, *Val2;
4747 ConstantInt *LHSCst, *RHSCst;
4748 ICmpInst::Predicate LHSCC, RHSCC;
4749
4750 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004752 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004753 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004754 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004755 return 0;
4756
4757 // From here on, we only handle:
4758 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4759 if (Val != Val2) return 0;
4760
4761 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4762 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4763 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4764 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4765 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4766 return 0;
4767
4768 // We can't fold (ugt x, C) | (sgt x, C2).
4769 if (!PredicatesFoldable(LHSCC, RHSCC))
4770 return 0;
4771
4772 // Ensure that the larger constant is on the RHS.
4773 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004774 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004775 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004776 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004777 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4778 else
4779 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4780
4781 if (ShouldSwap) {
4782 std::swap(LHS, RHS);
4783 std::swap(LHSCst, RHSCst);
4784 std::swap(LHSCC, RHSCC);
4785 }
4786
4787 // At this point, we know we have have two icmp instructions
4788 // comparing a value against two constants and or'ing the result
4789 // together. Because of the above check, we know that we only have
4790 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4791 // FoldICmpLogical check above), that the two constants are not
4792 // equal.
4793 assert(LHSCst != RHSCst && "Compares not folded above?");
4794
4795 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004796 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004797 case ICmpInst::ICMP_EQ:
4798 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004799 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004800 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004801 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004802 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004803 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004804 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004805 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004806 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004807 }
4808 break; // (X == 13 | X == 15) -> no change
4809 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4810 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4811 break;
4812 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4813 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4814 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4815 return ReplaceInstUsesWith(I, RHS);
4816 }
4817 break;
4818 case ICmpInst::ICMP_NE:
4819 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004820 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004821 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4822 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4823 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4824 return ReplaceInstUsesWith(I, LHS);
4825 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4826 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4827 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004828 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004829 }
4830 break;
4831 case ICmpInst::ICMP_ULT:
4832 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004833 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004834 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4835 break;
4836 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4837 // If RHSCst is [us]MAXINT, it is always false. Not handling
4838 // this can cause overflow.
4839 if (RHSCst->isMaxValue(false))
4840 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004841 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004842 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004843 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4844 break;
4845 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4846 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4847 return ReplaceInstUsesWith(I, RHS);
4848 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4849 break;
4850 }
4851 break;
4852 case ICmpInst::ICMP_SLT:
4853 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004855 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4856 break;
4857 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4858 // If RHSCst is [us]MAXINT, it is always false. Not handling
4859 // this can cause overflow.
4860 if (RHSCst->isMaxValue(true))
4861 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004862 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004863 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004864 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4865 break;
4866 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4867 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4868 return ReplaceInstUsesWith(I, RHS);
4869 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4870 break;
4871 }
4872 break;
4873 case ICmpInst::ICMP_UGT:
4874 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004875 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004876 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4877 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4878 return ReplaceInstUsesWith(I, LHS);
4879 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4880 break;
4881 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4882 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004883 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004884 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4885 break;
4886 }
4887 break;
4888 case ICmpInst::ICMP_SGT:
4889 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004890 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004891 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4892 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4893 return ReplaceInstUsesWith(I, LHS);
4894 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4895 break;
4896 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4897 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004898 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004899 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4900 break;
4901 }
4902 break;
4903 }
4904 return 0;
4905}
4906
Chris Lattner5414cc52009-07-23 05:46:22 +00004907Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4908 FCmpInst *RHS) {
4909 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4910 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4911 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4912 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4913 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4914 // If either of the constants are nans, then the whole thing returns
4915 // true.
4916 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004917 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004918
4919 // Otherwise, no need to compare the two constants, compare the
4920 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004921 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004922 LHS->getOperand(0), RHS->getOperand(0));
4923 }
4924
4925 // Handle vector zeros. This occurs because the canonical form of
4926 // "fcmp uno x,x" is "fcmp uno x, 0".
4927 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4928 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004929 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004930 LHS->getOperand(0), RHS->getOperand(0));
4931
4932 return 0;
4933 }
4934
4935 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4936 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4937 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4938
4939 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4940 // Swap RHS operands to match LHS.
4941 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4942 std::swap(Op1LHS, Op1RHS);
4943 }
4944 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4945 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4946 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004947 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004948 Op0LHS, Op0RHS);
4949 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004950 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004951 if (Op0CC == FCmpInst::FCMP_FALSE)
4952 return ReplaceInstUsesWith(I, RHS);
4953 if (Op1CC == FCmpInst::FCMP_FALSE)
4954 return ReplaceInstUsesWith(I, LHS);
4955 bool Op0Ordered;
4956 bool Op1Ordered;
4957 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4958 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4959 if (Op0Ordered == Op1Ordered) {
4960 // If both are ordered or unordered, return a new fcmp with
4961 // or'ed predicates.
4962 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4963 Op0LHS, Op0RHS, Context);
4964 if (Instruction *I = dyn_cast<Instruction>(RV))
4965 return I;
4966 // Otherwise, it's a constant boolean value...
4967 return ReplaceInstUsesWith(I, RV);
4968 }
4969 }
4970 return 0;
4971}
4972
Bill Wendlinga698a472008-12-01 08:23:25 +00004973/// FoldOrWithConstants - This helper function folds:
4974///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004975/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004976///
4977/// into:
4978///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004979/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004980///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004981/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004982Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004983 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004984 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4985 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004986
Bill Wendling286a0542008-12-02 06:24:20 +00004987 Value *V1 = 0;
4988 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004989 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004990
Bill Wendling29976b92008-12-02 06:18:11 +00004991 APInt Xor = CI1->getValue() ^ CI2->getValue();
4992 if (!Xor.isAllOnesValue()) return 0;
4993
Bill Wendling286a0542008-12-02 06:24:20 +00004994 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004995 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004996 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004997 }
4998
4999 return 0;
5000}
5001
Chris Lattner7e708292002-06-25 16:13:24 +00005002Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005003 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005005
Chris Lattnerd06094f2009-11-10 00:55:12 +00005006 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5007 return ReplaceInstUsesWith(I, V);
5008
5009
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005010 // See if we can simplify any instructions used by the instruction whose sole
5011 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005012 if (SimplifyDemandedInstructionBits(I))
5013 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005014
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005015 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005016 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005017 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005018 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005019 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005020 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005021 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005022 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005023 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005024 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005025
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005026 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005027 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005028 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005029 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005030 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005031 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005032 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005033 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005034
5035 // Try to fold constant and into select arguments.
5036 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005037 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005038 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005039 if (isa<PHINode>(Op0))
5040 if (Instruction *NV = FoldOpIntoPhi(I))
5041 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005042 }
5043
Chris Lattner4f637d42006-01-06 17:59:59 +00005044 Value *A = 0, *B = 0;
5045 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005046
Chris Lattner6423d4c2006-07-10 20:25:24 +00005047 // (A | B) | C and A | (B | C) -> bswap if possible.
5048 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005049 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5050 match(Op1, m_Or(m_Value(), m_Value())) ||
5051 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5052 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005053 if (Instruction *BSwap = MatchBSwap(I))
5054 return BSwap;
5055 }
5056
Chris Lattner6e4c6492005-05-09 04:58:36 +00005057 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005058 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005059 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005060 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005061 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005062 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005063 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005064 }
5065
5066 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005067 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005068 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005069 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005070 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005071 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005072 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005073 }
5074
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005075 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005076 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005077 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5078 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005079 Value *V1 = 0, *V2 = 0, *V3 = 0;
5080 C1 = dyn_cast<ConstantInt>(C);
5081 C2 = dyn_cast<ConstantInt>(D);
5082 if (C1 && C2) { // (A & C1)|(B & C2)
5083 // If we have: ((V + N) & C1) | (V & C2)
5084 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5085 // replace with V+N.
5086 if (C1->getValue() == ~C2->getValue()) {
5087 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005088 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005089 // Add commutes, try both ways.
5090 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5091 return ReplaceInstUsesWith(I, A);
5092 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5093 return ReplaceInstUsesWith(I, A);
5094 }
5095 // Or commutes, try both ways.
5096 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005097 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005098 // Add commutes, try both ways.
5099 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5100 return ReplaceInstUsesWith(I, B);
5101 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5102 return ReplaceInstUsesWith(I, B);
5103 }
5104 }
Chris Lattner044e5332007-04-08 08:01:49 +00005105 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005106 }
5107
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005108 // Check to see if we have any common things being and'ed. If so, find the
5109 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005110 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5111 if (A == B) // (A & C)|(A & D) == A & (C|D)
5112 V1 = A, V2 = C, V3 = D;
5113 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5114 V1 = A, V2 = B, V3 = C;
5115 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5116 V1 = C, V2 = A, V3 = D;
5117 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5118 V1 = C, V2 = A, V3 = B;
5119
5120 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005121 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005123 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005124 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005125
Dan Gohman1975d032008-10-30 20:40:10 +00005126 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005127 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005128 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005129 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005130 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005131 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005132 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005133 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005134 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005135
Bill Wendlingb01865c2008-11-30 13:52:49 +00005136 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 if ((match(C, m_Not(m_Specific(D))) &&
5138 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005139 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005140 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005141 if ((match(A, m_Not(m_Specific(D))) &&
5142 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005143 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005144 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005145 if ((match(C, m_Not(m_Specific(B))) &&
5146 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005147 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005148 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005149 if ((match(A, m_Not(m_Specific(B))) &&
5150 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005151 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005152 }
Chris Lattnere511b742006-11-14 07:46:50 +00005153
5154 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005155 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5156 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5157 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005158 SI0->getOperand(1) == SI1->getOperand(1) &&
5159 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005160 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5161 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005162 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005163 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005164 }
5165 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005166
Bill Wendlingb3833d12008-12-01 01:07:11 +00005167 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005168 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5169 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005170 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005171 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005172 }
5173 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005174 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5175 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005176 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005177 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005178 }
5179
Chris Lattnerd06094f2009-11-10 00:55:12 +00005180 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5181 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5182 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5183 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5184 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5185 I.getName()+".demorgan");
5186 return BinaryOperator::CreateNot(And);
5187 }
Chris Lattnera2881962003-02-18 19:28:33 +00005188
Reid Spencere4d87aa2006-12-23 06:05:41 +00005189 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5190 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005191 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005192 return R;
5193
Chris Lattner69d4ced2008-11-16 05:20:07 +00005194 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5195 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5196 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005197 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005198
5199 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005200 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005202 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005203 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5204 !isa<ICmpInst>(Op1C->getOperand(0))) {
5205 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005206 if (SrcTy == Op1C->getOperand(0)->getType() &&
5207 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005208 // Only do this if the casts both really cause code to be
5209 // generated.
5210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5211 I.getType(), TD) &&
5212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5213 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005214 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5215 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005216 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005217 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005218 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005219 }
Chris Lattner99c65742007-10-24 05:38:08 +00005220 }
5221
5222
5223 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5224 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005225 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5226 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5227 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005228 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005229
Chris Lattner7e708292002-06-25 16:13:24 +00005230 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005231}
5232
Dan Gohman844731a2008-05-13 00:00:25 +00005233namespace {
5234
Chris Lattnerc317d392004-02-16 01:20:27 +00005235// XorSelf - Implements: X ^ X --> 0
5236struct XorSelf {
5237 Value *RHS;
5238 XorSelf(Value *rhs) : RHS(rhs) {}
5239 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5240 Instruction *apply(BinaryOperator &Xor) const {
5241 return &Xor;
5242 }
5243};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005244
Dan Gohman844731a2008-05-13 00:00:25 +00005245}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005246
Chris Lattner7e708292002-06-25 16:13:24 +00005247Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005248 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005250
Evan Chengd34af782008-03-25 20:07:13 +00005251 if (isa<UndefValue>(Op1)) {
5252 if (isa<UndefValue>(Op0))
5253 // Handle undef ^ undef -> 0 special case. This is a common
5254 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005255 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005256 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005257 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005258
Chris Lattnerc317d392004-02-16 01:20:27 +00005259 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005260 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005261 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005262 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005263 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005264
5265 // See if we can simplify any instructions used by the instruction whose sole
5266 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005267 if (SimplifyDemandedInstructionBits(I))
5268 return &I;
5269 if (isa<VectorType>(I.getType()))
5270 if (isa<ConstantAggregateZero>(Op1))
5271 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005272
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005273 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005274 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005275 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5276 if (Op0I->getOpcode() == Instruction::And ||
5277 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005278 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5279 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5280 if (dyn_castNotVal(Op0I->getOperand(1)))
5281 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005282 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005283 Value *NotY =
5284 Builder->CreateNot(Op0I->getOperand(1),
5285 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005286 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005287 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005288 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005289 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005290
5291 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5292 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5293 if (isFreeToInvert(Op0I->getOperand(0)) &&
5294 isFreeToInvert(Op0I->getOperand(1))) {
5295 Value *NotX =
5296 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5297 Value *NotY =
5298 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5299 if (Op0I->getOpcode() == Instruction::And)
5300 return BinaryOperator::CreateOr(NotX, NotY);
5301 return BinaryOperator::CreateAnd(NotX, NotY);
5302 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005303 }
5304 }
5305 }
5306
5307
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005308 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005309 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005310 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005311 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005312 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005313 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005314
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005315 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005316 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005317 FCI->getOperand(0), FCI->getOperand(1));
5318 }
5319
Nick Lewycky517e1f52008-05-31 19:01:33 +00005320 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5321 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5322 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5323 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5324 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005325 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5326 (RHS == ConstantExpr::getCast(Opcode,
5327 ConstantInt::getTrue(*Context),
5328 Op0C->getDestTy()))) {
5329 CI->setPredicate(CI->getInversePredicate());
5330 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005331 }
5332 }
5333 }
5334 }
5335
Reid Spencere4d87aa2006-12-23 06:05:41 +00005336 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005337 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005338 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5339 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005340 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5341 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005342 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005343 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005344 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005345
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005346 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005347 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005348 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005349 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005350 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005351 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005352 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005353 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005354 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005355 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005356 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005357 Constant *C = ConstantInt::get(*Context,
5358 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005359 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005360
Chris Lattner7c4049c2004-01-12 19:35:11 +00005361 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005362 } else if (Op0I->getOpcode() == Instruction::Or) {
5363 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005364 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005365 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005366 // Anything in both C1 and C2 is known to be zero, remove it from
5367 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005368 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5369 NewRHS = ConstantExpr::getAnd(NewRHS,
5370 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005371 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005372 I.setOperand(0, Op0I->getOperand(0));
5373 I.setOperand(1, NewRHS);
5374 return &I;
5375 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005376 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005377 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005378 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005379
5380 // Try to fold constant and into select arguments.
5381 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005383 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005384 if (isa<PHINode>(Op0))
5385 if (Instruction *NV = FoldOpIntoPhi(I))
5386 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005387 }
5388
Dan Gohman186a6362009-08-12 16:04:34 +00005389 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005390 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005391 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005392
Dan Gohman186a6362009-08-12 16:04:34 +00005393 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005394 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005395 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005396
Chris Lattner318bf792007-03-18 22:51:34 +00005397
5398 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5399 if (Op1I) {
5400 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005401 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005402 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005403 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005404 I.swapOperands();
5405 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005406 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005407 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005408 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005409 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005410 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005411 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005412 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005413 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005414 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005415 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005416 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005417 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005418 std::swap(A, B);
5419 }
Chris Lattner318bf792007-03-18 22:51:34 +00005420 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005421 I.swapOperands(); // Simplified below.
5422 std::swap(Op0, Op1);
5423 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005424 }
Chris Lattner318bf792007-03-18 22:51:34 +00005425 }
5426
5427 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5428 if (Op0I) {
5429 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005430 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005431 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005432 if (A == Op1) // (B|A)^B == (A|B)^B
5433 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005434 if (B == Op1) // (A|B)^B == A & ~B
5435 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005436 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005437 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005438 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005439 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005440 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005441 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005442 if (A == Op1) // (A&B)^A -> (B&A)^A
5443 std::swap(A, B);
5444 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005445 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005446 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005447 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005448 }
Chris Lattner318bf792007-03-18 22:51:34 +00005449 }
5450
5451 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5452 if (Op0I && Op1I && Op0I->isShift() &&
5453 Op0I->getOpcode() == Op1I->getOpcode() &&
5454 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5455 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005456 Value *NewOp =
5457 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5458 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005460 Op1I->getOperand(1));
5461 }
5462
5463 if (Op0I && Op1I) {
5464 Value *A, *B, *C, *D;
5465 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005466 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5467 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005468 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005469 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005470 }
5471 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005472 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5473 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005474 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005475 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005476 }
5477
5478 // (A & B)^(C & D)
5479 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005480 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5481 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005482 // (X & Y)^(X & Y) -> (Y^Z) & X
5483 Value *X = 0, *Y = 0, *Z = 0;
5484 if (A == C)
5485 X = A, Y = B, Z = D;
5486 else if (A == D)
5487 X = A, Y = B, Z = C;
5488 else if (B == C)
5489 X = B, Y = A, Z = D;
5490 else if (B == D)
5491 X = B, Y = A, Z = C;
5492
5493 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005494 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005495 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005496 }
5497 }
5498 }
5499
Reid Spencere4d87aa2006-12-23 06:05:41 +00005500 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5501 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005502 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005503 return R;
5504
Chris Lattner6fc205f2006-05-05 06:39:07 +00005505 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005506 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005507 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005508 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5509 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005510 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005511 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005512 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5513 I.getType(), TD) &&
5514 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5515 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005516 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5517 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005518 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005519 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005520 }
Chris Lattner99c65742007-10-24 05:38:08 +00005521 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005522
Chris Lattner7e708292002-06-25 16:13:24 +00005523 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005524}
5525
Owen Andersond672ecb2009-07-03 00:17:18 +00005526static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005527 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005528 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005529}
Chris Lattnera96879a2004-09-29 17:40:11 +00005530
Dan Gohman6de29f82009-06-15 22:12:54 +00005531static bool HasAddOverflow(ConstantInt *Result,
5532 ConstantInt *In1, ConstantInt *In2,
5533 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005534 if (IsSigned)
5535 if (In2->getValue().isNegative())
5536 return Result->getValue().sgt(In1->getValue());
5537 else
5538 return Result->getValue().slt(In1->getValue());
5539 else
5540 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005541}
5542
Dan Gohman6de29f82009-06-15 22:12:54 +00005543/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005544/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005545static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005546 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005547 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005548 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005549
Dan Gohman6de29f82009-06-15 22:12:54 +00005550 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5551 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005552 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005553 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5554 ExtractElement(In1, Idx, Context),
5555 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005556 IsSigned))
5557 return true;
5558 }
5559 return false;
5560 }
5561
5562 return HasAddOverflow(cast<ConstantInt>(Result),
5563 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5564 IsSigned);
5565}
5566
5567static bool HasSubOverflow(ConstantInt *Result,
5568 ConstantInt *In1, ConstantInt *In2,
5569 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005570 if (IsSigned)
5571 if (In2->getValue().isNegative())
5572 return Result->getValue().slt(In1->getValue());
5573 else
5574 return Result->getValue().sgt(In1->getValue());
5575 else
5576 return Result->getValue().ugt(In1->getValue());
5577}
5578
Dan Gohman6de29f82009-06-15 22:12:54 +00005579/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5580/// overflowed for this type.
5581static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005582 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005583 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005584 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005585
5586 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5587 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005588 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005589 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5590 ExtractElement(In1, Idx, Context),
5591 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005592 IsSigned))
5593 return true;
5594 }
5595 return false;
5596 }
5597
5598 return HasSubOverflow(cast<ConstantInt>(Result),
5599 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5600 IsSigned);
5601}
5602
Chris Lattner10c0d912008-04-22 02:53:33 +00005603
Reid Spencere4d87aa2006-12-23 06:05:41 +00005604/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005605/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005606Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 ICmpInst::Predicate Cond,
5608 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005609 // Look through bitcasts.
5610 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5611 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005612
Chris Lattner574da9b2005-01-13 20:14:25 +00005613 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005614 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005615 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005616 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005617 // know pointers can't overflow since the gep is inbounds. See if we can
5618 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005619 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5620
5621 // If not, synthesize the offset the hard way.
5622 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005623 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005624 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005625 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005626 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005627 // If the base pointers are different, but the indices are the same, just
5628 // compare the base pointer.
5629 if (PtrBase != GEPRHS->getOperand(0)) {
5630 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005631 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005632 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005633 if (IndicesTheSame)
5634 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5635 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5636 IndicesTheSame = false;
5637 break;
5638 }
5639
5640 // If all indices are the same, just compare the base pointers.
5641 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005642 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005643 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005644
5645 // Otherwise, the base pointers are different and the indices are
5646 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005647 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005648 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005649
Chris Lattnere9d782b2005-01-13 22:25:21 +00005650 // If one of the GEPs has all zero indices, recurse.
5651 bool AllZeros = true;
5652 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5653 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5654 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5655 AllZeros = false;
5656 break;
5657 }
5658 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005659 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5660 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005661
5662 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005663 AllZeros = true;
5664 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5665 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5666 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5667 AllZeros = false;
5668 break;
5669 }
5670 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005671 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005672
Chris Lattner4401c9c2005-01-14 00:20:05 +00005673 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5674 // If the GEPs only differ by one index, compare it.
5675 unsigned NumDifferences = 0; // Keep track of # differences.
5676 unsigned DiffOperand = 0; // The operand that differs.
5677 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5678 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005679 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5680 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005681 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005682 NumDifferences = 2;
5683 break;
5684 } else {
5685 if (NumDifferences++) break;
5686 DiffOperand = i;
5687 }
5688 }
5689
5690 if (NumDifferences == 0) // SAME GEP?
5691 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005692 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005693 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005694
Chris Lattner4401c9c2005-01-14 00:20:05 +00005695 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005696 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5697 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005698 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005699 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005700 }
5701 }
5702
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005704 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005705 if (TD &&
5706 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005707 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5708 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005709 Value *L = EmitGEPOffset(GEPLHS, *this);
5710 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005711 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005712 }
5713 }
5714 return 0;
5715}
5716
Chris Lattnera5406232008-05-19 20:18:56 +00005717/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5718///
5719Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5720 Instruction *LHSI,
5721 Constant *RHSC) {
5722 if (!isa<ConstantFP>(RHSC)) return 0;
5723 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5724
5725 // Get the width of the mantissa. We don't want to hack on conversions that
5726 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005727 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005728 if (MantissaWidth == -1) return 0; // Unknown.
5729
5730 // Check to see that the input is converted from an integer type that is small
5731 // enough that preserves all bits. TODO: check here for "known" sign bits.
5732 // 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 +00005733 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005734
5735 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005736 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5737 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005738 ++InputSize;
5739
5740 // If the conversion would lose info, don't hack on this.
5741 if ((int)InputSize > MantissaWidth)
5742 return 0;
5743
5744 // Otherwise, we can potentially simplify the comparison. We know that it
5745 // will always come through as an integer value and we know the constant is
5746 // not a NAN (it would have been previously simplified).
5747 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5748
5749 ICmpInst::Predicate Pred;
5750 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005751 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005752 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005753 case FCmpInst::FCMP_OEQ:
5754 Pred = ICmpInst::ICMP_EQ;
5755 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005756 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 case FCmpInst::FCMP_OGT:
5758 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5759 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005760 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005761 case FCmpInst::FCMP_OGE:
5762 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5763 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005764 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005765 case FCmpInst::FCMP_OLT:
5766 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5767 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005768 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005769 case FCmpInst::FCMP_OLE:
5770 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5771 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005772 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 case FCmpInst::FCMP_ONE:
5774 Pred = ICmpInst::ICMP_NE;
5775 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005776 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005777 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005778 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005779 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005780 }
5781
5782 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5783
5784 // Now we know that the APFloat is a normal number, zero or inf.
5785
Chris Lattner85162782008-05-20 03:50:52 +00005786 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005787 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005788 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005789
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005790 if (!LHSUnsigned) {
5791 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5792 // and large values.
5793 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5794 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5795 APFloat::rmNearestTiesToEven);
5796 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5797 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5798 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005799 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5800 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005801 }
5802 } else {
5803 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5804 // +INF and large values.
5805 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5806 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5807 APFloat::rmNearestTiesToEven);
5808 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5809 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5810 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005811 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5812 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 }
Chris Lattnera5406232008-05-19 20:18:56 +00005814 }
5815
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005816 if (!LHSUnsigned) {
5817 // See if the RHS value is < SignedMin.
5818 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5819 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5820 APFloat::rmNearestTiesToEven);
5821 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5822 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5823 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5825 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005826 }
Chris Lattnera5406232008-05-19 20:18:56 +00005827 }
5828
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005829 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5830 // [0, UMAX], but it may still be fractional. See if it is fractional by
5831 // casting the FP value to the integer value and back, checking for equality.
5832 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005833 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005834 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5835 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005836 if (!RHS.isZero()) {
5837 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005838 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5839 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005840 if (!Equal) {
5841 // If we had a comparison against a fractional value, we have to adjust
5842 // the compare predicate and sometimes the value. RHSC is rounded towards
5843 // zero at this point.
5844 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005845 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005846 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005848 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005849 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005850 case ICmpInst::ICMP_ULE:
5851 // (float)int <= 4.4 --> int <= 4
5852 // (float)int <= -4.4 --> false
5853 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005854 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005855 break;
5856 case ICmpInst::ICMP_SLE:
5857 // (float)int <= 4.4 --> int <= 4
5858 // (float)int <= -4.4 --> int < -4
5859 if (RHS.isNegative())
5860 Pred = ICmpInst::ICMP_SLT;
5861 break;
5862 case ICmpInst::ICMP_ULT:
5863 // (float)int < -4.4 --> false
5864 // (float)int < 4.4 --> int <= 4
5865 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005866 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005867 Pred = ICmpInst::ICMP_ULE;
5868 break;
5869 case ICmpInst::ICMP_SLT:
5870 // (float)int < -4.4 --> int < -4
5871 // (float)int < 4.4 --> int <= 4
5872 if (!RHS.isNegative())
5873 Pred = ICmpInst::ICMP_SLE;
5874 break;
5875 case ICmpInst::ICMP_UGT:
5876 // (float)int > 4.4 --> int > 4
5877 // (float)int > -4.4 --> true
5878 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005879 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005880 break;
5881 case ICmpInst::ICMP_SGT:
5882 // (float)int > 4.4 --> int > 4
5883 // (float)int > -4.4 --> int >= -4
5884 if (RHS.isNegative())
5885 Pred = ICmpInst::ICMP_SGE;
5886 break;
5887 case ICmpInst::ICMP_UGE:
5888 // (float)int >= -4.4 --> true
5889 // (float)int >= 4.4 --> int > 4
5890 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005891 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005892 Pred = ICmpInst::ICMP_UGT;
5893 break;
5894 case ICmpInst::ICMP_SGE:
5895 // (float)int >= -4.4 --> int >= -4
5896 // (float)int >= 4.4 --> int > 4
5897 if (!RHS.isNegative())
5898 Pred = ICmpInst::ICMP_SGT;
5899 break;
5900 }
Chris Lattnera5406232008-05-19 20:18:56 +00005901 }
5902 }
5903
5904 // Lower this FP comparison into an appropriate integer version of the
5905 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005906 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005907}
5908
Reid Spencere4d87aa2006-12-23 06:05:41 +00005909Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005910 bool Changed = false;
5911
5912 /// Orders the operands of the compare so that they are listed from most
5913 /// complex to least complex. This puts constants before unary operators,
5914 /// before binary operators.
5915 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5916 I.swapOperands();
5917 Changed = true;
5918 }
5919
Chris Lattner8b170942002-08-09 23:47:40 +00005920 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005921
Chris Lattner210c5d42009-11-09 23:55:12 +00005922 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5923 return ReplaceInstUsesWith(I, V);
5924
Chris Lattner58e97462007-01-14 19:42:17 +00005925 // Simplify 'fcmp pred X, X'
5926 if (Op0 == Op1) {
5927 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005928 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005929 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5930 case FCmpInst::FCMP_ULT: // True if unordered or less than
5931 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5932 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5933 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5934 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005935 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005936 return &I;
5937
5938 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5939 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5940 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5941 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5942 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5943 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005944 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005945 return &I;
5946 }
5947 }
5948
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 // Handle fcmp with constant RHS
5950 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5951 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5952 switch (LHSI->getOpcode()) {
5953 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005954 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5955 // block. If in the same block, we're encouraging jump threading. If
5956 // not, we are just pessimizing the code by making an i1 phi.
5957 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005958 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005959 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005961 case Instruction::SIToFP:
5962 case Instruction::UIToFP:
5963 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5964 return NV;
5965 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 case Instruction::Select:
5967 // If either operand of the select is a constant, we can fold the
5968 // comparison into the select arms, which will cause one to be
5969 // constant folded and the select turned into a bitwise or.
5970 Value *Op1 = 0, *Op2 = 0;
5971 if (LHSI->hasOneUse()) {
5972 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5973 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005974 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005976 Op2 = Builder->CreateFCmp(I.getPredicate(),
5977 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5979 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005980 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005982 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5983 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 }
5985 }
5986
5987 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005988 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 break;
5990 }
5991 }
5992
5993 return Changed ? &I : 0;
5994}
5995
5996Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005997 bool Changed = false;
5998
5999 /// Orders the operands of the compare so that they are listed from most
6000 /// complex to least complex. This puts constants before unary operators,
6001 /// before binary operators.
6002 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6003 I.swapOperands();
6004 Changed = true;
6005 }
6006
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006008
Chris Lattner210c5d42009-11-09 23:55:12 +00006009 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6010 return ReplaceInstUsesWith(I, V);
6011
6012 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006013
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006015 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006017 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006018 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006019 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006020 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006021 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006022 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006023 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006024
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006026 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006027 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006028 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006029 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006030 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006031 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006032 case ICmpInst::ICMP_SGT:
6033 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006034 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006035 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006036 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006037 return BinaryOperator::CreateAnd(Not, Op0);
6038 }
6039 case ICmpInst::ICMP_UGE:
6040 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6041 // FALL THROUGH
6042 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006043 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006044 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006045 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006046 case ICmpInst::ICMP_SGE:
6047 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6048 // FALL THROUGH
6049 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006050 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006051 return BinaryOperator::CreateOr(Not, Op0);
6052 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006053 }
Chris Lattner8b170942002-08-09 23:47:40 +00006054 }
6055
Dan Gohman1c8491e2009-04-25 17:12:48 +00006056 unsigned BitWidth = 0;
6057 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006058 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6059 else if (Ty->isIntOrIntVector())
6060 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006061
6062 bool isSignBit = false;
6063
Dan Gohman81b28ce2008-09-16 18:46:06 +00006064 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006065 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006066 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006067
Chris Lattnerb6566012008-01-05 01:18:20 +00006068 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6069 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006070 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006071 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006072 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006073 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006074
Dan Gohman81b28ce2008-09-16 18:46:06 +00006075 // If we have an icmp le or icmp ge instruction, turn it into the
6076 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006077 // them being folded in the code below. The SimplifyICmpInst code has
6078 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006079 switch (I.getPredicate()) {
6080 default: break;
6081 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006082 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006083 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006084 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006086 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006087 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006088 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006089 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006090 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006092 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006093 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006094 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006095 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006096 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006097 }
6098
Chris Lattner183661e2008-07-11 05:40:05 +00006099 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006100 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006101 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6103 }
6104
6105 // See if we can fold the comparison based on range information we can get
6106 // by checking whether bits are known to be zero or one in the input.
6107 if (BitWidth != 0) {
6108 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6109 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6110
6111 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006112 isSignBit ? APInt::getSignBit(BitWidth)
6113 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006115 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (SimplifyDemandedBits(I.getOperandUse(1),
6117 APInt::getAllOnesValue(BitWidth),
6118 Op1KnownZero, Op1KnownOne, 0))
6119 return &I;
6120
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006121 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006122 // in. Compute the Min, Max and RHS values based on the known bits. For the
6123 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6125 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006126 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6128 Op0Min, Op0Max);
6129 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6130 Op1Min, Op1Max);
6131 } else {
6132 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6133 Op0Min, Op0Max);
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6135 Op1Min, Op1Max);
6136 }
6137
Chris Lattner183661e2008-07-11 05:40:05 +00006138 // If Min and Max are known to be the same, then SimplifyDemandedBits
6139 // figured out that the LHS is a constant. Just constant fold this now so
6140 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006142 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006143 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006144 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006145 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006146 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147
Chris Lattner183661e2008-07-11 05:40:05 +00006148 // Based on the range information we know about the LHS, see if we can
6149 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006151 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006152 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006155 break;
6156 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006157 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006159 break;
6160 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006162 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006166 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6168 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006170 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171
6172 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6173 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006174 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006175 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 }
Chris Lattner84dff672008-07-11 05:08:55 +00006177 break;
6178 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006180 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006182 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006183
6184 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006185 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6187 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006188 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006189 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190
6191 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6192 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006193 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006194 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006195 }
Chris Lattner84dff672008-07-11 05:08:55 +00006196 break;
6197 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006201 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006203 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6205 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006207 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 }
Chris Lattner84dff672008-07-11 05:08:55 +00006209 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 case ICmpInst::ICMP_SGT:
6211 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006212 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006214 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215
6216 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006217 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6219 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006221 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 }
6223 break;
6224 case ICmpInst::ICMP_SGE:
6225 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6226 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006227 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006228 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006229 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230 break;
6231 case ICmpInst::ICMP_SLE:
6232 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6233 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006234 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006236 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006237 break;
6238 case ICmpInst::ICMP_UGE:
6239 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6240 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006241 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006242 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006243 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244 break;
6245 case ICmpInst::ICMP_ULE:
6246 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6247 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006248 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006249 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006250 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006251 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006252 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253
6254 // Turn a signed comparison into an unsigned one if both operands
6255 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006256 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006257 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6258 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006259 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006260 }
6261
6262 // Test if the ICmpInst instruction is used exclusively by a select as
6263 // part of a minimum or maximum operation. If so, refrain from doing
6264 // any other folding. This helps out other analyses which understand
6265 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6266 // and CodeGen. And in this case, at least one of the comparison
6267 // operands has at least one user besides the compare (the select),
6268 // which would often largely negate the benefit of folding anyway.
6269 if (I.hasOneUse())
6270 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6271 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6272 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6273 return 0;
6274
6275 // See if we are doing a comparison between a constant and an instruction that
6276 // can be folded into the comparison.
6277 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006279 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006281 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006282 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6283 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006284 }
6285
Chris Lattner01deb9d2007-04-03 17:43:25 +00006286 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006287 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6288 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6289 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006290 case Instruction::GetElementPtr:
6291 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006293 bool isAllZeros = true;
6294 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6295 if (!isa<Constant>(LHSI->getOperand(i)) ||
6296 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6297 isAllZeros = false;
6298 break;
6299 }
6300 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006301 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006302 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006303 }
6304 break;
6305
Chris Lattner6970b662005-04-23 15:31:55 +00006306 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006307 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006308 // block. If in the same block, we're encouraging jump threading. If
6309 // not, we are just pessimizing the code by making an i1 phi.
6310 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006311 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006312 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006313 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006314 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006315 // If either operand of the select is a constant, we can fold the
6316 // comparison into the select arms, which will cause one to be
6317 // constant folded and the select turned into a bitwise or.
6318 Value *Op1 = 0, *Op2 = 0;
6319 if (LHSI->hasOneUse()) {
6320 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6321 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006322 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006323 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006324 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6325 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006326 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6327 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006328 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006329 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006330 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6331 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006332 }
6333 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006334
Chris Lattner6970b662005-04-23 15:31:55 +00006335 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006336 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006337 break;
6338 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006339 case Instruction::Call:
6340 // If we have (malloc != null), and if the malloc has a single use, we
6341 // can assume it is successful and remove the malloc.
6342 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6343 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006344 // Need to explicitly erase malloc call here, instead of adding it to
6345 // Worklist, because it won't get DCE'd from the Worklist since
6346 // isInstructionTriviallyDead() returns false for function calls.
6347 // It is OK to replace LHSI/MallocCall with Undef because the
6348 // instruction that uses it will be erased via Worklist.
6349 if (extractMallocCall(LHSI)) {
6350 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6351 EraseInstFromFunction(*LHSI);
6352 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006353 ConstantInt::get(Type::getInt1Ty(*Context),
6354 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006355 }
6356 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6357 if (MallocCall->hasOneUse()) {
6358 MallocCall->replaceAllUsesWith(
6359 UndefValue::get(MallocCall->getType()));
6360 EraseInstFromFunction(*MallocCall);
6361 Worklist.Add(LHSI); // The malloc's bitcast use.
6362 return ReplaceInstUsesWith(I,
6363 ConstantInt::get(Type::getInt1Ty(*Context),
6364 !I.isTrueWhenEqual()));
6365 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006366 }
6367 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006368 }
Chris Lattner6970b662005-04-23 15:31:55 +00006369 }
6370
Reid Spencere4d87aa2006-12-23 06:05:41 +00006371 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006372 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006373 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006374 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006375 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006376 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6377 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006378 return NI;
6379
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006381 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6382 // now.
6383 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6384 if (isa<PointerType>(Op0->getType()) &&
6385 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006386 // We keep moving the cast from the left operand over to the right
6387 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006388 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006389
Chris Lattner57d86372007-01-06 01:45:59 +00006390 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6391 // so eliminate it as well.
6392 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6393 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006394
Chris Lattnerde90b762003-11-03 04:25:02 +00006395 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006396 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006397 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006398 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006399 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006400 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006401 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006402 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006403 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006404 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006405 }
Chris Lattner57d86372007-01-06 01:45:59 +00006406 }
6407
6408 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006409 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006410 // This comes up when you have code like
6411 // int X = A < B;
6412 // if (X) ...
6413 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006414 // with a constant or another cast from the same type.
6415 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006416 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006417 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006418 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006419
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006420 // See if it's the same type of instruction on the left and right.
6421 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6422 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006423 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006424 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006425 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006426 default: break;
6427 case Instruction::Add:
6428 case Instruction::Sub:
6429 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006430 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006431 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006432 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006433 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6434 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6435 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006436 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006437 ? I.getUnsignedPredicate()
6438 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006439 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006440 Op1I->getOperand(0));
6441 }
6442
6443 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006444 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006445 ? I.getUnsignedPredicate()
6446 : I.getSignedPredicate();
6447 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006448 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006449 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006450 }
6451 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006452 break;
6453 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006454 if (!I.isEquality())
6455 break;
6456
Nick Lewycky5d52c452008-08-21 05:56:10 +00006457 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6458 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6459 // Mask = -1 >> count-trailing-zeros(Cst).
6460 if (!CI->isZero() && !CI->isOne()) {
6461 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006462 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006463 APInt::getLowBitsSet(AP.getBitWidth(),
6464 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006465 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006466 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6467 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006468 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006469 }
6470 }
6471 break;
6472 }
6473 }
6474 }
6475 }
6476
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006477 // ~x < ~y --> y < x
6478 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006479 if (match(Op0, m_Not(m_Value(A))) &&
6480 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006481 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006482 }
6483
Chris Lattner65b72ba2006-09-18 04:22:48 +00006484 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006485 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006486
6487 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006488 if (match(Op0, m_Neg(m_Value(A))) &&
6489 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006490 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006491
Dan Gohman4ae51262009-08-12 16:23:25 +00006492 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006493 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6494 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006495 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006496 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006497 }
6498
Dan Gohman4ae51262009-08-12 16:23:25 +00006499 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006500 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006501 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006502 if (match(B, m_ConstantInt(C1)) &&
6503 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006504 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006505 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006506 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6507 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006508 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006509
6510 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006511 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6512 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6513 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6514 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006515 }
6516 }
6517
Dan Gohman4ae51262009-08-12 16:23:25 +00006518 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006519 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006520 // A == (A^B) -> B == 0
6521 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006522 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006523 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006524 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006525
6526 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006527 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006528 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006529 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006530
6531 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006532 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006533 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006534 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006535
Chris Lattner9c2328e2006-11-14 06:06:06 +00006536 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6537 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006538 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6539 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006540 Value *X = 0, *Y = 0, *Z = 0;
6541
6542 if (A == C) {
6543 X = B; Y = D; Z = A;
6544 } else if (A == D) {
6545 X = B; Y = C; Z = A;
6546 } else if (B == C) {
6547 X = A; Y = D; Z = B;
6548 } else if (B == D) {
6549 X = A; Y = C; Z = B;
6550 }
6551
6552 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006553 Op1 = Builder->CreateXor(X, Y, "tmp");
6554 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006555 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006556 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006557 return &I;
6558 }
6559 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006560 }
Chris Lattner7e708292002-06-25 16:13:24 +00006561 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006562}
6563
Chris Lattner562ef782007-06-20 23:46:26 +00006564
6565/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6566/// and CmpRHS are both known to be integer constants.
6567Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6568 ConstantInt *DivRHS) {
6569 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6570 const APInt &CmpRHSV = CmpRHS->getValue();
6571
6572 // FIXME: If the operand types don't match the type of the divide
6573 // then don't attempt this transform. The code below doesn't have the
6574 // logic to deal with a signed divide and an unsigned compare (and
6575 // vice versa). This is because (x /s C1) <s C2 produces different
6576 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6577 // (x /u C1) <u C2. Simply casting the operands and result won't
6578 // work. :( The if statement below tests that condition and bails
6579 // if it finds it.
6580 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006581 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006582 return 0;
6583 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006585 if (DivIsSigned && DivRHS->isAllOnesValue())
6586 return 0; // The overflow computation also screws up here
6587 if (DivRHS->isOne())
6588 return 0; // Not worth bothering, and eliminates some funny cases
6589 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006590
6591 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6592 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6593 // C2 (CI). By solving for X we can turn this into a range check
6594 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006595 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006596
6597 // Determine if the product overflows by seeing if the product is
6598 // not equal to the divide. Make sure we do the same kind of divide
6599 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006600 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6601 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006602
6603 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006604 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006605
Chris Lattner1dbfd482007-06-21 18:11:19 +00006606 // Figure out the interval that is being checked. For example, a comparison
6607 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6608 // Compute this interval based on the constants involved and the signedness of
6609 // the compare/divide. This computes a half-open interval, keeping track of
6610 // whether either value in the interval overflows. After analysis each
6611 // overflow variable is set to 0 if it's corresponding bound variable is valid
6612 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6613 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006614 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006615
Chris Lattner562ef782007-06-20 23:46:26 +00006616 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006618 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 HiOverflow = LoOverflow = ProdOV;
6620 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006621 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006622 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006623 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006625 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006626 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006627 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6629 HiOverflow = LoOverflow = ProdOV;
6630 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006631 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006632 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006633 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006634 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006635 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6636 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006637 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006638 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006639 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006640 true) ? -1 : 0;
6641 }
Chris Lattner562ef782007-06-20 23:46:26 +00006642 }
Dan Gohman76491272008-02-13 22:09:18 +00006643 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006644 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006645 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006646 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006647 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006648 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6649 HiOverflow = 1; // [INTMIN+1, overflow)
6650 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6651 }
Dan Gohman76491272008-02-13 22:09:18 +00006652 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006653 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006654 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006656 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006657 LoOverflow = AddWithOverflow(LoBound, HiBound,
6658 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006659 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006660 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6661 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006662 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006663 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006664 }
6665
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 // Dividing by a negative swaps the condition. LT <-> GT
6667 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006668 }
6669
6670 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006672 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006673 case ICmpInst::ICMP_EQ:
6674 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006675 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006676 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006677 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006678 ICmpInst::ICMP_UGE, X, LoBound);
6679 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006680 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006681 ICmpInst::ICMP_ULT, X, HiBound);
6682 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006683 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006684 case ICmpInst::ICMP_NE:
6685 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006686 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006687 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006688 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006689 ICmpInst::ICMP_ULT, X, LoBound);
6690 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006691 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006692 ICmpInst::ICMP_UGE, X, HiBound);
6693 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006694 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006695 case ICmpInst::ICMP_ULT:
6696 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006697 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006698 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006699 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006700 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006701 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006702 case ICmpInst::ICMP_UGT:
6703 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006704 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006705 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006706 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006707 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006708 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006709 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006710 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006711 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006712 }
6713}
6714
6715
Chris Lattner01deb9d2007-04-03 17:43:25 +00006716/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6717///
6718Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6719 Instruction *LHSI,
6720 ConstantInt *RHS) {
6721 const APInt &RHSV = RHS->getValue();
6722
6723 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006724 case Instruction::Trunc:
6725 if (ICI.isEquality() && LHSI->hasOneUse()) {
6726 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6727 // of the high bits truncated out of x are known.
6728 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6729 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6730 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6731 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6732 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6733
6734 // If all the high bits are known, we can do this xform.
6735 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6736 // Pull in the high bits from known-ones set.
6737 APInt NewRHS(RHS->getValue());
6738 NewRHS.zext(SrcBits);
6739 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006740 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006741 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006742 }
6743 }
6744 break;
6745
Duncan Sands0091bf22007-04-04 06:42:45 +00006746 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006747 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6748 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6749 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006750 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6751 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006752 Value *CompareVal = LHSI->getOperand(0);
6753
6754 // If the sign bit of the XorCST is not set, there is no change to
6755 // the operation, just stop using the Xor.
6756 if (!XorCST->getValue().isNegative()) {
6757 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006758 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006759 return &ICI;
6760 }
6761
6762 // Was the old condition true if the operand is positive?
6763 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6764
6765 // If so, the new one isn't.
6766 isTrueIfPositive ^= true;
6767
6768 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006769 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006770 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006772 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006773 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006775
6776 if (LHSI->hasOneUse()) {
6777 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6778 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6779 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006780 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006781 ? ICI.getUnsignedPredicate()
6782 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006783 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006784 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006785 }
6786
6787 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006788 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006789 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006790 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006791 ? ICI.getUnsignedPredicate()
6792 : ICI.getSignedPredicate();
6793 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006794 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006795 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006796 }
6797 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798 }
6799 break;
6800 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6801 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6802 LHSI->getOperand(0)->hasOneUse()) {
6803 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6804
6805 // If the LHS is an AND of a truncating cast, we can widen the
6806 // and/compare to be the input width without changing the value
6807 // produced, eliminating a cast.
6808 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6809 // We can do this transformation if either the AND constant does not
6810 // have its sign bit set or if it is an equality comparison.
6811 // Extending a relational comparison when we're checking the sign
6812 // bit would not work.
6813 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006814 (ICI.isEquality() ||
6815 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 uint32_t BitWidth =
6817 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6818 APInt NewCST = AndCST->getValue();
6819 NewCST.zext(BitWidth);
6820 APInt NewCI = RHSV;
6821 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006822 Value *NewAnd =
6823 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006824 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006825 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006826 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006827 }
6828 }
6829
6830 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6831 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6832 // happens a LOT in code produced by the C front-end, for bitfield
6833 // access.
6834 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6835 if (Shift && !Shift->isShift())
6836 Shift = 0;
6837
6838 ConstantInt *ShAmt;
6839 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6840 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6841 const Type *AndTy = AndCST->getType(); // Type of the and.
6842
6843 // We can fold this as long as we can't shift unknown bits
6844 // into the mask. This can only happen with signed shift
6845 // rights, as they sign-extend.
6846 if (ShAmt) {
6847 bool CanFold = Shift->isLogicalShift();
6848 if (!CanFold) {
6849 // To test for the bad case of the signed shr, see if any
6850 // of the bits shifted in could be tested after the mask.
6851 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6852 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6853
6854 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6855 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6856 AndCST->getValue()) == 0)
6857 CanFold = true;
6858 }
6859
6860 if (CanFold) {
6861 Constant *NewCst;
6862 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006863 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006864 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006865 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866
6867 // Check to see if we are shifting out any of the bits being
6868 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006869 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006870 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006871 // If we shifted bits out, the fold is not going to work out.
6872 // As a special case, check to see if this means that the
6873 // result is always true or false now.
6874 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006875 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006876 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006877 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 } else {
6879 ICI.setOperand(1, NewCst);
6880 Constant *NewAndCST;
6881 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006882 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006883 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006884 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006885 LHSI->setOperand(1, NewAndCST);
6886 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006887 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006888 return &ICI;
6889 }
6890 }
6891 }
6892
6893 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6894 // preferable because it allows the C<<Y expression to be hoisted out
6895 // of a loop if Y is invariant and X is not.
6896 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006897 ICI.isEquality() && !Shift->isArithmeticShift() &&
6898 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 // Compute C << Y.
6900 Value *NS;
6901 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006902 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006903 } else {
6904 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006905 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006906 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006907
6908 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006909 Value *NewAnd =
6910 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911
6912 ICI.setOperand(0, NewAnd);
6913 return &ICI;
6914 }
6915 }
6916 break;
6917
Chris Lattnera0141b92007-07-15 20:42:37 +00006918 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6919 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6920 if (!ShAmt) break;
6921
6922 uint32_t TypeBits = RHSV.getBitWidth();
6923
6924 // Check that the shift amount is in range. If not, don't perform
6925 // undefined shifts. When the shift is visited it will be
6926 // simplified.
6927 if (ShAmt->uge(TypeBits))
6928 break;
6929
6930 if (ICI.isEquality()) {
6931 // If we are comparing against bits always shifted out, the
6932 // comparison cannot succeed.
6933 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006934 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006935 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006936 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6937 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006938 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006939 return ReplaceInstUsesWith(ICI, Cst);
6940 }
6941
6942 if (LHSI->hasOneUse()) {
6943 // Otherwise strength reduce the shift into an and.
6944 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6945 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006946 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006947 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006948
Chris Lattner74381062009-08-30 07:44:24 +00006949 Value *And =
6950 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006951 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006952 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006953 }
6954 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006955
6956 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957 bool TrueIfSigned = false;
6958 if (LHSI->hasOneUse() &&
6959 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006961 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006962 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006963 Value *And =
6964 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006965 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006966 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006967 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006968 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006969 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006970
6971 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006972 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006973 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006974 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006975 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006976
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 // Check that the shift amount is in range. If not, don't perform
6978 // undefined shifts. When the shift is visited it will be
6979 // simplified.
6980 uint32_t TypeBits = RHSV.getBitWidth();
6981 if (ShAmt->uge(TypeBits))
6982 break;
6983
6984 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006985
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006986 // If we are comparing against bits always shifted out, the
6987 // comparison cannot succeed.
6988 APInt Comp = RHSV << ShAmtVal;
6989 if (LHSI->getOpcode() == Instruction::LShr)
6990 Comp = Comp.lshr(ShAmtVal);
6991 else
6992 Comp = Comp.ashr(ShAmtVal);
6993
6994 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6995 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006996 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006997 return ReplaceInstUsesWith(ICI, Cst);
6998 }
6999
7000 // Otherwise, check to see if the bits shifted out are known to be zero.
7001 // If so, we can compare against the unshifted value:
7002 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007003 if (LHSI->hasOneUse() &&
7004 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007005 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007006 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007007 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007008 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007009
Evan Chengf30752c2008-04-23 00:38:06 +00007010 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007011 // Otherwise strength reduce the shift into an and.
7012 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007013 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007014
Chris Lattner74381062009-08-30 07:44:24 +00007015 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7016 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007017 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007018 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 }
7020 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007021 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022
7023 case Instruction::SDiv:
7024 case Instruction::UDiv:
7025 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026 // Fold this div into the comparison, producing a range check.
7027 // Determine, based on the divide type, what the range is being
7028 // checked. If there is an overflow on the low or high side, remember
7029 // it, otherwise compute the range [low, hi) bounding the new value.
7030 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007031 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033 DivRHS))
7034 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007035 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007036
7037 case Instruction::Add:
7038 // Fold: icmp pred (add, X, C1), C2
7039
7040 if (!ICI.isEquality()) {
7041 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042 if (!LHSC) break;
7043 const APInt &LHSV = LHSC->getValue();
7044
7045 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046 .subtract(LHSV);
7047
Nick Lewycky4a134af2009-10-25 05:20:17 +00007048 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007049 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007050 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007051 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007052 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007053 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007054 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007055 }
7056 } else {
7057 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007058 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007059 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007060 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007061 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007062 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007063 }
7064 }
7065 }
7066 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007067 }
7068
7069 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070 if (ICI.isEquality()) {
7071 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072
7073 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7074 // the second operand is a constant, simplify a bit.
7075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076 switch (BO->getOpcode()) {
7077 case Instruction::SRem:
7078 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007082 Value *NewRem =
7083 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7084 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007085 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007086 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007087 }
7088 }
7089 break;
7090 case Instruction::Add:
7091 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7092 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7093 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007094 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007095 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 } else if (RHSV == 0) {
7097 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7098 // efficiently invertible, or if the add has just this one use.
7099 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7100
Dan Gohman186a6362009-08-12 16:04:34 +00007101 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007102 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007103 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007105 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007106 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007107 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007108 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 }
7110 }
7111 break;
7112 case Instruction::Xor:
7113 // For the xor case, we can xor two constants together, eliminating
7114 // the explicit xor.
7115 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007116 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007117 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007118
7119 // FALLTHROUGH
7120 case Instruction::Sub:
7121 // Replace (([sub|xor] A, B) != 0) with (A != B)
7122 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007123 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 BO->getOperand(1));
7125 break;
7126
7127 case Instruction::Or:
7128 // If bits are being or'd in that are not present in the constant we
7129 // are comparing against, then the comparison could never succeed!
7130 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007131 Constant *NotCI = ConstantExpr::getNot(RHS);
7132 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007133 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007134 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007135 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007136 }
7137 break;
7138
7139 case Instruction::And:
7140 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7141 // If bits are being compared against that are and'd out, then the
7142 // comparison can never succeed!
7143 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007144 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007145 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007146 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147
7148 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7149 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007150 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007151 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007152 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153
7154 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007155 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007157 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007158 ICmpInst::Predicate pred = isICMP_NE ?
7159 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007160 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007161 }
7162
7163 // ((X & ~7) == 0) --> X < 8
7164 if (RHSV == 0 && isHighOnes(BOC)) {
7165 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007166 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 ICmpInst::Predicate pred = isICMP_NE ?
7168 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007169 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007170 }
7171 }
7172 default: break;
7173 }
7174 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7175 // Handle icmp {eq|ne} <intrinsic>, intcst.
7176 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007177 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007178 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007179 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007180 return &ICI;
7181 }
7182 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007183 }
7184 return 0;
7185}
7186
7187/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7188/// We only handle extending casts so far.
7189///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7191 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007192 Value *LHSCIOp = LHSCI->getOperand(0);
7193 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007195 Value *RHSCIOp;
7196
Chris Lattner8c756c12007-05-05 22:41:33 +00007197 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7198 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007199 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7200 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007201 cast<IntegerType>(DestTy)->getBitWidth()) {
7202 Value *RHSOp = 0;
7203 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007204 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007205 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7206 RHSOp = RHSC->getOperand(0);
7207 // If the pointer types don't match, insert a bitcast.
7208 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007209 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007210 }
7211
7212 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007213 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007214 }
7215
7216 // The code below only handles extension cast instructions, so far.
7217 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007218 if (LHSCI->getOpcode() != Instruction::ZExt &&
7219 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007220 return 0;
7221
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007223 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007224
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007226 // Not an extension from the same type?
7227 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 if (RHSCIOp->getType() != LHSCIOp->getType())
7229 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007230
Nick Lewycky4189a532008-01-28 03:48:02 +00007231 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007232 // and the other is a zext), then we can't handle this.
7233 if (CI->getOpcode() != LHSCI->getOpcode())
7234 return 0;
7235
Nick Lewycky4189a532008-01-28 03:48:02 +00007236 // Deal with equality cases early.
7237 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007238 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007239
7240 // A signed comparison of sign extended values simplifies into a
7241 // signed comparison.
7242 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007243 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007244
7245 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007246 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007247 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007248
Reid Spencere4d87aa2006-12-23 06:05:41 +00007249 // If we aren't dealing with a constant on the RHS, exit early
7250 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7251 if (!CI)
7252 return 0;
7253
7254 // Compute the constant that would happen if we truncated to SrcTy then
7255 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007256 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7257 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007258 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259
7260 // If the re-extended constant didn't change...
7261 if (Res2 == CI) {
7262 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7263 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007264 // %A = sext i16 %X to i32
7265 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007267 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 // because %A may have negative value.
7269 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007270 // However, we allow this when the compare is EQ/NE, because they are
7271 // signless.
7272 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007273 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007274 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 }
7276
7277 // The re-extended constant changed so the constant cannot be represented
7278 // in the shorter type. Consequently, we cannot emit a simple comparison.
7279
7280 // First, handle some easy cases. We know the result cannot be equal at this
7281 // point so handle the ICI.isEquality() cases
7282 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007283 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007285 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286
7287 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7288 // should have been folded away previously and not enter in here.
7289 Value *Result;
7290 if (isSignedCmp) {
7291 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007292 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007293 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007294 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007295 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 } else {
7297 // We're performing an unsigned comparison.
7298 if (isSignedExt) {
7299 // We're performing an unsigned comp with a sign extended value.
7300 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007301 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007302 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007303 } else {
7304 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007305 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007306 }
7307 }
7308
7309 // Finally, return the value computed.
7310 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007311 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007312 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007313
7314 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7315 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7316 "ICmp should be folded!");
7317 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007318 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007319 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007320}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007321
Reid Spencer832254e2007-02-02 02:16:23 +00007322Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7323 return commonShiftTransforms(I);
7324}
7325
7326Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7327 return commonShiftTransforms(I);
7328}
7329
7330Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007331 if (Instruction *R = commonShiftTransforms(I))
7332 return R;
7333
7334 Value *Op0 = I.getOperand(0);
7335
7336 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7337 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7338 if (CSI->isAllOnesValue())
7339 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007340
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007341 // See if we can turn a signed shr into an unsigned shr.
7342 if (MaskedValueIsZero(Op0,
7343 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7344 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7345
7346 // Arithmetic shifting an all-sign-bit value is a no-op.
7347 unsigned NumSignBits = ComputeNumSignBits(Op0);
7348 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7349 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007350
Chris Lattner348f6652007-12-06 01:59:46 +00007351 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007352}
7353
7354Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7355 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007356 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007357
7358 // shl X, 0 == X and shr X, 0 == X
7359 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007360 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7361 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007362 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007363
Reid Spencere4d87aa2006-12-23 06:05:41 +00007364 if (isa<UndefValue>(Op0)) {
7365 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007366 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007367 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007369 }
7370 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007371 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7372 return ReplaceInstUsesWith(I, Op0);
7373 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007375 }
7376
Dan Gohman9004c8a2009-05-21 02:28:33 +00007377 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007378 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007379 return &I;
7380
Chris Lattner2eefe512004-04-09 19:05:30 +00007381 // Try to fold constant and into select arguments.
7382 if (isa<Constant>(Op0))
7383 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007385 return R;
7386
Reid Spencerb83eb642006-10-20 07:07:24 +00007387 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007388 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7389 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007390 return 0;
7391}
7392
Reid Spencerb83eb642006-10-20 07:07:24 +00007393Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007394 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007395 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007397 // See if we can simplify any instructions used by the instruction whose sole
7398 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007399 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007400
Dan Gohmana119de82009-06-14 23:30:43 +00007401 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7402 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007403 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007404 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007405 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007406 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007407 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007408 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007410 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007411 }
7412
7413 // ((X*C1) << C2) == (X * (C1 << C2))
7414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7415 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7416 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007418 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007419
7420 // Try to fold constant and into select arguments.
7421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7423 return R;
7424 if (isa<PHINode>(Op0))
7425 if (Instruction *NV = FoldOpIntoPhi(I))
7426 return NV;
7427
Chris Lattner8999dd32007-12-22 09:07:47 +00007428 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7429 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7430 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7431 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7432 // place. Don't try to do this transformation in this case. Also, we
7433 // require that the input operand is a shift-by-constant so that we have
7434 // confidence that the shifts will get folded together. We could do this
7435 // xform in more cases, but it is unlikely to be profitable.
7436 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7437 isa<ConstantInt>(TrOp->getOperand(1))) {
7438 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007439 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007440 // (shift2 (shift1 & 0x00FF), c2)
7441 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007442
7443 // For logical shifts, the truncation has the effect of making the high
7444 // part of the register be zeros. Emulate this by inserting an AND to
7445 // clear the top bits as needed. This 'and' will usually be zapped by
7446 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007447 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7448 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007449 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7450
7451 // The mask we constructed says what the trunc would do if occurring
7452 // between the shifts. We want to know the effect *after* the second
7453 // shift. We know that it is a logical shift by a constant, so adjust the
7454 // mask as appropriate.
7455 if (I.getOpcode() == Instruction::Shl)
7456 MaskV <<= Op1->getZExtValue();
7457 else {
7458 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7459 MaskV = MaskV.lshr(Op1->getZExtValue());
7460 }
7461
Chris Lattner74381062009-08-30 07:44:24 +00007462 // shift1 & 0x00FF
7463 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7464 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007465
7466 // Return the value truncated to the interesting size.
7467 return new TruncInst(And, I.getType());
7468 }
7469 }
7470
Chris Lattner4d5542c2006-01-06 07:12:35 +00007471 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007472 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7473 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7474 Value *V1, *V2;
7475 ConstantInt *CC;
7476 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007477 default: break;
7478 case Instruction::Add:
7479 case Instruction::And:
7480 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007481 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007482 // These operators commute.
7483 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007484 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007485 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007486 m_Specific(Op1)))) {
7487 Value *YS = // (Y << C)
7488 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7489 // (X + (Y << C))
7490 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7491 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007492 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007493 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007494 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007495 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007496
Chris Lattner150f12a2005-09-18 06:30:59 +00007497 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007498 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007499 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007500 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007501 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007502 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007503 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007504 Value *YS = // (Y << C)
7505 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7506 Op0BO->getName());
7507 // X & (CC << C)
7508 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7509 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007510 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007511 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007512 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007513
Reid Spencera07cb7d2007-02-02 14:41:37 +00007514 // FALL THROUGH.
7515 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007516 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007517 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007518 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007519 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007520 Value *YS = // (Y << C)
7521 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7522 // (X + (Y << C))
7523 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7524 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007525 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007526 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007527 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007528 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007529
Chris Lattner13d4ab42006-05-31 21:14:00 +00007530 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007531 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7532 match(Op0BO->getOperand(0),
7533 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007534 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007535 cast<BinaryOperator>(Op0BO->getOperand(0))
7536 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007537 Value *YS = // (Y << C)
7538 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7539 // X & (CC << C)
7540 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7541 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007542
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007544 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007545
Chris Lattner11021cb2005-09-18 05:12:10 +00007546 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007547 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007548 }
7549
7550
7551 // If the operand is an bitwise operator with a constant RHS, and the
7552 // shift is the only use, we can pull it out of the shift.
7553 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7554 bool isValid = true; // Valid only for And, Or, Xor
7555 bool highBitSet = false; // Transform if high bit of constant set?
7556
7557 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007558 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007559 case Instruction::Add:
7560 isValid = isLeftShift;
7561 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007562 case Instruction::Or:
7563 case Instruction::Xor:
7564 highBitSet = false;
7565 break;
7566 case Instruction::And:
7567 highBitSet = true;
7568 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007569 }
7570
7571 // If this is a signed shift right, and the high bit is modified
7572 // by the logical operation, do not perform the transformation.
7573 // The highBitSet boolean indicates the value of the high bit of
7574 // the constant which would cause it to be modified for this
7575 // operation.
7576 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007577 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007578 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007579
7580 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007581 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007582
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007583 Value *NewShift =
7584 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007585 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007586
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007587 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588 NewRHS);
7589 }
7590 }
7591 }
7592 }
7593
Chris Lattnerad0124c2006-01-06 07:52:12 +00007594 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007595 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7596 if (ShiftOp && !ShiftOp->isShift())
7597 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007598
Reid Spencerb83eb642006-10-20 07:07:24 +00007599 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007600 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007601 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7602 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007603 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7604 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7605 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007606
Zhou Sheng4351c642007-04-02 08:20:41 +00007607 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608
7609 const IntegerType *Ty = cast<IntegerType>(I.getType());
7610
7611 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007612 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007613 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7614 // saturates.
7615 if (AmtSum >= TypeBits) {
7616 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007618 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7619 }
7620
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007621 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007622 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007623 }
7624
7625 if (ShiftOp->getOpcode() == Instruction::LShr &&
7626 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007627 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007629
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007631 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007632 }
7633
7634 if (ShiftOp->getOpcode() == Instruction::AShr &&
7635 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007636 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007637 if (AmtSum >= TypeBits)
7638 AmtSum = TypeBits-1;
7639
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007640 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007641
Zhou Shenge9e03f62007-03-28 15:02:20 +00007642 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007643 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007644 }
7645
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 // Okay, if we get here, one shift must be left, and the other shift must be
7647 // right. See if the amounts are equal.
7648 if (ShiftAmt1 == ShiftAmt2) {
7649 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7650 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007651 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007652 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 }
7654 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7655 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007656 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007657 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007658 }
7659 // We can simplify ((X << C) >>s C) into a trunc + sext.
7660 // NOTE: we could do this for any C, but that would make 'unusual' integer
7661 // types. For now, just stick to ones well-supported by the code
7662 // generators.
7663 const Type *SExtType = 0;
7664 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007665 case 1 :
7666 case 8 :
7667 case 16 :
7668 case 32 :
7669 case 64 :
7670 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007671 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007672 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673 default: break;
7674 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007675 if (SExtType)
7676 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007677 // Otherwise, we can't handle it yet.
7678 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007679 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007680
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007681 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007682 if (I.getOpcode() == Instruction::Shl) {
7683 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7684 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007685 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007686
Reid Spencer55702aa2007-03-25 21:11:44 +00007687 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007688 return BinaryOperator::CreateAnd(Shift,
7689 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007690 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007691
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007692 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693 if (I.getOpcode() == Instruction::LShr) {
7694 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007695 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007696
Reid Spencerd5e30f02007-03-26 17:18:58 +00007697 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007698 return BinaryOperator::CreateAnd(Shift,
7699 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007700 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701
7702 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7703 } else {
7704 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007705 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007706
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007707 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708 if (I.getOpcode() == Instruction::Shl) {
7709 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7710 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007711 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7712 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713
Reid Spencer55702aa2007-03-25 21:11:44 +00007714 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007715 return BinaryOperator::CreateAnd(Shift,
7716 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 }
7718
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007719 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007720 if (I.getOpcode() == Instruction::LShr) {
7721 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007722 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007723
Reid Spencer68d27cf2007-03-26 23:45:51 +00007724 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007725 return BinaryOperator::CreateAnd(Shift,
7726 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007727 }
7728
7729 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007730 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007731 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007732 return 0;
7733}
7734
Chris Lattnera1be5662002-05-02 17:06:02 +00007735
Chris Lattnercfd65102005-10-29 04:36:15 +00007736/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7737/// expression. If so, decompose it, returning some value X, such that Val is
7738/// X*Scale+Offset.
7739///
7740static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007741 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007742 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7743 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007744 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007745 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007746 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007747 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007748 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7749 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7750 if (I->getOpcode() == Instruction::Shl) {
7751 // This is a value scaled by '1 << the shift amt'.
7752 Scale = 1U << RHS->getZExtValue();
7753 Offset = 0;
7754 return I->getOperand(0);
7755 } else if (I->getOpcode() == Instruction::Mul) {
7756 // This value is scaled by 'RHS'.
7757 Scale = RHS->getZExtValue();
7758 Offset = 0;
7759 return I->getOperand(0);
7760 } else if (I->getOpcode() == Instruction::Add) {
7761 // We have X+C. Check to see if we really have (X*C2)+C1,
7762 // where C1 is divisible by C2.
7763 unsigned SubScale;
7764 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007765 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7766 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007767 Offset += RHS->getZExtValue();
7768 Scale = SubScale;
7769 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007770 }
7771 }
7772 }
7773
7774 // Otherwise, we can't look past this.
7775 Scale = 1;
7776 Offset = 0;
7777 return Val;
7778}
7779
7780
Chris Lattnerb3f83972005-10-24 06:03:58 +00007781/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7782/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007783Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007784 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007785 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007786
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007787 BuilderTy AllocaBuilder(*Builder);
7788 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7789
Chris Lattnerb53c2382005-10-24 06:22:12 +00007790 // Remove any uses of AI that are dead.
7791 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007792
Chris Lattnerb53c2382005-10-24 06:22:12 +00007793 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7794 Instruction *User = cast<Instruction>(*UI++);
7795 if (isInstructionTriviallyDead(User)) {
7796 while (UI != E && *UI == User)
7797 ++UI; // If this instruction uses AI more than once, don't break UI.
7798
Chris Lattnerb53c2382005-10-24 06:22:12 +00007799 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007800 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007801 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007802 }
7803 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007804
7805 // This requires TargetData to get the alloca alignment and size information.
7806 if (!TD) return 0;
7807
Chris Lattnerb3f83972005-10-24 06:03:58 +00007808 // Get the type really allocated and the type casted to.
7809 const Type *AllocElTy = AI.getAllocatedType();
7810 const Type *CastElTy = PTy->getElementType();
7811 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007812
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007813 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7814 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007815 if (CastElTyAlign < AllocElTyAlign) return 0;
7816
Chris Lattner39387a52005-10-24 06:35:18 +00007817 // If the allocation has multiple uses, only promote it if we are strictly
7818 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007819 // same, we open the door to infinite loops of various kinds. (A reference
7820 // from a dbg.declare doesn't count as a use for this purpose.)
7821 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7822 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007823
Duncan Sands777d2302009-05-09 07:06:46 +00007824 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7825 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007826 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007827
Chris Lattner455fcc82005-10-29 03:19:53 +00007828 // See if we can satisfy the modulus by pulling a scale out of the array
7829 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007830 unsigned ArraySizeScale;
7831 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007832 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007833 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7834 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007835
Chris Lattner455fcc82005-10-29 03:19:53 +00007836 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7837 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007838 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7839 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007840
Chris Lattner455fcc82005-10-29 03:19:53 +00007841 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7842 Value *Amt = 0;
7843 if (Scale == 1) {
7844 Amt = NumElements;
7845 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007846 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007847 // Insert before the alloca, not before the cast.
7848 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007849 }
7850
Jeff Cohen86796be2007-04-04 16:58:57 +00007851 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007852 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007853 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007854 }
7855
Victor Hernandez7b929da2009-10-23 21:09:37 +00007856 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007857 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007858 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007859
Dale Johannesena0a66372009-03-05 00:39:02 +00007860 // If the allocation has one real use plus a dbg.declare, just remove the
7861 // declare.
7862 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7863 EraseInstFromFunction(*DI);
7864 }
7865 // If the allocation has multiple real uses, insert a cast and change all
7866 // things that used it to use the new cast. This will also hack on CI, but it
7867 // will die soon.
7868 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007869 // New is the allocation instruction, pointer typed. AI is the original
7870 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007871 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007872 AI.replaceAllUsesWith(NewCast);
7873 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007874 return ReplaceInstUsesWith(CI, New);
7875}
7876
Chris Lattner70074e02006-05-13 02:06:03 +00007877/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007878/// and return it as type Ty without inserting any new casts and without
7879/// changing the computed value. This is used by code that tries to decide
7880/// whether promoting or shrinking integer operations to wider or smaller types
7881/// will allow us to eliminate a truncate or extend.
7882///
7883/// This is a truncation operation if Ty is smaller than V->getType(), or an
7884/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007885///
7886/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7887/// should return true if trunc(V) can be computed by computing V in the smaller
7888/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7889/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7890/// efficiently truncated.
7891///
7892/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7893/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7894/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007895bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007896 unsigned CastOpc,
7897 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007898 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007899 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007901
7902 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007903 if (!I) return false;
7904
Dan Gohman6de29f82009-06-15 22:12:54 +00007905 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007906
Chris Lattner951626b2007-08-02 06:11:14 +00007907 // If this is an extension or truncate, we can often eliminate it.
7908 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7909 // If this is a cast from the destination type, we can trivially eliminate
7910 // it, and this will remove a cast overall.
7911 if (I->getOperand(0)->getType() == Ty) {
7912 // If the first operand is itself a cast, and is eliminable, do not count
7913 // this as an eliminable cast. We would prefer to eliminate those two
7914 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007915 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007916 ++NumCastsRemoved;
7917 return true;
7918 }
7919 }
7920
7921 // We can't extend or shrink something that has multiple uses: doing so would
7922 // require duplicating the instruction in general, which isn't profitable.
7923 if (!I->hasOneUse()) return false;
7924
Evan Chengf35fd542009-01-15 17:01:23 +00007925 unsigned Opc = I->getOpcode();
7926 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007927 case Instruction::Add:
7928 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007929 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007930 case Instruction::And:
7931 case Instruction::Or:
7932 case Instruction::Xor:
7933 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007934 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007935 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007936 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007937 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938
Eli Friedman070a9812009-07-13 22:46:01 +00007939 case Instruction::UDiv:
7940 case Instruction::URem: {
7941 // UDiv and URem can be truncated if all the truncated bits are zero.
7942 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7943 uint32_t BitWidth = Ty->getScalarSizeInBits();
7944 if (BitWidth < OrigBitWidth) {
7945 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7946 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7947 MaskedValueIsZero(I->getOperand(1), Mask)) {
7948 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7949 NumCastsRemoved) &&
7950 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7951 NumCastsRemoved);
7952 }
7953 }
7954 break;
7955 }
Chris Lattner46b96052006-11-29 07:18:39 +00007956 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007957 // If we are truncating the result of this SHL, and if it's a shift of a
7958 // constant amount, we can always perform a SHL in a smaller type.
7959 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007960 uint32_t BitWidth = Ty->getScalarSizeInBits();
7961 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007962 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007963 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007964 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007965 }
7966 break;
7967 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007968 // If this is a truncate of a logical shr, we can truncate it to a smaller
7969 // lshr iff we know that the bits we would otherwise be shifting in are
7970 // already zeros.
7971 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007972 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7973 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007974 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007975 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007976 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7977 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007978 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007979 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007980 }
7981 }
Chris Lattner46b96052006-11-29 07:18:39 +00007982 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007983 case Instruction::ZExt:
7984 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007985 case Instruction::Trunc:
7986 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007987 // can safely replace it. Note that replacing it does not reduce the number
7988 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007989 if (Opc == CastOpc)
7990 return true;
7991
7992 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007993 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007994 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007995 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007996 case Instruction::Select: {
7997 SelectInst *SI = cast<SelectInst>(I);
7998 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007999 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008000 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008001 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008002 }
Chris Lattner8114b712008-06-18 04:00:49 +00008003 case Instruction::PHI: {
8004 // We can change a phi if we can change all operands.
8005 PHINode *PN = cast<PHINode>(I);
8006 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8007 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008008 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008009 return false;
8010 return true;
8011 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008013 // TODO: Can handle more cases here.
8014 break;
8015 }
8016
8017 return false;
8018}
8019
8020/// EvaluateInDifferentType - Given an expression that
8021/// CanEvaluateInDifferentType returns true for, actually insert the code to
8022/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008023Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008024 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008025 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008026 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008027
8028 // Otherwise, it must be an instruction.
8029 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008030 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008031 unsigned Opc = I->getOpcode();
8032 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008033 case Instruction::Add:
8034 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008035 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008036 case Instruction::And:
8037 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008038 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008039 case Instruction::AShr:
8040 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008041 case Instruction::Shl:
8042 case Instruction::UDiv:
8043 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008044 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008045 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008046 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008047 break;
8048 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 case Instruction::Trunc:
8050 case Instruction::ZExt:
8051 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008053 // just return the source. There's no need to insert it because it is not
8054 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008055 if (I->getOperand(0)->getType() == Ty)
8056 return I->getOperand(0);
8057
Chris Lattner8114b712008-06-18 04:00:49 +00008058 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008059 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008060 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008061 case Instruction::Select: {
8062 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8063 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8064 Res = SelectInst::Create(I->getOperand(0), True, False);
8065 break;
8066 }
Chris Lattner8114b712008-06-18 04:00:49 +00008067 case Instruction::PHI: {
8068 PHINode *OPN = cast<PHINode>(I);
8069 PHINode *NPN = PHINode::Create(Ty);
8070 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8071 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8072 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8073 }
8074 Res = NPN;
8075 break;
8076 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008077 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008078 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008079 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008080 break;
8081 }
8082
Chris Lattner8114b712008-06-18 04:00:49 +00008083 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008084 return InsertNewInstBefore(Res, *I);
8085}
8086
Reid Spencer3da59db2006-11-27 01:05:10 +00008087/// @brief Implement the transforms common to all CastInst visitors.
8088Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008089 Value *Src = CI.getOperand(0);
8090
Dan Gohman23d9d272007-05-11 21:10:54 +00008091 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008092 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008093 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008094 if (Instruction::CastOps opc =
8095 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8096 // The first cast (CSrc) is eliminable so we need to fix up or replace
8097 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008098 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008099 }
8100 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008101
Reid Spencer3da59db2006-11-27 01:05:10 +00008102 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008103 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8104 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8105 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008106
8107 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008108 if (isa<PHINode>(Src)) {
8109 // We don't do this if this would create a PHI node with an illegal type if
8110 // it is currently legal.
8111 if (!isa<IntegerType>(Src->getType()) ||
8112 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008113 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008114 if (Instruction *NV = FoldOpIntoPhi(CI))
8115 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008116 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008117
Reid Spencer3da59db2006-11-27 01:05:10 +00008118 return 0;
8119}
8120
Chris Lattner46cd5a12009-01-09 05:44:56 +00008121/// FindElementAtOffset - Given a type and a constant offset, determine whether
8122/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008123/// the specified offset. If so, fill them into NewIndices and return the
8124/// resultant element type, otherwise return null.
8125static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8126 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008127 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008128 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008129 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008130 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008131
8132 // Start with the index over the outer type. Note that the type size
8133 // might be zero (even if the offset isn't zero) if the indexed type
8134 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008135 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008137 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008138 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008139 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008141 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008142 if (Offset < 0) {
8143 --FirstIdx;
8144 Offset += TySize;
8145 assert(Offset >= 0);
8146 }
8147 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8148 }
8149
Owen Andersoneed707b2009-07-24 23:12:02 +00008150 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008151
8152 // Index into the types. If we fail, set OrigBase to null.
8153 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008154 // Indexing into tail padding between struct/array elements.
8155 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008156 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008157
Chris Lattner46cd5a12009-01-09 05:44:56 +00008158 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8159 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008160 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8161 "Offset must stay within the indexed type");
8162
Chris Lattner46cd5a12009-01-09 05:44:56 +00008163 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008164 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008165
8166 Offset -= SL->getElementOffset(Elt);
8167 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008168 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008169 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008170 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008171 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008172 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008173 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008175 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008176 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008177 }
8178 }
8179
Chris Lattner3914f722009-01-24 01:00:13 +00008180 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008181}
8182
Chris Lattnerd3e28342007-04-27 17:44:50 +00008183/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8184Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8185 Value *Src = CI.getOperand(0);
8186
Chris Lattnerd3e28342007-04-27 17:44:50 +00008187 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008188 // If casting the result of a getelementptr instruction with no offset, turn
8189 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008190 if (GEP->hasAllZeroIndices()) {
8191 // Changing the cast operand is usually not a good idea but it is safe
8192 // here because the pointer operand is being replaced with another
8193 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008194 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008195 CI.setOperand(0, GEP->getOperand(0));
8196 return &CI;
8197 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008198
8199 // If the GEP has a single use, and the base pointer is a bitcast, and the
8200 // GEP computes a constant offset, see if we can convert these three
8201 // instructions into fewer. This typically happens with unions and other
8202 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008203 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008204 if (GEP->hasAllConstantIndices()) {
8205 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008206 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008207 int64_t Offset = OffsetV->getSExtValue();
8208
8209 // Get the base pointer input of the bitcast, and the type it points to.
8210 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8211 const Type *GEPIdxTy =
8212 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008213 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008214 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008215 // If we were able to index down into an element, create the GEP
8216 // and bitcast the result. This eliminates one bitcast, potentially
8217 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008218 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8219 Builder->CreateInBoundsGEP(OrigBase,
8220 NewIndices.begin(), NewIndices.end()) :
8221 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008222 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008223
Chris Lattner46cd5a12009-01-09 05:44:56 +00008224 if (isa<BitCastInst>(CI))
8225 return new BitCastInst(NGEP, CI.getType());
8226 assert(isa<PtrToIntInst>(CI));
8227 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008228 }
8229 }
8230 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008231 }
8232
8233 return commonCastTransforms(CI);
8234}
8235
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008236/// commonIntCastTransforms - This function implements the common transforms
8237/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008238Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8239 if (Instruction *Result = commonCastTransforms(CI))
8240 return Result;
8241
8242 Value *Src = CI.getOperand(0);
8243 const Type *SrcTy = Src->getType();
8244 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008245 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8246 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008247
Reid Spencer3da59db2006-11-27 01:05:10 +00008248 // See if we can simplify any instructions used by the LHS whose sole
8249 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008250 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008251 return &CI;
8252
8253 // If the source isn't an instruction or has more than one use then we
8254 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008255 Instruction *SrcI = dyn_cast<Instruction>(Src);
8256 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008257 return 0;
8258
Chris Lattnerc739cd62007-03-03 05:27:34 +00008259 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008260 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008261 // Only do this if the dest type is a simple type, don't convert the
8262 // expression tree to something weird like i93 unless the source is also
8263 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008264 if ((isa<VectorType>(DestTy) ||
8265 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8266 CanEvaluateInDifferentType(SrcI, DestTy,
8267 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008269 // eliminates the cast, so it is always a win. If this is a zero-extension,
8270 // we need to do an AND to maintain the clear top-part of the computation,
8271 // so we require that the input have eliminated at least one cast. If this
8272 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008274 bool DoXForm = false;
8275 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008276 switch (CI.getOpcode()) {
8277 default:
8278 // All the others use floating point so we shouldn't actually
8279 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008280 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008281 case Instruction::Trunc:
8282 DoXForm = true;
8283 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008284 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008285 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008286
Chris Lattner39c27ed2009-01-31 19:05:27 +00008287 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008288 // If it's unnecessary to issue an AND to clear the high bits, it's
8289 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008290 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008291 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8292 if (MaskedValueIsZero(TryRes, Mask))
8293 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008294
8295 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008296 if (TryI->use_empty())
8297 EraseInstFromFunction(*TryI);
8298 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008299 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008300 }
Evan Chengf35fd542009-01-15 17:01:23 +00008301 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008302 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008303 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008304 // If we do not have to emit the truncate + sext pair, then it's always
8305 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008306 //
8307 // It's not safe to eliminate the trunc + sext pair if one of the
8308 // eliminated cast is a truncate. e.g.
8309 // t2 = trunc i32 t1 to i16
8310 // t3 = sext i16 t2 to i32
8311 // !=
8312 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008313 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008314 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8315 if (NumSignBits > (DestBitSize - SrcBitSize))
8316 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008317
8318 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 if (TryI->use_empty())
8320 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008321 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008322 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008323 }
Evan Chengf35fd542009-01-15 17:01:23 +00008324 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008325
8326 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008327 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8328 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008329 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8330 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008332 // Just replace this cast with the result.
8333 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008334
Reid Spencer3da59db2006-11-27 01:05:10 +00008335 assert(Res->getType() == DestTy);
8336 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008337 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008339 // Just replace this cast with the result.
8340 return ReplaceInstUsesWith(CI, Res);
8341 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008343
8344 // If the high bits are already zero, just replace this cast with the
8345 // result.
8346 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8347 if (MaskedValueIsZero(Res, Mask))
8348 return ReplaceInstUsesWith(CI, Res);
8349
8350 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008351 Constant *C = ConstantInt::get(*Context,
8352 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008353 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008354 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008355 case Instruction::SExt: {
8356 // If the high bits are already filled with sign bit, just replace this
8357 // cast with the result.
8358 unsigned NumSignBits = ComputeNumSignBits(Res);
8359 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008360 return ReplaceInstUsesWith(CI, Res);
8361
Reid Spencer3da59db2006-11-27 01:05:10 +00008362 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008363 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 }
8367 }
8368
8369 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8370 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8371
8372 switch (SrcI->getOpcode()) {
8373 case Instruction::Add:
8374 case Instruction::Mul:
8375 case Instruction::And:
8376 case Instruction::Or:
8377 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008378 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008379 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8380 // Don't insert two casts unless at least one can be eliminated.
8381 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008382 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008383 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8384 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008385 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008386 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008387 }
8388 }
8389
8390 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8391 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8392 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008393 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008394 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008395 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008396 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008397 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008398 }
8399 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008400
Eli Friedman65445c52009-07-13 21:45:57 +00008401 case Instruction::Shl: {
8402 // Canonicalize trunc inside shl, if we can.
8403 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8404 if (CI && DestBitSize < SrcBitSize &&
8405 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008406 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8407 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008408 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 }
8410 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008411 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 }
8413 return 0;
8414}
8415
Chris Lattner8a9f5712007-04-11 06:57:46 +00008416Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008417 if (Instruction *Result = commonIntCastTransforms(CI))
8418 return Result;
8419
8420 Value *Src = CI.getOperand(0);
8421 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008422 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8423 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008424
8425 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008426 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008427 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008428 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008429 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008430 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008431 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008432
Chris Lattner4f9797d2009-03-24 18:15:30 +00008433 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8434 ConstantInt *ShAmtV = 0;
8435 Value *ShiftOp = 0;
8436 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008437 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008438 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8439
8440 // Get a mask for the bits shifting in.
8441 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8442 if (MaskedValueIsZero(ShiftOp, Mask)) {
8443 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008444 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008445
8446 // Okay, we can shrink this. Truncate the input, then return a new
8447 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008448 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008449 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008450 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008451 }
8452 }
Chris Lattner9956c052009-11-08 19:23:30 +00008453
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008454 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008455}
8456
Evan Chengb98a10e2008-03-24 00:21:34 +00008457/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8458/// in order to eliminate the icmp.
8459Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8460 bool DoXform) {
8461 // If we are just checking for a icmp eq of a single bit and zext'ing it
8462 // to an integer, then shift the bit to the appropriate place and then
8463 // cast to integer to avoid the comparison.
8464 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8465 const APInt &Op1CV = Op1C->getValue();
8466
8467 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8468 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8469 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8470 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8471 if (!DoXform) return ICI;
8472
8473 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008474 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008475 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008476 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008477 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008478 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008479
8480 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008481 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008482 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008483 }
8484
8485 return ReplaceInstUsesWith(CI, In);
8486 }
8487
8488
8489
8490 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8491 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8492 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8493 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8494 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8495 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8496 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8497 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8498 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8499 // This only works for EQ and NE
8500 ICI->isEquality()) {
8501 // If Op1C some other power of two, convert:
8502 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8503 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8504 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8505 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8506
8507 APInt KnownZeroMask(~KnownZero);
8508 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8509 if (!DoXform) return ICI;
8510
8511 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8512 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8513 // (X&4) == 2 --> false
8514 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008515 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008516 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008517 return ReplaceInstUsesWith(CI, Res);
8518 }
8519
8520 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8521 Value *In = ICI->getOperand(0);
8522 if (ShiftAmt) {
8523 // Perform a logical shr by shiftamt.
8524 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008525 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8526 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008527 }
8528
8529 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008530 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008531 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008532 }
8533
8534 if (CI.getType() == In->getType())
8535 return ReplaceInstUsesWith(CI, In);
8536 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008537 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008538 }
8539 }
8540 }
8541
8542 return 0;
8543}
8544
Chris Lattner8a9f5712007-04-11 06:57:46 +00008545Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008546 // If one of the common conversion will work ..
8547 if (Instruction *Result = commonIntCastTransforms(CI))
8548 return Result;
8549
8550 Value *Src = CI.getOperand(0);
8551
Chris Lattnera84f47c2009-02-17 20:47:23 +00008552 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8553 // types and if the sizes are just right we can convert this into a logical
8554 // 'and' which will be much cheaper than the pair of casts.
8555 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8556 // Get the sizes of the types involved. We know that the intermediate type
8557 // will be smaller than A or C, but don't know the relation between A and C.
8558 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008559 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8560 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8561 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008562 // If we're actually extending zero bits, then if
8563 // SrcSize < DstSize: zext(a & mask)
8564 // SrcSize == DstSize: a & mask
8565 // SrcSize > DstSize: trunc(a) & mask
8566 if (SrcSize < DstSize) {
8567 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008568 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008569 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008570 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008571 }
8572
8573 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008574 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008575 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008576 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008577 }
8578 if (SrcSize > DstSize) {
8579 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008580 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008581 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008582 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008583 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008584 }
8585 }
8586
Evan Chengb98a10e2008-03-24 00:21:34 +00008587 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8588 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008589
Evan Chengb98a10e2008-03-24 00:21:34 +00008590 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8591 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8592 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8593 // of the (zext icmp) will be transformed.
8594 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8595 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8596 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8597 (transformZExtICmp(LHS, CI, false) ||
8598 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008599 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8600 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008601 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008602 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008603 }
8604
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008605 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008606 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8607 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8608 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8609 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008610 if (TI0->getType() == CI.getType())
8611 return
8612 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008613 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008614 }
8615
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008616 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8617 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8618 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8619 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8620 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8621 And->getOperand(1) == C)
8622 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8623 Value *TI0 = TI->getOperand(0);
8624 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008625 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008626 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008627 return BinaryOperator::CreateXor(NewAnd, ZC);
8628 }
8629 }
8630
Reid Spencer3da59db2006-11-27 01:05:10 +00008631 return 0;
8632}
8633
Chris Lattner8a9f5712007-04-11 06:57:46 +00008634Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008635 if (Instruction *I = commonIntCastTransforms(CI))
8636 return I;
8637
Chris Lattner8a9f5712007-04-11 06:57:46 +00008638 Value *Src = CI.getOperand(0);
8639
Dan Gohman1975d032008-10-30 20:40:10 +00008640 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008641 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008642 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008643 Constant::getAllOnesValue(CI.getType()),
8644 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008645
8646 // See if the value being truncated is already sign extended. If so, just
8647 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008648 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008649 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008650 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8651 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8652 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008653 unsigned NumSignBits = ComputeNumSignBits(Op);
8654
8655 if (OpBits == DestBits) {
8656 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8657 // bits, it is already ready.
8658 if (NumSignBits > DestBits-MidBits)
8659 return ReplaceInstUsesWith(CI, Op);
8660 } else if (OpBits < DestBits) {
8661 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8662 // bits, just sext from i32.
8663 if (NumSignBits > OpBits-MidBits)
8664 return new SExtInst(Op, CI.getType(), "tmp");
8665 } else {
8666 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8667 // bits, just truncate to i32.
8668 if (NumSignBits > OpBits-MidBits)
8669 return new TruncInst(Op, CI.getType(), "tmp");
8670 }
8671 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008672
8673 // If the input is a shl/ashr pair of a same constant, then this is a sign
8674 // extension from a smaller value. If we could trust arbitrary bitwidth
8675 // integers, we could turn this into a truncate to the smaller bit and then
8676 // use a sext for the whole extension. Since we don't, look deeper and check
8677 // for a truncate. If the source and dest are the same type, eliminate the
8678 // trunc and extend and just do shifts. For example, turn:
8679 // %a = trunc i32 %i to i8
8680 // %b = shl i8 %a, 6
8681 // %c = ashr i8 %b, 6
8682 // %d = sext i8 %c to i32
8683 // into:
8684 // %a = shl i32 %i, 30
8685 // %d = ashr i32 %a, 30
8686 Value *A = 0;
8687 ConstantInt *BA = 0, *CA = 0;
8688 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008689 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008690 BA == CA && isa<TruncInst>(A)) {
8691 Value *I = cast<TruncInst>(A)->getOperand(0);
8692 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008693 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8694 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008695 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008696 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008697 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008698 return BinaryOperator::CreateAShr(I, ShAmtV);
8699 }
8700 }
8701
Chris Lattnerba417832007-04-11 06:12:58 +00008702 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008703}
8704
Chris Lattnerb7530652008-01-27 05:29:54 +00008705/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8706/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008707static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008708 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008709 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008710 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008711 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8712 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008713 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008714 return 0;
8715}
8716
8717/// LookThroughFPExtensions - If this is an fp extension instruction, look
8718/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008719static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008720 if (Instruction *I = dyn_cast<Instruction>(V))
8721 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008722 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008723
8724 // If this value is a constant, return the constant in the smallest FP type
8725 // that can accurately represent it. This allows us to turn
8726 // (float)((double)X+2.0) into x+2.0f.
8727 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008728 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008729 return V; // No constant folding of this.
8730 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008731 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008732 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008733 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008734 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008735 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008736 return V;
8737 // Don't try to shrink to various long double types.
8738 }
8739
8740 return V;
8741}
8742
8743Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8744 if (Instruction *I = commonCastTransforms(CI))
8745 return I;
8746
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008747 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008748 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008749 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008750 // many builtins (sqrt, etc).
8751 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8752 if (OpI && OpI->hasOneUse()) {
8753 switch (OpI->getOpcode()) {
8754 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008755 case Instruction::FAdd:
8756 case Instruction::FSub:
8757 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008758 case Instruction::FDiv:
8759 case Instruction::FRem:
8760 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008761 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8762 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008763 if (LHSTrunc->getType() != SrcTy &&
8764 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008765 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008766 // If the source types were both smaller than the destination type of
8767 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008768 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8769 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008770 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8771 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008772 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 }
8774 }
8775 break;
8776 }
8777 }
8778 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008779}
8780
8781Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8782 return commonCastTransforms(CI);
8783}
8784
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008785Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008786 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8787 if (OpI == 0)
8788 return commonCastTransforms(FI);
8789
8790 // fptoui(uitofp(X)) --> X
8791 // fptoui(sitofp(X)) --> X
8792 // This is safe if the intermediate type has enough bits in its mantissa to
8793 // accurately represent all values of X. For example, do not do this with
8794 // i64->float->i64. This is also safe for sitofp case, because any negative
8795 // 'X' value would cause an undefined result for the fptoui.
8796 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8797 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008798 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008799 OpI->getType()->getFPMantissaWidth())
8800 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008801
8802 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008803}
8804
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008805Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008806 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8807 if (OpI == 0)
8808 return commonCastTransforms(FI);
8809
8810 // fptosi(sitofp(X)) --> X
8811 // fptosi(uitofp(X)) --> X
8812 // This is safe if the intermediate type has enough bits in its mantissa to
8813 // accurately represent all values of X. For example, do not do this with
8814 // i64->float->i64. This is also safe for sitofp case, because any negative
8815 // 'X' value would cause an undefined result for the fptoui.
8816 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8817 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008818 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008819 OpI->getType()->getFPMantissaWidth())
8820 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008821
8822 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008823}
8824
8825Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8826 return commonCastTransforms(CI);
8827}
8828
8829Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8830 return commonCastTransforms(CI);
8831}
8832
Chris Lattnera0e69692009-03-24 18:35:40 +00008833Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8834 // If the destination integer type is smaller than the intptr_t type for
8835 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8836 // trunc to be exposed to other transforms. Don't do this for extending
8837 // ptrtoint's, because we don't know if the target sign or zero extends its
8838 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008839 if (TD &&
8840 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008841 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8842 TD->getIntPtrType(CI.getContext()),
8843 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008844 return new TruncInst(P, CI.getType());
8845 }
8846
Chris Lattnerd3e28342007-04-27 17:44:50 +00008847 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008848}
8849
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008850Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008851 // If the source integer type is larger than the intptr_t type for
8852 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8853 // allows the trunc to be exposed to other transforms. Don't do this for
8854 // extending inttoptr's, because we don't know if the target sign or zero
8855 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008856 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008857 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008858 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8859 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008860 return new IntToPtrInst(P, CI.getType());
8861 }
8862
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008863 if (Instruction *I = commonCastTransforms(CI))
8864 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008865
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008866 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008867}
8868
Chris Lattnerd3e28342007-04-27 17:44:50 +00008869Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008870 // If the operands are integer typed then apply the integer transforms,
8871 // otherwise just apply the common ones.
8872 Value *Src = CI.getOperand(0);
8873 const Type *SrcTy = Src->getType();
8874 const Type *DestTy = CI.getType();
8875
Eli Friedman7e25d452009-07-13 20:53:00 +00008876 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008877 if (Instruction *I = commonPointerCastTransforms(CI))
8878 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008879 } else {
8880 if (Instruction *Result = commonCastTransforms(CI))
8881 return Result;
8882 }
8883
8884
8885 // Get rid of casts from one type to the same type. These are useless and can
8886 // be replaced by the operand.
8887 if (DestTy == Src->getType())
8888 return ReplaceInstUsesWith(CI, Src);
8889
Reid Spencer3da59db2006-11-27 01:05:10 +00008890 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008891 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8892 const Type *DstElTy = DstPTy->getElementType();
8893 const Type *SrcElTy = SrcPTy->getElementType();
8894
Nate Begeman83ad90a2008-03-31 00:22:16 +00008895 // If the address spaces don't match, don't eliminate the bitcast, which is
8896 // required for changing types.
8897 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8898 return 0;
8899
Victor Hernandez83d63912009-09-18 22:35:49 +00008900 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008901 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008902 // There is no need to modify malloc calls because it is their bitcast that
8903 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008904 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008905 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8906 return V;
8907
Chris Lattnerd717c182007-05-05 22:32:24 +00008908 // If the source and destination are pointers, and this cast is equivalent
8909 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008910 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008911 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008912 unsigned NumZeros = 0;
8913 while (SrcElTy != DstElTy &&
8914 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8915 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8916 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8917 ++NumZeros;
8918 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008919
Chris Lattnerd3e28342007-04-27 17:44:50 +00008920 // If we found a path from the src to dest, create the getelementptr now.
8921 if (SrcElTy == DstElTy) {
8922 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008923 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8924 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008925 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008927
Eli Friedman2451a642009-07-18 23:06:53 +00008928 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8929 if (DestVTy->getNumElements() == 1) {
8930 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008931 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008932 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008933 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008934 }
8935 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8936 }
8937 }
8938
8939 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8940 if (SrcVTy->getNumElements() == 1) {
8941 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008942 Value *Elem =
8943 Builder->CreateExtractElement(Src,
8944 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008945 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8946 }
8947 }
8948 }
8949
Reid Spencer3da59db2006-11-27 01:05:10 +00008950 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8951 if (SVI->hasOneUse()) {
8952 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8953 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008954 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008955 cast<VectorType>(DestTy)->getNumElements() ==
8956 SVI->getType()->getNumElements() &&
8957 SVI->getType()->getNumElements() ==
8958 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008959 CastInst *Tmp;
8960 // If either of the operands is a cast from CI.getType(), then
8961 // evaluating the shuffle in the casted destination's type will allow
8962 // us to eliminate at least one cast.
8963 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8964 Tmp->getOperand(0)->getType() == DestTy) ||
8965 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8966 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008967 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8968 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008969 // Return a new shuffle vector. Use the same element ID's, as we
8970 // know the vector types match #elts.
8971 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008972 }
8973 }
8974 }
8975 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008976 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008977}
8978
Chris Lattnere576b912004-04-09 23:46:01 +00008979/// GetSelectFoldableOperands - We want to turn code that looks like this:
8980/// %C = or %A, %B
8981/// %D = select %cond, %C, %A
8982/// into:
8983/// %C = select %cond, %B, 0
8984/// %D = or %A, %C
8985///
8986/// Assuming that the specified instruction is an operand to the select, return
8987/// a bitmask indicating which operands of this instruction are foldable if they
8988/// equal the other incoming value of the select.
8989///
8990static unsigned GetSelectFoldableOperands(Instruction *I) {
8991 switch (I->getOpcode()) {
8992 case Instruction::Add:
8993 case Instruction::Mul:
8994 case Instruction::And:
8995 case Instruction::Or:
8996 case Instruction::Xor:
8997 return 3; // Can fold through either operand.
8998 case Instruction::Sub: // Can only fold on the amount subtracted.
8999 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009000 case Instruction::LShr:
9001 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009002 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009003 default:
9004 return 0; // Cannot fold
9005 }
9006}
9007
9008/// GetSelectFoldableConstant - For the same transformation as the previous
9009/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009010static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009011 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009012 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009013 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009014 case Instruction::Add:
9015 case Instruction::Sub:
9016 case Instruction::Or:
9017 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009018 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009019 case Instruction::LShr:
9020 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009021 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009022 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009023 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009024 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009025 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009026 }
9027}
9028
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009029/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9030/// have the same opcode and only one use each. Try to simplify this.
9031Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9032 Instruction *FI) {
9033 if (TI->getNumOperands() == 1) {
9034 // If this is a non-volatile load or a cast from the same type,
9035 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009036 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009037 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9038 return 0;
9039 } else {
9040 return 0; // unknown unary op.
9041 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009042
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009043 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009044 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009045 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009046 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009047 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009048 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009049 }
9050
Reid Spencer832254e2007-02-02 02:16:23 +00009051 // Only handle binary operators here.
9052 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009053 return 0;
9054
9055 // Figure out if the operations have any operands in common.
9056 Value *MatchOp, *OtherOpT, *OtherOpF;
9057 bool MatchIsOpZero;
9058 if (TI->getOperand(0) == FI->getOperand(0)) {
9059 MatchOp = TI->getOperand(0);
9060 OtherOpT = TI->getOperand(1);
9061 OtherOpF = FI->getOperand(1);
9062 MatchIsOpZero = true;
9063 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9064 MatchOp = TI->getOperand(1);
9065 OtherOpT = TI->getOperand(0);
9066 OtherOpF = FI->getOperand(0);
9067 MatchIsOpZero = false;
9068 } else if (!TI->isCommutative()) {
9069 return 0;
9070 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9071 MatchOp = TI->getOperand(0);
9072 OtherOpT = TI->getOperand(1);
9073 OtherOpF = FI->getOperand(0);
9074 MatchIsOpZero = true;
9075 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9076 MatchOp = TI->getOperand(1);
9077 OtherOpT = TI->getOperand(0);
9078 OtherOpF = FI->getOperand(1);
9079 MatchIsOpZero = true;
9080 } else {
9081 return 0;
9082 }
9083
9084 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009085 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9086 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009087 InsertNewInstBefore(NewSI, SI);
9088
9089 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9090 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009091 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009092 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009093 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009094 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009095 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009096 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009097}
9098
Evan Chengde621922009-03-31 20:42:45 +00009099static bool isSelect01(Constant *C1, Constant *C2) {
9100 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9101 if (!C1I)
9102 return false;
9103 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9104 if (!C2I)
9105 return false;
9106 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9107}
9108
9109/// FoldSelectIntoOp - Try fold the select into one of the operands to
9110/// facilitate further optimization.
9111Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9112 Value *FalseVal) {
9113 // See the comment above GetSelectFoldableOperands for a description of the
9114 // transformation we are doing here.
9115 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9116 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9117 !isa<Constant>(FalseVal)) {
9118 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9119 unsigned OpToFold = 0;
9120 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9121 OpToFold = 1;
9122 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9123 OpToFold = 2;
9124 }
9125
9126 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009127 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009128 Value *OOp = TVI->getOperand(2-OpToFold);
9129 // Avoid creating select between 2 constants unless it's selecting
9130 // between 0 and 1.
9131 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9132 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9133 InsertNewInstBefore(NewSel, SI);
9134 NewSel->takeName(TVI);
9135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9136 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009137 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009138 }
9139 }
9140 }
9141 }
9142 }
9143
9144 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9145 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9146 !isa<Constant>(TrueVal)) {
9147 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9148 unsigned OpToFold = 0;
9149 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9150 OpToFold = 1;
9151 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9152 OpToFold = 2;
9153 }
9154
9155 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009156 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009157 Value *OOp = FVI->getOperand(2-OpToFold);
9158 // Avoid creating select between 2 constants unless it's selecting
9159 // between 0 and 1.
9160 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9161 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9162 InsertNewInstBefore(NewSel, SI);
9163 NewSel->takeName(FVI);
9164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9165 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009166 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009167 }
9168 }
9169 }
9170 }
9171 }
9172
9173 return 0;
9174}
9175
Dan Gohman81b28ce2008-09-16 18:46:06 +00009176/// visitSelectInstWithICmp - Visit a SelectInst that has an
9177/// ICmpInst as its first operand.
9178///
9179Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9180 ICmpInst *ICI) {
9181 bool Changed = false;
9182 ICmpInst::Predicate Pred = ICI->getPredicate();
9183 Value *CmpLHS = ICI->getOperand(0);
9184 Value *CmpRHS = ICI->getOperand(1);
9185 Value *TrueVal = SI.getTrueValue();
9186 Value *FalseVal = SI.getFalseValue();
9187
9188 // Check cases where the comparison is with a constant that
9189 // can be adjusted to fit the min/max idiom. We may edit ICI in
9190 // place here, so make sure the select is the only user.
9191 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009192 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009193 switch (Pred) {
9194 default: break;
9195 case ICmpInst::ICMP_ULT:
9196 case ICmpInst::ICMP_SLT: {
9197 // X < MIN ? T : F --> F
9198 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9199 return ReplaceInstUsesWith(SI, FalseVal);
9200 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009201 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009202 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9203 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9204 Pred = ICmpInst::getSwappedPredicate(Pred);
9205 CmpRHS = AdjustedRHS;
9206 std::swap(FalseVal, TrueVal);
9207 ICI->setPredicate(Pred);
9208 ICI->setOperand(1, CmpRHS);
9209 SI.setOperand(1, TrueVal);
9210 SI.setOperand(2, FalseVal);
9211 Changed = true;
9212 }
9213 break;
9214 }
9215 case ICmpInst::ICMP_UGT:
9216 case ICmpInst::ICMP_SGT: {
9217 // X > MAX ? T : F --> F
9218 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9219 return ReplaceInstUsesWith(SI, FalseVal);
9220 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009221 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009222 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9223 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9224 Pred = ICmpInst::getSwappedPredicate(Pred);
9225 CmpRHS = AdjustedRHS;
9226 std::swap(FalseVal, TrueVal);
9227 ICI->setPredicate(Pred);
9228 ICI->setOperand(1, CmpRHS);
9229 SI.setOperand(1, TrueVal);
9230 SI.setOperand(2, FalseVal);
9231 Changed = true;
9232 }
9233 break;
9234 }
9235 }
9236
Dan Gohman1975d032008-10-30 20:40:10 +00009237 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9238 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009239 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009240 if (match(TrueVal, m_ConstantInt<-1>()) &&
9241 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009242 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009243 else if (match(TrueVal, m_ConstantInt<0>()) &&
9244 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009245 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9246
Dan Gohman1975d032008-10-30 20:40:10 +00009247 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9248 // If we are just checking for a icmp eq of a single bit and zext'ing it
9249 // to an integer, then shift the bit to the appropriate place and then
9250 // cast to integer to avoid the comparison.
9251 const APInt &Op1CV = CI->getValue();
9252
9253 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9254 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9255 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009256 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009257 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009258 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009259 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009260 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009261 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009262 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009263 if (In->getType() != SI.getType())
9264 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009265 true/*SExt*/, "tmp", ICI);
9266
9267 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009268 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009269 In->getName()+".not"), *ICI);
9270
9271 return ReplaceInstUsesWith(SI, In);
9272 }
9273 }
9274 }
9275
Dan Gohman81b28ce2008-09-16 18:46:06 +00009276 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9277 // Transform (X == Y) ? X : Y -> Y
9278 if (Pred == ICmpInst::ICMP_EQ)
9279 return ReplaceInstUsesWith(SI, FalseVal);
9280 // Transform (X != Y) ? X : Y -> X
9281 if (Pred == ICmpInst::ICMP_NE)
9282 return ReplaceInstUsesWith(SI, TrueVal);
9283 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9284
9285 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9286 // Transform (X == Y) ? Y : X -> X
9287 if (Pred == ICmpInst::ICMP_EQ)
9288 return ReplaceInstUsesWith(SI, FalseVal);
9289 // Transform (X != Y) ? Y : X -> Y
9290 if (Pred == ICmpInst::ICMP_NE)
9291 return ReplaceInstUsesWith(SI, TrueVal);
9292 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9293 }
9294
9295 /// NOTE: if we wanted to, this is where to detect integer ABS
9296
9297 return Changed ? &SI : 0;
9298}
9299
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009300
Chris Lattner7f239582009-10-22 00:17:26 +00009301/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9302/// PHI node (but the two may be in different blocks). See if the true/false
9303/// values (V) are live in all of the predecessor blocks of the PHI. For
9304/// example, cases like this cannot be mapped:
9305///
9306/// X = phi [ C1, BB1], [C2, BB2]
9307/// Y = add
9308/// Z = select X, Y, 0
9309///
9310/// because Y is not live in BB1/BB2.
9311///
9312static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9313 const SelectInst &SI) {
9314 // If the value is a non-instruction value like a constant or argument, it
9315 // can always be mapped.
9316 const Instruction *I = dyn_cast<Instruction>(V);
9317 if (I == 0) return true;
9318
9319 // If V is a PHI node defined in the same block as the condition PHI, we can
9320 // map the arguments.
9321 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9322
9323 if (const PHINode *VP = dyn_cast<PHINode>(I))
9324 if (VP->getParent() == CondPHI->getParent())
9325 return true;
9326
9327 // Otherwise, if the PHI and select are defined in the same block and if V is
9328 // defined in a different block, then we can transform it.
9329 if (SI.getParent() == CondPHI->getParent() &&
9330 I->getParent() != CondPHI->getParent())
9331 return true;
9332
9333 // Otherwise we have a 'hard' case and we can't tell without doing more
9334 // detailed dominator based analysis, punt.
9335 return false;
9336}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009337
Chris Lattner3d69f462004-03-12 05:52:32 +00009338Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009339 Value *CondVal = SI.getCondition();
9340 Value *TrueVal = SI.getTrueValue();
9341 Value *FalseVal = SI.getFalseValue();
9342
9343 // select true, X, Y -> X
9344 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009345 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009346 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009347
9348 // select C, X, X -> X
9349 if (TrueVal == FalseVal)
9350 return ReplaceInstUsesWith(SI, TrueVal);
9351
Chris Lattnere87597f2004-10-16 18:11:37 +00009352 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9353 return ReplaceInstUsesWith(SI, FalseVal);
9354 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9355 return ReplaceInstUsesWith(SI, TrueVal);
9356 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9357 if (isa<Constant>(TrueVal))
9358 return ReplaceInstUsesWith(SI, TrueVal);
9359 else
9360 return ReplaceInstUsesWith(SI, FalseVal);
9361 }
9362
Owen Anderson1d0be152009-08-13 21:58:54 +00009363 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009364 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009365 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009366 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009367 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009368 } else {
9369 // Change: A = select B, false, C --> A = and !B, C
9370 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009371 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009372 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009373 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009374 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009375 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009376 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009377 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009378 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009379 } else {
9380 // Change: A = select B, C, true --> A = or !B, C
9381 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009382 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009383 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009384 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009385 }
9386 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009387
9388 // select a, b, a -> a&b
9389 // select a, a, b -> a|b
9390 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009391 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009392 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009393 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009394 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009395
Chris Lattner2eefe512004-04-09 19:05:30 +00009396 // Selecting between two integer constants?
9397 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9398 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009399 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009400 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009401 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009402 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009403 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009404 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009405 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009406 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009407 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009408 }
Chris Lattner457dd822004-06-09 07:59:58 +00009409
Reid Spencere4d87aa2006-12-23 06:05:41 +00009410 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009411 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009412 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009413 // non-constant value, eliminate this whole mess. This corresponds to
9414 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009415 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009416 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009417 cast<Constant>(IC->getOperand(1))->isNullValue())
9418 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9419 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009420 isa<ConstantInt>(ICA->getOperand(1)) &&
9421 (ICA->getOperand(1) == TrueValC ||
9422 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009423 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9424 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009425 // know whether we have a icmp_ne or icmp_eq and whether the
9426 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009427 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009428 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009429 Value *V = ICA;
9430 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009431 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009432 Instruction::Xor, V, ICA->getOperand(1)), SI);
9433 return ReplaceInstUsesWith(SI, V);
9434 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009435 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009436 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009437
9438 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009439 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9440 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009441 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009442 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9443 // This is not safe in general for floating point:
9444 // consider X== -0, Y== +0.
9445 // It becomes safe if either operand is a nonzero constant.
9446 ConstantFP *CFPt, *CFPf;
9447 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9448 !CFPt->getValueAPF().isZero()) ||
9449 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9450 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009451 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009452 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009453 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009454 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009455 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009456 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009457
Reid Spencere4d87aa2006-12-23 06:05:41 +00009458 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009459 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009460 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9461 // This is not safe in general for floating point:
9462 // consider X== -0, Y== +0.
9463 // It becomes safe if either operand is a nonzero constant.
9464 ConstantFP *CFPt, *CFPf;
9465 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9466 !CFPt->getValueAPF().isZero()) ||
9467 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9468 !CFPf->getValueAPF().isZero()))
9469 return ReplaceInstUsesWith(SI, FalseVal);
9470 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009471 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009472 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9473 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009474 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009475 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009476 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009477 }
9478
9479 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009480 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9481 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9482 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009483
Chris Lattner87875da2005-01-13 22:52:24 +00009484 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9485 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9486 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009487 Instruction *AddOp = 0, *SubOp = 0;
9488
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009489 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9490 if (TI->getOpcode() == FI->getOpcode())
9491 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9492 return IV;
9493
9494 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9495 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009496 if ((TI->getOpcode() == Instruction::Sub &&
9497 FI->getOpcode() == Instruction::Add) ||
9498 (TI->getOpcode() == Instruction::FSub &&
9499 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009500 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009501 } else if ((FI->getOpcode() == Instruction::Sub &&
9502 TI->getOpcode() == Instruction::Add) ||
9503 (FI->getOpcode() == Instruction::FSub &&
9504 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009505 AddOp = TI; SubOp = FI;
9506 }
9507
9508 if (AddOp) {
9509 Value *OtherAddOp = 0;
9510 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9511 OtherAddOp = AddOp->getOperand(1);
9512 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9513 OtherAddOp = AddOp->getOperand(0);
9514 }
9515
9516 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009517 // So at this point we know we have (Y -> OtherAddOp):
9518 // select C, (add X, Y), (sub X, Z)
9519 Value *NegVal; // Compute -Z
9520 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009521 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009522 } else {
9523 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009524 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009525 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009526 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009527
9528 Value *NewTrueOp = OtherAddOp;
9529 Value *NewFalseOp = NegVal;
9530 if (AddOp != TI)
9531 std::swap(NewTrueOp, NewFalseOp);
9532 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009533 SelectInst::Create(CondVal, NewTrueOp,
9534 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009535
9536 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009537 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009538 }
9539 }
9540 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009541
Chris Lattnere576b912004-04-09 23:46:01 +00009542 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009543 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009544 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9545 if (FoldI)
9546 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009547 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009548
Chris Lattner7f239582009-10-22 00:17:26 +00009549 // See if we can fold the select into a phi node if the condition is a select.
9550 if (isa<PHINode>(SI.getCondition()))
9551 // The true/false values have to be live in the PHI predecessor's blocks.
9552 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9553 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9554 if (Instruction *NV = FoldOpIntoPhi(SI))
9555 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009556
Chris Lattnera1df33c2005-04-24 07:30:14 +00009557 if (BinaryOperator::isNot(CondVal)) {
9558 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9559 SI.setOperand(1, FalseVal);
9560 SI.setOperand(2, TrueVal);
9561 return &SI;
9562 }
9563
Chris Lattner3d69f462004-03-12 05:52:32 +00009564 return 0;
9565}
9566
Dan Gohmaneee962e2008-04-10 18:43:06 +00009567/// EnforceKnownAlignment - If the specified pointer points to an object that
9568/// we control, modify the object's alignment to PrefAlign. This isn't
9569/// often possible though. If alignment is important, a more reliable approach
9570/// is to simply align all global variables and allocation instructions to
9571/// their preferred alignment from the beginning.
9572///
9573static unsigned EnforceKnownAlignment(Value *V,
9574 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009575
Dan Gohmaneee962e2008-04-10 18:43:06 +00009576 User *U = dyn_cast<User>(V);
9577 if (!U) return Align;
9578
Dan Gohmanca178902009-07-17 20:47:02 +00009579 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009580 default: break;
9581 case Instruction::BitCast:
9582 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9583 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009584 // If all indexes are zero, it is just the alignment of the base pointer.
9585 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009586 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009587 if (!isa<Constant>(*i) ||
9588 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009589 AllZeroOperands = false;
9590 break;
9591 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009592
9593 if (AllZeroOperands) {
9594 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009596 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009597 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009598 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009599 }
9600
9601 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9602 // If there is a large requested alignment and we can, bump up the alignment
9603 // of the global.
9604 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009605 if (GV->getAlignment() >= PrefAlign)
9606 Align = GV->getAlignment();
9607 else {
9608 GV->setAlignment(PrefAlign);
9609 Align = PrefAlign;
9610 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009612 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9613 // If there is a requested alignment and if this is an alloca, round up.
9614 if (AI->getAlignment() >= PrefAlign)
9615 Align = AI->getAlignment();
9616 else {
9617 AI->setAlignment(PrefAlign);
9618 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009619 }
9620 }
9621
9622 return Align;
9623}
9624
9625/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9626/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9627/// and it is more than the alignment of the ultimate object, see if we can
9628/// increase the alignment of the ultimate object, making this check succeed.
9629unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9630 unsigned PrefAlign) {
9631 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9632 sizeof(PrefAlign) * CHAR_BIT;
9633 APInt Mask = APInt::getAllOnesValue(BitWidth);
9634 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9635 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9636 unsigned TrailZ = KnownZero.countTrailingOnes();
9637 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9638
9639 if (PrefAlign > Align)
9640 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9641
9642 // We don't need to make any adjustment.
9643 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009644}
9645
Chris Lattnerf497b022008-01-13 23:50:23 +00009646Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009647 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009648 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009649 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009650 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009651
9652 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009653 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009654 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009655 return MI;
9656 }
9657
9658 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9659 // load/store.
9660 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9661 if (MemOpLength == 0) return 0;
9662
Chris Lattner37ac6082008-01-14 00:28:35 +00009663 // Source and destination pointer types are always "i8*" for intrinsic. See
9664 // if the size is something we can handle with a single primitive load/store.
9665 // A single load+store correctly handles overlapping memory in the memmove
9666 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009667 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009668 if (Size == 0) return MI; // Delete this mem transfer.
9669
9670 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009671 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009672
Chris Lattner37ac6082008-01-14 00:28:35 +00009673 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009674 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009675 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009676
9677 // Memcpy forces the use of i8* for the source and destination. That means
9678 // that if you're using memcpy to move one double around, you'll get a cast
9679 // from double* to i8*. We'd much rather use a double load+store rather than
9680 // an i64 load+store, here because this improves the odds that the source or
9681 // dest address will be promotable. See if we can find a better type than the
9682 // integer datatype.
9683 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9684 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009685 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009686 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9687 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009688 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009689 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9690 if (STy->getNumElements() == 1)
9691 SrcETy = STy->getElementType(0);
9692 else
9693 break;
9694 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9695 if (ATy->getNumElements() == 1)
9696 SrcETy = ATy->getElementType();
9697 else
9698 break;
9699 } else
9700 break;
9701 }
9702
Dan Gohman8f8e2692008-05-23 01:52:21 +00009703 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009704 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009705 }
9706 }
9707
9708
Chris Lattnerf497b022008-01-13 23:50:23 +00009709 // If the memcpy/memmove provides better alignment info than we can
9710 // infer, use it.
9711 SrcAlign = std::max(SrcAlign, CopyAlign);
9712 DstAlign = std::max(DstAlign, CopyAlign);
9713
Chris Lattner08142f22009-08-30 19:47:22 +00009714 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9715 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009716 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9717 InsertNewInstBefore(L, *MI);
9718 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9719
9720 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009721 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009722 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009723}
Chris Lattner3d69f462004-03-12 05:52:32 +00009724
Chris Lattner69ea9d22008-04-30 06:39:11 +00009725Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9726 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009727 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009728 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009729 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009730 return MI;
9731 }
9732
9733 // Extract the length and alignment and fill if they are constant.
9734 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9735 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009736 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009737 return 0;
9738 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009739 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009740
9741 // If the length is zero, this is a no-op
9742 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9743
9744 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9745 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009746 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009747
9748 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009749 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009750
9751 // Alignment 0 is identity for alignment 1 for memset, but not store.
9752 if (Alignment == 0) Alignment = 1;
9753
9754 // Extract the fill value and store.
9755 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009756 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009757 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009758
9759 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009760 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009761 return MI;
9762 }
9763
9764 return 0;
9765}
9766
9767
Chris Lattner8b0ea312006-01-13 20:11:04 +00009768/// visitCallInst - CallInst simplification. This mostly only handles folding
9769/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9770/// the heavy lifting.
9771///
Chris Lattner9fe38862003-06-19 17:00:31 +00009772Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009773 if (isFreeCall(&CI))
9774 return visitFree(CI);
9775
Chris Lattneraab6ec42009-05-13 17:39:14 +00009776 // If the caller function is nounwind, mark the call as nounwind, even if the
9777 // callee isn't.
9778 if (CI.getParent()->getParent()->doesNotThrow() &&
9779 !CI.doesNotThrow()) {
9780 CI.setDoesNotThrow();
9781 return &CI;
9782 }
9783
Chris Lattner8b0ea312006-01-13 20:11:04 +00009784 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9785 if (!II) return visitCallSite(&CI);
9786
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009787 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9788 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009789 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009790 bool Changed = false;
9791
9792 // memmove/cpy/set of zero bytes is a noop.
9793 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9794 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9795
Chris Lattner35b9e482004-10-12 04:52:52 +00009796 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009797 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009798 // Replace the instruction with just byte operations. We would
9799 // transform other cases to loads/stores, but we don't know if
9800 // alignment is sufficient.
9801 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009802 }
9803
Chris Lattner35b9e482004-10-12 04:52:52 +00009804 // If we have a memmove and the source operation is a constant global,
9805 // then the source and dest pointers can't alias, so we can change this
9806 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009807 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009808 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9809 if (GVSrc->isConstant()) {
9810 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009811 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9812 const Type *Tys[1];
9813 Tys[0] = CI.getOperand(3)->getType();
9814 CI.setOperand(0,
9815 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009816 Changed = true;
9817 }
Chris Lattnera935db82008-05-28 05:30:41 +00009818
9819 // memmove(x,x,size) -> noop.
9820 if (MMI->getSource() == MMI->getDest())
9821 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009822 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009823
Chris Lattner95a959d2006-03-06 20:18:44 +00009824 // If we can determine a pointer alignment that is bigger than currently
9825 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009826 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009827 if (Instruction *I = SimplifyMemTransfer(MI))
9828 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009829 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9830 if (Instruction *I = SimplifyMemSet(MSI))
9831 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009832 }
9833
Chris Lattner8b0ea312006-01-13 20:11:04 +00009834 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009835 }
9836
9837 switch (II->getIntrinsicID()) {
9838 default: break;
9839 case Intrinsic::bswap:
9840 // bswap(bswap(x)) -> x
9841 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9842 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9843 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9844 break;
9845 case Intrinsic::ppc_altivec_lvx:
9846 case Intrinsic::ppc_altivec_lvxl:
9847 case Intrinsic::x86_sse_loadu_ps:
9848 case Intrinsic::x86_sse2_loadu_pd:
9849 case Intrinsic::x86_sse2_loadu_dq:
9850 // Turn PPC lvx -> load if the pointer is known aligned.
9851 // Turn X86 loadups -> load if the pointer is known aligned.
9852 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009853 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9854 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009855 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009856 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009857 break;
9858 case Intrinsic::ppc_altivec_stvx:
9859 case Intrinsic::ppc_altivec_stvxl:
9860 // Turn stvx -> store if the pointer is known aligned.
9861 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9862 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009863 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009864 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009865 return new StoreInst(II->getOperand(1), Ptr);
9866 }
9867 break;
9868 case Intrinsic::x86_sse_storeu_ps:
9869 case Intrinsic::x86_sse2_storeu_pd:
9870 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009871 // Turn X86 storeu -> store if the pointer is known aligned.
9872 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9873 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009874 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009875 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 return new StoreInst(II->getOperand(2), Ptr);
9877 }
9878 break;
9879
9880 case Intrinsic::x86_sse_cvttss2si: {
9881 // These intrinsics only demands the 0th element of its input vector. If
9882 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009883 unsigned VWidth =
9884 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9885 APInt DemandedElts(VWidth, 1);
9886 APInt UndefElts(VWidth, 0);
9887 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 UndefElts)) {
9889 II->setOperand(1, V);
9890 return II;
9891 }
9892 break;
9893 }
9894
9895 case Intrinsic::ppc_altivec_vperm:
9896 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9897 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9898 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009899
Chris Lattner0521e3c2008-06-18 04:33:20 +00009900 // Check that all of the elements are integer constants or undefs.
9901 bool AllEltsOk = true;
9902 for (unsigned i = 0; i != 16; ++i) {
9903 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9904 !isa<UndefValue>(Mask->getOperand(i))) {
9905 AllEltsOk = false;
9906 break;
9907 }
9908 }
9909
9910 if (AllEltsOk) {
9911 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009912 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9913 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009914 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009915
Chris Lattner0521e3c2008-06-18 04:33:20 +00009916 // Only extract each element once.
9917 Value *ExtractedElts[32];
9918 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9919
Chris Lattnere2ed0572006-04-06 19:19:17 +00009920 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009921 if (isa<UndefValue>(Mask->getOperand(i)))
9922 continue;
9923 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9924 Idx &= 31; // Match the hardware behavior.
9925
9926 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009927 ExtractedElts[Idx] =
9928 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9929 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9930 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009931 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009932
Chris Lattner0521e3c2008-06-18 04:33:20 +00009933 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009934 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9935 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9936 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009937 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009938 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009939 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009940 }
9941 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009942
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 case Intrinsic::stackrestore: {
9944 // If the save is right next to the restore, remove the restore. This can
9945 // happen when variable allocas are DCE'd.
9946 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9947 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9948 BasicBlock::iterator BI = SS;
9949 if (&*++BI == II)
9950 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009951 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 }
9953
9954 // Scan down this block to see if there is another stack restore in the
9955 // same block without an intervening call/alloca.
9956 BasicBlock::iterator BI = II;
9957 TerminatorInst *TI = II->getParent()->getTerminator();
9958 bool CannotRemove = false;
9959 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009960 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009961 CannotRemove = true;
9962 break;
9963 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009964 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9965 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9966 // If there is a stackrestore below this one, remove this one.
9967 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9968 return EraseInstFromFunction(CI);
9969 // Otherwise, ignore the intrinsic.
9970 } else {
9971 // If we found a non-intrinsic call, we can't remove the stack
9972 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009973 CannotRemove = true;
9974 break;
9975 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009977 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009978
9979 // If the stack restore is in a return/unwind block and if there are no
9980 // allocas or calls between the restore and the return, nuke the restore.
9981 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9982 return EraseInstFromFunction(CI);
9983 break;
9984 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009985 }
9986
Chris Lattner8b0ea312006-01-13 20:11:04 +00009987 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009988}
9989
9990// InvokeInst simplification
9991//
9992Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009993 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009994}
9995
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009996/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9997/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009998static bool isSafeToEliminateVarargsCast(const CallSite CS,
9999 const CastInst * const CI,
10000 const TargetData * const TD,
10001 const int ix) {
10002 if (!CI->isLosslessCast())
10003 return false;
10004
10005 // The size of ByVal arguments is derived from the type, so we
10006 // can't change to a type with a different size. If the size were
10007 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010008 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010009 return true;
10010
10011 const Type* SrcTy =
10012 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10013 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10014 if (!SrcTy->isSized() || !DstTy->isSized())
10015 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010016 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010017 return false;
10018 return true;
10019}
10020
Chris Lattnera44d8a22003-10-07 22:32:43 +000010021// visitCallSite - Improvements for call and invoke instructions.
10022//
10023Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010024 bool Changed = false;
10025
10026 // If the callee is a constexpr cast of a function, attempt to move the cast
10027 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010028 if (transformConstExprCastCall(CS)) return 0;
10029
Chris Lattner6c266db2003-10-07 22:54:13 +000010030 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010031
Chris Lattner08b22ec2005-05-13 07:09:09 +000010032 if (Function *CalleeF = dyn_cast<Function>(Callee))
10033 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10034 Instruction *OldCall = CS.getInstruction();
10035 // If the call and callee calling conventions don't match, this call must
10036 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010037 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010038 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010039 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010040 // If OldCall dues not return void then replaceAllUsesWith undef.
10041 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010042 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010043 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010044 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10045 return EraseInstFromFunction(*OldCall);
10046 return 0;
10047 }
10048
Chris Lattner17be6352004-10-18 02:59:09 +000010049 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10050 // This instruction is not reachable, just remove it. We insert a store to
10051 // undef so that we know that this code is not reachable, despite the fact
10052 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010053 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010054 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010055 CS.getInstruction());
10056
Devang Patel228ebd02009-10-13 22:56:32 +000010057 // If CS dues not return void then replaceAllUsesWith undef.
10058 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010059 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010060 CS.getInstruction()->
10061 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010062
10063 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10064 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010065 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010066 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010067 }
Chris Lattner17be6352004-10-18 02:59:09 +000010068 return EraseInstFromFunction(*CS.getInstruction());
10069 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010070
Duncan Sandscdb6d922007-09-17 10:26:40 +000010071 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10072 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10073 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10074 return transformCallThroughTrampoline(CS);
10075
Chris Lattner6c266db2003-10-07 22:54:13 +000010076 const PointerType *PTy = cast<PointerType>(Callee->getType());
10077 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10078 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010079 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010080 // See if we can optimize any arguments passed through the varargs area of
10081 // the call.
10082 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010083 E = CS.arg_end(); I != E; ++I, ++ix) {
10084 CastInst *CI = dyn_cast<CastInst>(*I);
10085 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10086 *I = CI->getOperand(0);
10087 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010088 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010089 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010090 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010091
Duncan Sandsf0c33542007-12-19 21:13:37 +000010092 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010093 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010094 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010095 Changed = true;
10096 }
10097
Chris Lattner6c266db2003-10-07 22:54:13 +000010098 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010099}
10100
Chris Lattner9fe38862003-06-19 17:00:31 +000010101// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10102// attempt to move the cast to the arguments of the call/invoke.
10103//
10104bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10105 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10106 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010107 if (CE->getOpcode() != Instruction::BitCast ||
10108 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010109 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010110 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010111 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010112 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010113
10114 // Okay, this is a cast from a function to a different type. Unless doing so
10115 // would cause a type conversion of one of our arguments, change this call to
10116 // be a direct call with arguments casted to the appropriate types.
10117 //
10118 const FunctionType *FT = Callee->getFunctionType();
10119 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010120 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010121
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010122 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010123 return false; // TODO: Handle multiple return values.
10124
Chris Lattnerf78616b2004-01-14 06:06:08 +000010125 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010126 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010127 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010128 // Conversion is ok if changing from one pointer type to another or from
10129 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010130 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010131 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010132 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010133 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010134 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010135
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010136 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010137 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010138 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010139 return false; // Cannot transform this return value.
10140
Chris Lattner58d74912008-03-12 17:45:29 +000010141 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010142 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010143 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010144 return false; // Attribute not compatible with transformed value.
10145 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010146
Chris Lattnerf78616b2004-01-14 06:06:08 +000010147 // If the callsite is an invoke instruction, and the return value is used by
10148 // a PHI node in a successor, we cannot change the return type of the call
10149 // because there is no place to put the cast instruction (without breaking
10150 // the critical edge). Bail out in this case.
10151 if (!Caller->use_empty())
10152 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10153 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10154 UI != E; ++UI)
10155 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10156 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010157 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010158 return false;
10159 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010160
10161 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10162 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010163
Chris Lattner9fe38862003-06-19 17:00:31 +000010164 CallSite::arg_iterator AI = CS.arg_begin();
10165 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10166 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010167 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010168
10169 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010170 return false; // Cannot transform this parameter value.
10171
Devang Patel19c87462008-09-26 22:53:05 +000010172 if (CallerPAL.getParamAttributes(i + 1)
10173 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010174 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010175
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010176 // Converting from one pointer type to another or between a pointer and an
10177 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010178 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010179 (TD && ((isa<PointerType>(ParamTy) ||
10180 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10181 (isa<PointerType>(ActTy) ||
10182 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010183 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010184 }
10185
10186 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010187 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010188 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010189
Chris Lattner58d74912008-03-12 17:45:29 +000010190 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10191 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010192 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010193 // won't be dropping them. Check that these extra arguments have attributes
10194 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010195 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10196 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010197 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010198 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010199 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010200 return false;
10201 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010202
Chris Lattner9fe38862003-06-19 17:00:31 +000010203 // Okay, we decided that this is a safe thing to do: go ahead and start
10204 // inserting cast instructions as necessary...
10205 std::vector<Value*> Args;
10206 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010207 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010208 attrVec.reserve(NumCommonArgs);
10209
10210 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010211 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010212
10213 // If the return value is not being used, the type may not be compatible
10214 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010215 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010216
10217 // Add the new return attributes.
10218 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010219 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010220
10221 AI = CS.arg_begin();
10222 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10223 const Type *ParamTy = FT->getParamType(i);
10224 if ((*AI)->getType() == ParamTy) {
10225 Args.push_back(*AI);
10226 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010227 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010228 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010229 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
10232 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010233 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010235 }
10236
10237 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010238 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010239 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010240 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010241
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010242 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010243 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010244 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010245 errs() << "WARNING: While resolving call to function '"
10246 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010247 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010248 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010249 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10250 const Type *PTy = getPromotedType((*AI)->getType());
10251 if (PTy != (*AI)->getType()) {
10252 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010253 Instruction::CastOps opcode =
10254 CastInst::getCastOpcode(*AI, false, PTy, false);
10255 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 } else {
10257 Args.push_back(*AI);
10258 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010259
Duncan Sandse1e520f2008-01-13 08:02:44 +000010260 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010261 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010262 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010263 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010265 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010266
Devang Patel19c87462008-09-26 22:53:05 +000010267 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10268 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10269
Devang Patel9674d152009-10-14 17:29:00 +000010270 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010271 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010272
Eric Christophera66297a2009-07-25 02:45:27 +000010273 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10274 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010275
Chris Lattner9fe38862003-06-19 17:00:31 +000010276 Instruction *NC;
10277 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010278 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010279 Args.begin(), Args.end(),
10280 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010281 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010282 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010283 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010284 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10285 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010286 CallInst *CI = cast<CallInst>(Caller);
10287 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010288 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010289 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010290 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010291 }
10292
Chris Lattner6934a042007-02-11 01:23:03 +000010293 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010295 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010296 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010297 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010298 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010299 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010300
10301 // If this is an invoke instruction, we should insert it after the first
10302 // non-phi, instruction in the normal successor block.
10303 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010304 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010305 InsertNewInstBefore(NC, *I);
10306 } else {
10307 // Otherwise, it's a call, just insert cast right after the call instr
10308 InsertNewInstBefore(NC, *Caller);
10309 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010310 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010311 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010312 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010313 }
10314 }
10315
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010316
Chris Lattner931f8f32009-08-31 05:17:58 +000010317 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010318 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010319
10320 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 return true;
10322}
10323
Duncan Sandscdb6d922007-09-17 10:26:40 +000010324// transformCallThroughTrampoline - Turn a call to a function created by the
10325// init_trampoline intrinsic into a direct call to the underlying function.
10326//
10327Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10328 Value *Callee = CS.getCalledValue();
10329 const PointerType *PTy = cast<PointerType>(Callee->getType());
10330 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010331 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010332
10333 // If the call already has the 'nest' attribute somewhere then give up -
10334 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010335 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010336 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337
10338 IntrinsicInst *Tramp =
10339 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10340
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010341 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010342 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10343 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10344
Devang Patel05988662008-09-25 21:00:45 +000010345 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010346 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010347 unsigned NestIdx = 1;
10348 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010349 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010350
10351 // Look for a parameter marked with the 'nest' attribute.
10352 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10353 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010354 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010355 // Record the parameter type and any other attributes.
10356 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010357 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 break;
10359 }
10360
10361 if (NestTy) {
10362 Instruction *Caller = CS.getInstruction();
10363 std::vector<Value*> NewArgs;
10364 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10365
Devang Patel05988662008-09-25 21:00:45 +000010366 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010367 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010368
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010370 // mean appending it. Likewise for attributes.
10371
Devang Patel19c87462008-09-26 22:53:05 +000010372 // Add any result attributes.
10373 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010374 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010375
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 {
10377 unsigned Idx = 1;
10378 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10379 do {
10380 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010381 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 Value *NestVal = Tramp->getOperand(3);
10383 if (NestVal->getType() != NestTy)
10384 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10385 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010386 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 }
10388
10389 if (I == E)
10390 break;
10391
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010392 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010393 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010394 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010396 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397
10398 ++Idx, ++I;
10399 } while (1);
10400 }
10401
Devang Patel19c87462008-09-26 22:53:05 +000010402 // Add any function attributes.
10403 if (Attributes Attr = Attrs.getFnAttributes())
10404 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10405
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 // The trampoline may have been bitcast to a bogus type (FTy).
10407 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411 NewTypes.reserve(FTy->getNumParams()+1);
10412
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010414 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010415 {
10416 unsigned Idx = 1;
10417 FunctionType::param_iterator I = FTy->param_begin(),
10418 E = FTy->param_end();
10419
10420 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010421 if (Idx == NestIdx)
10422 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424
10425 if (I == E)
10426 break;
10427
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010428 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010429 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430
10431 ++Idx, ++I;
10432 } while (1);
10433 }
10434
10435 // Replace the trampoline call with a direct call. Let the generic
10436 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010437 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010438 FTy->isVarArg());
10439 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010440 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010441 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010442 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010443 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10444 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010445
10446 Instruction *NewCaller;
10447 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010448 NewCaller = InvokeInst::Create(NewCallee,
10449 II->getNormalDest(), II->getUnwindDest(),
10450 NewArgs.begin(), NewArgs.end(),
10451 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010453 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010455 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10456 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457 if (cast<CallInst>(Caller)->isTailCall())
10458 cast<CallInst>(NewCaller)->setTailCall();
10459 cast<CallInst>(NewCaller)->
10460 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010461 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010462 }
Devang Patel9674d152009-10-14 17:29:00 +000010463 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010464 Caller->replaceAllUsesWith(NewCaller);
10465 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010466 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010467 return 0;
10468 }
10469 }
10470
10471 // Replace the trampoline call with a direct call. Since there is no 'nest'
10472 // parameter, there is no need to adjust the argument list. Let the generic
10473 // code sort out any function type mismatches.
10474 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010475 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010476 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 CS.setCalledFunction(NewCallee);
10478 return CS.getInstruction();
10479}
10480
Dan Gohman9ad29202009-09-16 16:50:24 +000010481/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10482/// 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 +000010483/// and a single binop.
10484Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10485 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010486 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010487 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010488 Value *LHSVal = FirstInst->getOperand(0);
10489 Value *RHSVal = FirstInst->getOperand(1);
10490
10491 const Type *LHSType = LHSVal->getType();
10492 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010493
Dan Gohman9ad29202009-09-16 16:50:24 +000010494 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010495 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010496 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010497 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010498 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010499 // types or GEP's with different index types.
10500 I->getOperand(0)->getType() != LHSType ||
10501 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010502 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010503
10504 // If they are CmpInst instructions, check their predicates
10505 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10506 if (cast<CmpInst>(I)->getPredicate() !=
10507 cast<CmpInst>(FirstInst)->getPredicate())
10508 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010509
10510 // Keep track of which operand needs a phi node.
10511 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10512 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010513 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010514
10515 // If both LHS and RHS would need a PHI, don't do this transformation,
10516 // because it would increase the number of PHIs entering the block,
10517 // which leads to higher register pressure. This is especially
10518 // bad when the PHIs are in the header of a loop.
10519 if (!LHSVal && !RHSVal)
10520 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010521
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010522 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010523
Chris Lattner7da52b22006-11-01 04:51:18 +000010524 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010525 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010526 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010527 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010528 NewLHS = PHINode::Create(LHSType,
10529 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010530 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10531 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010532 InsertNewInstBefore(NewLHS, PN);
10533 LHSVal = NewLHS;
10534 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010535
10536 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010537 NewRHS = PHINode::Create(RHSType,
10538 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010539 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10540 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010541 InsertNewInstBefore(NewRHS, PN);
10542 RHSVal = NewRHS;
10543 }
10544
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010545 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010546 if (NewLHS || NewRHS) {
10547 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10548 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10549 if (NewLHS) {
10550 Value *NewInLHS = InInst->getOperand(0);
10551 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10552 }
10553 if (NewRHS) {
10554 Value *NewInRHS = InInst->getOperand(1);
10555 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10556 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010557 }
10558 }
10559
Chris Lattner7da52b22006-11-01 04:51:18 +000010560 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010561 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010562 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010563 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010564 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010565}
10566
Chris Lattner05f18922008-12-01 02:34:36 +000010567Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10568 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10569
10570 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10571 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010572 // This is true if all GEP bases are allocas and if all indices into them are
10573 // constants.
10574 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010575
10576 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010577 // more than one phi, which leads to higher register pressure. This is
10578 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010579 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010580
Dan Gohman9ad29202009-09-16 16:50:24 +000010581 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010582 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10583 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10584 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10585 GEP->getNumOperands() != FirstInst->getNumOperands())
10586 return 0;
10587
Chris Lattner36d3e322009-02-21 00:46:50 +000010588 // Keep track of whether or not all GEPs are of alloca pointers.
10589 if (AllBasePointersAreAllocas &&
10590 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10591 !GEP->hasAllConstantIndices()))
10592 AllBasePointersAreAllocas = false;
10593
Chris Lattner05f18922008-12-01 02:34:36 +000010594 // Compare the operand lists.
10595 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10596 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10597 continue;
10598
10599 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10600 // if one of the PHIs has a constant for the index. The index may be
10601 // substantially cheaper to compute for the constants, so making it a
10602 // variable index could pessimize the path. This also handles the case
10603 // for struct indices, which must always be constant.
10604 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10605 isa<ConstantInt>(GEP->getOperand(op)))
10606 return 0;
10607
10608 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10609 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010610
10611 // If we already needed a PHI for an earlier operand, and another operand
10612 // also requires a PHI, we'd be introducing more PHIs than we're
10613 // eliminating, which increases register pressure on entry to the PHI's
10614 // block.
10615 if (NeededPhi)
10616 return 0;
10617
Chris Lattner05f18922008-12-01 02:34:36 +000010618 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010619 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010620 }
10621 }
10622
Chris Lattner36d3e322009-02-21 00:46:50 +000010623 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010624 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010625 // offset calculation, but all the predecessors will have to materialize the
10626 // stack address into a register anyway. We'd actually rather *clone* the
10627 // load up into the predecessors so that we have a load of a gep of an alloca,
10628 // which can usually all be folded into the load.
10629 if (AllBasePointersAreAllocas)
10630 return 0;
10631
Chris Lattner05f18922008-12-01 02:34:36 +000010632 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10633 // that is variable.
10634 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10635
10636 bool HasAnyPHIs = false;
10637 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10638 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10639 Value *FirstOp = FirstInst->getOperand(i);
10640 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10641 FirstOp->getName()+".pn");
10642 InsertNewInstBefore(NewPN, PN);
10643
10644 NewPN->reserveOperandSpace(e);
10645 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10646 OperandPhis[i] = NewPN;
10647 FixedOperands[i] = NewPN;
10648 HasAnyPHIs = true;
10649 }
10650
10651
10652 // Add all operands to the new PHIs.
10653 if (HasAnyPHIs) {
10654 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10655 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10656 BasicBlock *InBB = PN.getIncomingBlock(i);
10657
10658 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10659 if (PHINode *OpPhi = OperandPhis[op])
10660 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10661 }
10662 }
10663
10664 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010665 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10666 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10667 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010668 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10669 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010670}
10671
10672
Chris Lattner21550882009-02-23 05:56:17 +000010673/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10674/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010675/// obvious the value of the load is not changed from the point of the load to
10676/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010677///
10678/// Finally, it is safe, but not profitable, to sink a load targetting a
10679/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10680/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010681static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010682 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10683
10684 for (++BBI; BBI != E; ++BBI)
10685 if (BBI->mayWriteToMemory())
10686 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010687
10688 // Check for non-address taken alloca. If not address-taken already, it isn't
10689 // profitable to do this xform.
10690 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10691 bool isAddressTaken = false;
10692 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10693 UI != E; ++UI) {
10694 if (isa<LoadInst>(UI)) continue;
10695 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10696 // If storing TO the alloca, then the address isn't taken.
10697 if (SI->getOperand(1) == AI) continue;
10698 }
10699 isAddressTaken = true;
10700 break;
10701 }
10702
Chris Lattner36d3e322009-02-21 00:46:50 +000010703 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010704 return false;
10705 }
10706
Chris Lattner36d3e322009-02-21 00:46:50 +000010707 // If this load is a load from a GEP with a constant offset from an alloca,
10708 // then we don't want to sink it. In its present form, it will be
10709 // load [constant stack offset]. Sinking it will cause us to have to
10710 // materialize the stack addresses in each predecessor in a register only to
10711 // do a shared load from register in the successor.
10712 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10713 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10714 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10715 return false;
10716
Chris Lattner76c73142006-11-01 07:13:54 +000010717 return true;
10718}
10719
Chris Lattner751a3622009-11-01 20:04:24 +000010720Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10721 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10722
10723 // When processing loads, we need to propagate two bits of information to the
10724 // sunk load: whether it is volatile, and what its alignment is. We currently
10725 // don't sink loads when some have their alignment specified and some don't.
10726 // visitLoadInst will propagate an alignment onto the load when TD is around,
10727 // and if TD isn't around, we can't handle the mixed case.
10728 bool isVolatile = FirstLI->isVolatile();
10729 unsigned LoadAlignment = FirstLI->getAlignment();
10730
10731 // We can't sink the load if the loaded value could be modified between the
10732 // load and the PHI.
10733 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10734 !isSafeAndProfitableToSinkLoad(FirstLI))
10735 return 0;
10736
10737 // If the PHI is of volatile loads and the load block has multiple
10738 // successors, sinking it would remove a load of the volatile value from
10739 // the path through the other successor.
10740 if (isVolatile &&
10741 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10742 return 0;
10743
10744 // Check to see if all arguments are the same operation.
10745 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10746 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10747 if (!LI || !LI->hasOneUse())
10748 return 0;
10749
10750 // We can't sink the load if the loaded value could be modified between
10751 // the load and the PHI.
10752 if (LI->isVolatile() != isVolatile ||
10753 LI->getParent() != PN.getIncomingBlock(i) ||
10754 !isSafeAndProfitableToSinkLoad(LI))
10755 return 0;
10756
10757 // If some of the loads have an alignment specified but not all of them,
10758 // we can't do the transformation.
10759 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10760 return 0;
10761
Chris Lattnera664bb72009-11-01 20:07:07 +000010762 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010763
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 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10769 return 0;
10770 }
10771
10772 // Okay, they are all the same operation. Create a new PHI node of the
10773 // correct type, and PHI together all of the LHS's of the instructions.
10774 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10775 PN.getName()+".in");
10776 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10777
10778 Value *InVal = FirstLI->getOperand(0);
10779 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10780
10781 // Add all operands to the new PHI.
10782 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10783 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10784 if (NewInVal != InVal)
10785 InVal = 0;
10786 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10787 }
10788
10789 Value *PhiVal;
10790 if (InVal) {
10791 // The new PHI unions all of the same values together. This is really
10792 // common, so we handle it intelligently here for compile-time speed.
10793 PhiVal = InVal;
10794 delete NewPN;
10795 } else {
10796 InsertNewInstBefore(NewPN, PN);
10797 PhiVal = NewPN;
10798 }
10799
10800 // If this was a volatile load that we are merging, make sure to loop through
10801 // and mark all the input loads as non-volatile. If we don't do this, we will
10802 // insert a new volatile load and the old ones will not be deletable.
10803 if (isVolatile)
10804 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10805 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10806
10807 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10808}
10809
Chris Lattner9fe38862003-06-19 17:00:31 +000010810
Chris Lattnerc22d4d12009-11-10 07:23:37 +000010811
10812/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10813/// operator and they all are only used by the PHI, PHI together their
10814/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010815Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10816 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10817
Chris Lattner751a3622009-11-01 20:04:24 +000010818 if (isa<GetElementPtrInst>(FirstInst))
10819 return FoldPHIArgGEPIntoPHI(PN);
10820 if (isa<LoadInst>(FirstInst))
10821 return FoldPHIArgLoadIntoPHI(PN);
10822
Chris Lattnerbac32862004-11-14 19:13:23 +000010823 // Scan the instruction, looking for input operations that can be folded away.
10824 // If all input operands to the phi are the same instruction (e.g. a cast from
10825 // the same type or "+42") we can pull the operation through the PHI, reducing
10826 // code size and simplifying code.
10827 Constant *ConstantOp = 0;
10828 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010829
Chris Lattnerbac32862004-11-14 19:13:23 +000010830 if (isa<CastInst>(FirstInst)) {
10831 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000010832
10833 // Be careful about transforming integer PHIs. We don't want to pessimize
10834 // the code by turning an i32 into an i1293.
10835 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000010836 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000010837 return 0;
10838 }
Reid Spencer832254e2007-02-02 02:16:23 +000010839 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010840 // Can fold binop, compare or shift here if the RHS is a constant,
10841 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010842 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010843 if (ConstantOp == 0)
10844 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010845 } else {
10846 return 0; // Cannot fold this operation.
10847 }
10848
10849 // Check to see if all arguments are the same operation.
10850 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010851 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10852 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010853 return 0;
10854 if (CastSrcTy) {
10855 if (I->getOperand(0)->getType() != CastSrcTy)
10856 return 0; // Cast operation must match.
10857 } else if (I->getOperand(1) != ConstantOp) {
10858 return 0;
10859 }
10860 }
10861
10862 // Okay, they are all the same operation. Create a new PHI node of the
10863 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010864 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10865 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010866 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010867
10868 Value *InVal = FirstInst->getOperand(0);
10869 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010870
10871 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010872 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10873 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10874 if (NewInVal != InVal)
10875 InVal = 0;
10876 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10877 }
10878
10879 Value *PhiVal;
10880 if (InVal) {
10881 // The new PHI unions all of the same values together. This is really
10882 // common, so we handle it intelligently here for compile-time speed.
10883 PhiVal = InVal;
10884 delete NewPN;
10885 } else {
10886 InsertNewInstBefore(NewPN, PN);
10887 PhiVal = NewPN;
10888 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010889
Chris Lattnerbac32862004-11-14 19:13:23 +000010890 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010891 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010892 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010893
Chris Lattner54545ac2008-04-29 17:13:43 +000010894 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010895 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010896
Chris Lattner751a3622009-11-01 20:04:24 +000010897 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10898 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10899 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010900}
Chris Lattnera1be5662002-05-02 17:06:02 +000010901
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010902/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10903/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010904static bool DeadPHICycle(PHINode *PN,
10905 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010906 if (PN->use_empty()) return true;
10907 if (!PN->hasOneUse()) return false;
10908
10909 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010910 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010911 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010912
10913 // Don't scan crazily complex things.
10914 if (PotentiallyDeadPHIs.size() == 16)
10915 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010916
10917 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10918 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010919
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010920 return false;
10921}
10922
Chris Lattnercf5008a2007-11-06 21:52:06 +000010923/// PHIsEqualValue - Return true if this phi node is always equal to
10924/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10925/// z = some value; x = phi (y, z); y = phi (x, z)
10926static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10927 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10928 // See if we already saw this PHI node.
10929 if (!ValueEqualPHIs.insert(PN))
10930 return true;
10931
10932 // Don't scan crazily complex things.
10933 if (ValueEqualPHIs.size() == 16)
10934 return false;
10935
10936 // Scan the operands to see if they are either phi nodes or are equal to
10937 // the value.
10938 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10939 Value *Op = PN->getIncomingValue(i);
10940 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10941 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10942 return false;
10943 } else if (Op != NonPhiInVal)
10944 return false;
10945 }
10946
10947 return true;
10948}
10949
10950
Chris Lattner9956c052009-11-08 19:23:30 +000010951namespace {
10952struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010953 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000010954 unsigned Shift; // The amount shifted.
10955 Instruction *Inst; // The trunc instruction.
10956
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010957 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
10958 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000010959
10960 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010961 if (PHIId < RHS.PHIId) return true;
10962 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000010963 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010964 if (Shift > RHS.Shift) return false;
10965 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000010966 RHS.Inst->getType()->getPrimitiveSizeInBits();
10967 }
10968};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010969
10970struct LoweredPHIRecord {
10971 PHINode *PN; // The PHI that was lowered.
10972 unsigned Shift; // The amount shifted.
10973 unsigned Width; // The width extracted.
10974
10975 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
10976 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
10977
10978 // Ctor form used by DenseMap.
10979 LoweredPHIRecord(PHINode *pn, unsigned Sh)
10980 : PN(pn), Shift(Sh), Width(0) {}
10981};
10982}
10983
10984namespace llvm {
10985 template<>
10986 struct DenseMapInfo<LoweredPHIRecord> {
10987 static inline LoweredPHIRecord getEmptyKey() {
10988 return LoweredPHIRecord(0, 0);
10989 }
10990 static inline LoweredPHIRecord getTombstoneKey() {
10991 return LoweredPHIRecord(0, 1);
10992 }
10993 static unsigned getHashValue(const LoweredPHIRecord &Val) {
10994 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
10995 (Val.Width>>3);
10996 }
10997 static bool isEqual(const LoweredPHIRecord &LHS,
10998 const LoweredPHIRecord &RHS) {
10999 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11000 LHS.Width == RHS.Width;
11001 }
11002 static bool isPod() { return true; }
11003 };
Chris Lattner9956c052009-11-08 19:23:30 +000011004}
11005
11006
11007/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11008/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11009/// so, we split the PHI into the various pieces being extracted. This sort of
11010/// thing is introduced when SROA promotes an aggregate to large integer values.
11011///
11012/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11013/// inttoptr. We should produce new PHIs in the right type.
11014///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011015Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11016 // PHIUsers - Keep track of all of the truncated values extracted from a set
11017 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011018 SmallVector<PHIUsageRecord, 16> PHIUsers;
11019
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011020 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11021 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11022 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11023 // check the uses of (to ensure they are all extracts).
11024 SmallVector<PHINode*, 8> PHIsToSlice;
11025 SmallPtrSet<PHINode*, 8> PHIsInspected;
11026
11027 PHIsToSlice.push_back(&FirstPhi);
11028 PHIsInspected.insert(&FirstPhi);
11029
11030 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11031 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011032
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011033 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11034 UI != E; ++UI) {
11035 Instruction *User = cast<Instruction>(*UI);
11036
11037 // If the user is a PHI, inspect its uses recursively.
11038 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11039 if (PHIsInspected.insert(UserPN))
11040 PHIsToSlice.push_back(UserPN);
11041 continue;
11042 }
11043
11044 // Truncates are always ok.
11045 if (isa<TruncInst>(User)) {
11046 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11047 continue;
11048 }
11049
11050 // Otherwise it must be a lshr which can only be used by one trunc.
11051 if (User->getOpcode() != Instruction::LShr ||
11052 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11053 !isa<ConstantInt>(User->getOperand(1)))
11054 return 0;
11055
11056 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11057 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011058 }
Chris Lattner9956c052009-11-08 19:23:30 +000011059 }
11060
11061 // If we have no users, they must be all self uses, just nuke the PHI.
11062 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011063 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011064
11065 // If this phi node is transformable, create new PHIs for all the pieces
11066 // extracted out of it. First, sort the users by their offset and size.
11067 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11068
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011069 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11070 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11071 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11072 );
Chris Lattner9956c052009-11-08 19:23:30 +000011073
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011074 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11075 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011076 DenseMap<BasicBlock*, Value*> PredValues;
11077
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011078 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11079 // introduce redundant PHIs.
11080 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11081
11082 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11083 unsigned PHIId = PHIUsers[UserI].PHIId;
11084 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011085 unsigned Offset = PHIUsers[UserI].Shift;
11086 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011087
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011088 PHINode *EltPHI;
11089
11090 // If we've already lowered a user like this, reuse the previously lowered
11091 // value.
11092 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011093
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011094 // Otherwise, Create the new PHI node for this user.
11095 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11096 assert(EltPHI->getType() != PN->getType() &&
11097 "Truncate didn't shrink phi?");
11098
11099 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11100 BasicBlock *Pred = PN->getIncomingBlock(i);
11101 Value *&PredVal = PredValues[Pred];
11102
11103 // If we already have a value for this predecessor, reuse it.
11104 if (PredVal) {
11105 EltPHI->addIncoming(PredVal, Pred);
11106 continue;
11107 }
Chris Lattner9956c052009-11-08 19:23:30 +000011108
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011109 // Handle the PHI self-reuse case.
11110 Value *InVal = PN->getIncomingValue(i);
11111 if (InVal == PN) {
11112 PredVal = EltPHI;
11113 EltPHI->addIncoming(PredVal, Pred);
11114 continue;
11115 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11116 // If the incoming value was a PHI, and if it was one of the PHIs we
11117 // already rewrote it, just use the lowered value.
11118 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11119 PredVal = Res;
11120 EltPHI->addIncoming(PredVal, Pred);
11121 continue;
11122 }
11123 }
11124
11125 // Otherwise, do an extract in the predecessor.
11126 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11127 Value *Res = InVal;
11128 if (Offset)
11129 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11130 Offset), "extract");
11131 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11132 PredVal = Res;
11133 EltPHI->addIncoming(Res, Pred);
11134
11135 // If the incoming value was a PHI, and if it was one of the PHIs we are
11136 // rewriting, we will ultimately delete the code we inserted. This
11137 // means we need to revisit that PHI to make sure we extract out the
11138 // needed piece.
11139 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11140 if (PHIsInspected.count(OldInVal)) {
11141 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11142 OldInVal)-PHIsToSlice.begin();
11143 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11144 cast<Instruction>(Res)));
11145 ++UserE;
11146 }
Chris Lattner9956c052009-11-08 19:23:30 +000011147 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011148 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011149
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011150 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11151 << *EltPHI << '\n');
11152 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011153 }
Chris Lattner9956c052009-11-08 19:23:30 +000011154
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011155 // Replace the use of this piece with the PHI node.
11156 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011157 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011158
11159 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11160 // with undefs.
11161 Value *Undef = UndefValue::get(FirstPhi.getType());
11162 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11163 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11164 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011165}
11166
Chris Lattner473945d2002-05-06 18:06:38 +000011167// PHINode simplification
11168//
Chris Lattner7e708292002-06-25 16:13:24 +000011169Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011170 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011171 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011172
Owen Anderson7e057142006-07-10 22:03:18 +000011173 if (Value *V = PN.hasConstantValue())
11174 return ReplaceInstUsesWith(PN, V);
11175
Owen Anderson7e057142006-07-10 22:03:18 +000011176 // If all PHI operands are the same operation, pull them through the PHI,
11177 // reducing code size.
11178 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011179 isa<Instruction>(PN.getIncomingValue(1)) &&
11180 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11181 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11182 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11183 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011184 PN.getIncomingValue(0)->hasOneUse())
11185 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11186 return Result;
11187
11188 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11189 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11190 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011191 if (PN.hasOneUse()) {
11192 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11193 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011194 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011195 PotentiallyDeadPHIs.insert(&PN);
11196 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011197 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011198 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011199
11200 // If this phi has a single use, and if that use just computes a value for
11201 // the next iteration of a loop, delete the phi. This occurs with unused
11202 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11203 // common case here is good because the only other things that catch this
11204 // are induction variable analysis (sometimes) and ADCE, which is only run
11205 // late.
11206 if (PHIUser->hasOneUse() &&
11207 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11208 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011209 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011210 }
11211 }
Owen Anderson7e057142006-07-10 22:03:18 +000011212
Chris Lattnercf5008a2007-11-06 21:52:06 +000011213 // We sometimes end up with phi cycles that non-obviously end up being the
11214 // same value, for example:
11215 // z = some value; x = phi (y, z); y = phi (x, z)
11216 // where the phi nodes don't necessarily need to be in the same block. Do a
11217 // quick check to see if the PHI node only contains a single non-phi value, if
11218 // so, scan to see if the phi cycle is actually equal to that value.
11219 {
11220 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11221 // Scan for the first non-phi operand.
11222 while (InValNo != NumOperandVals &&
11223 isa<PHINode>(PN.getIncomingValue(InValNo)))
11224 ++InValNo;
11225
11226 if (InValNo != NumOperandVals) {
11227 Value *NonPhiInVal = PN.getOperand(InValNo);
11228
11229 // Scan the rest of the operands to see if there are any conflicts, if so
11230 // there is no need to recursively scan other phis.
11231 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11232 Value *OpVal = PN.getIncomingValue(InValNo);
11233 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11234 break;
11235 }
11236
11237 // If we scanned over all operands, then we have one unique value plus
11238 // phi values. Scan PHI nodes to see if they all merge in each other or
11239 // the value.
11240 if (InValNo == NumOperandVals) {
11241 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11242 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11243 return ReplaceInstUsesWith(PN, NonPhiInVal);
11244 }
11245 }
11246 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011247
Dan Gohman5b097012009-10-31 14:22:52 +000011248 // If there are multiple PHIs, sort their operands so that they all list
11249 // the blocks in the same order. This will help identical PHIs be eliminated
11250 // by other passes. Other passes shouldn't depend on this for correctness
11251 // however.
11252 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11253 if (&PN != FirstPN)
11254 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011255 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011256 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11257 if (BBA != BBB) {
11258 Value *VA = PN.getIncomingValue(i);
11259 unsigned j = PN.getBasicBlockIndex(BBB);
11260 Value *VB = PN.getIncomingValue(j);
11261 PN.setIncomingBlock(i, BBB);
11262 PN.setIncomingValue(i, VB);
11263 PN.setIncomingBlock(j, BBA);
11264 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011265 // NOTE: Instcombine normally would want us to "return &PN" if we
11266 // modified any of the operands of an instruction. However, since we
11267 // aren't adding or removing uses (just rearranging them) we don't do
11268 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011269 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011270 }
11271
Chris Lattner9956c052009-11-08 19:23:30 +000011272 // If this is an integer PHI and we know that it has an illegal type, see if
11273 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11274 // PHI into the various pieces being extracted. This sort of thing is
11275 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011276 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011277 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11278 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11279 return Res;
11280
Chris Lattner60921c92003-12-19 05:58:40 +000011281 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011282}
11283
Chris Lattner7e708292002-06-25 16:13:24 +000011284Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011285 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011286 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011287 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011288 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011289
Chris Lattnere87597f2004-10-16 18:11:37 +000011290 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011291 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011292
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011293 bool HasZeroPointerIndex = false;
11294 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11295 HasZeroPointerIndex = C->isNullValue();
11296
11297 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011298 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011299
Chris Lattner28977af2004-04-05 01:30:19 +000011300 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011301 if (TD) {
11302 bool MadeChange = false;
11303 unsigned PtrSize = TD->getPointerSizeInBits();
11304
11305 gep_type_iterator GTI = gep_type_begin(GEP);
11306 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11307 I != E; ++I, ++GTI) {
11308 if (!isa<SequentialType>(*GTI)) continue;
11309
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011310 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011311 // to what we need. If narrower, sign-extend it to what we need. This
11312 // explicit cast can make subsequent optimizations more obvious.
11313 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011314 if (OpBits == PtrSize)
11315 continue;
11316
Chris Lattner2345d1d2009-08-30 20:01:10 +000011317 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011318 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011319 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011320 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011321 }
Chris Lattner28977af2004-04-05 01:30:19 +000011322
Chris Lattner90ac28c2002-08-02 19:29:35 +000011323 // Combine Indices - If the source pointer to this getelementptr instruction
11324 // is a getelementptr instruction, combine the indices of the two
11325 // getelementptr instructions into a single instruction.
11326 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011327 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011328 // Note that if our source is a gep chain itself that we wait for that
11329 // chain to be resolved before we perform this transformation. This
11330 // avoids us creating a TON of code in some cases.
11331 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011332 if (GetElementPtrInst *SrcGEP =
11333 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11334 if (SrcGEP->getNumOperands() == 2)
11335 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011336
Chris Lattner72588fc2007-02-15 22:48:32 +000011337 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011338
11339 // Find out whether the last index in the source GEP is a sequential idx.
11340 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011341 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11342 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011343 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011344
Chris Lattner90ac28c2002-08-02 19:29:35 +000011345 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011346 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011347 // Replace: gep (gep %P, long B), long A, ...
11348 // With: T = long A+B; gep %P, T, ...
11349 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011350 Value *Sum;
11351 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11352 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011353 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011354 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011355 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011356 Sum = SO1;
11357 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011358 // If they aren't the same type, then the input hasn't been processed
11359 // by the loop above yet (which canonicalizes sequential index types to
11360 // intptr_t). Just avoid transforming this until the input has been
11361 // normalized.
11362 if (SO1->getType() != GO1->getType())
11363 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011364 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011365 }
Chris Lattner620ce142004-05-07 22:09:22 +000011366
Chris Lattnerab984842009-08-30 05:30:55 +000011367 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011368 if (Src->getNumOperands() == 2) {
11369 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011370 GEP.setOperand(1, Sum);
11371 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011372 }
Chris Lattnerab984842009-08-30 05:30:55 +000011373 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011374 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011375 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011376 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011377 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011378 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011379 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011380 Indices.append(Src->op_begin()+1, Src->op_end());
11381 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011382 }
11383
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011384 if (!Indices.empty())
11385 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11386 Src->isInBounds()) ?
11387 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11388 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011389 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011390 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011391 }
11392
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011393 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11394 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011395 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011396
Chris Lattner2de23192009-08-30 20:38:21 +000011397 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11398 // want to change the gep until the bitcasts are eliminated.
11399 if (getBitCastOperand(X)) {
11400 Worklist.AddValue(PtrOp);
11401 return 0;
11402 }
11403
Chris Lattner963f4ba2009-08-30 20:36:46 +000011404 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11405 // into : GEP [10 x i8]* X, i32 0, ...
11406 //
11407 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11408 // into : GEP i8* X, ...
11409 //
11410 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011411 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011412 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11413 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011414 if (const ArrayType *CATy =
11415 dyn_cast<ArrayType>(CPTy->getElementType())) {
11416 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11417 if (CATy->getElementType() == XTy->getElementType()) {
11418 // -> GEP i8* X, ...
11419 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011420 return cast<GEPOperator>(&GEP)->isInBounds() ?
11421 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11422 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011423 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11424 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011425 }
11426
11427 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011428 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011429 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011430 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011431 // At this point, we know that the cast source type is a pointer
11432 // to an array of the same type as the destination pointer
11433 // array. Because the array type is never stepped over (there
11434 // is a leading zero) we can fold the cast into this GEP.
11435 GEP.setOperand(0, X);
11436 return &GEP;
11437 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011438 }
11439 }
Chris Lattnereed48272005-09-13 00:40:14 +000011440 } else if (GEP.getNumOperands() == 2) {
11441 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011442 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11443 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011444 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11445 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011446 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011447 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11448 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011449 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011450 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011451 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011452 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11453 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011454 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011455 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011456 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011457 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011458
11459 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011460 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011461 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011462 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011463
Owen Anderson1d0be152009-08-13 21:58:54 +000011464 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011465 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011466 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011467
11468 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11469 // allow either a mul, shift, or constant here.
11470 Value *NewIdx = 0;
11471 ConstantInt *Scale = 0;
11472 if (ArrayEltSize == 1) {
11473 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011474 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011475 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011476 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011477 Scale = CI;
11478 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11479 if (Inst->getOpcode() == Instruction::Shl &&
11480 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011481 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11482 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011483 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011484 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011485 NewIdx = Inst->getOperand(0);
11486 } else if (Inst->getOpcode() == Instruction::Mul &&
11487 isa<ConstantInt>(Inst->getOperand(1))) {
11488 Scale = cast<ConstantInt>(Inst->getOperand(1));
11489 NewIdx = Inst->getOperand(0);
11490 }
11491 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011492
Chris Lattner7835cdd2005-09-13 18:36:04 +000011493 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011494 // out, perform the transformation. Note, we don't know whether Scale is
11495 // signed or not. We'll use unsigned version of division/modulo
11496 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011497 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011498 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011499 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011500 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011501 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011502 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11503 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011504 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011505 }
11506
11507 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011508 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011509 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011510 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011511 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11512 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11513 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011514 // The NewGEP must be pointer typed, so must the old one -> BitCast
11515 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011516 }
11517 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011518 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011519 }
Chris Lattner58407792009-01-09 04:53:57 +000011520
Chris Lattner46cd5a12009-01-09 05:44:56 +000011521 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011522 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011523 /// Y = gep X, <...constant indices...>
11524 /// into a gep of the original struct. This is important for SROA and alias
11525 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011526 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011527 if (TD &&
11528 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011529 // Determine how much the GEP moves the pointer. We are guaranteed to get
11530 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011531 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011532 int64_t Offset = OffsetV->getSExtValue();
11533
11534 // If this GEP instruction doesn't move the pointer, just replace the GEP
11535 // with a bitcast of the real input to the dest type.
11536 if (Offset == 0) {
11537 // If the bitcast is of an allocation, and the allocation will be
11538 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011539 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011540 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011541 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11542 if (Instruction *I = visitBitCast(*BCI)) {
11543 if (I != BCI) {
11544 I->takeName(BCI);
11545 BCI->getParent()->getInstList().insert(BCI, I);
11546 ReplaceInstUsesWith(*BCI, I);
11547 }
11548 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011549 }
Chris Lattner58407792009-01-09 04:53:57 +000011550 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011551 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011552 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011553
11554 // Otherwise, if the offset is non-zero, we need to find out if there is a
11555 // field at Offset in 'A's type. If so, we can pull the cast through the
11556 // GEP.
11557 SmallVector<Value*, 8> NewIndices;
11558 const Type *InTy =
11559 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011560 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011561 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11562 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11563 NewIndices.end()) :
11564 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11565 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011566
11567 if (NGEP->getType() == GEP.getType())
11568 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011569 NGEP->takeName(&GEP);
11570 return new BitCastInst(NGEP, GEP.getType());
11571 }
Chris Lattner58407792009-01-09 04:53:57 +000011572 }
11573 }
11574
Chris Lattner8a2a3112001-12-14 16:52:21 +000011575 return 0;
11576}
11577
Victor Hernandez7b929da2009-10-23 21:09:37 +000011578Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011579 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011580 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011581 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11582 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011583 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011584 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011585 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011586 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011587
Chris Lattner0864acf2002-11-04 16:18:53 +000011588 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011589 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011590 //
11591 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011592 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011593
11594 // Now that I is pointing to the first non-allocation-inst in the block,
11595 // insert our getelementptr instruction...
11596 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011597 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011598 Value *Idx[2];
11599 Idx[0] = NullIdx;
11600 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011601 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11602 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011603
11604 // Now make everything use the getelementptr instead of the original
11605 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011606 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011607 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011608 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011609 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011610 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011611
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011612 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011613 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011614 // Note that we only do this for alloca's, because malloc should allocate
11615 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011616 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011617 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011618
11619 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11620 if (AI.getAlignment() == 0)
11621 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11622 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011623
Chris Lattner0864acf2002-11-04 16:18:53 +000011624 return 0;
11625}
11626
Victor Hernandez66284e02009-10-24 04:23:03 +000011627Instruction *InstCombiner::visitFree(Instruction &FI) {
11628 Value *Op = FI.getOperand(1);
11629
11630 // free undef -> unreachable.
11631 if (isa<UndefValue>(Op)) {
11632 // Insert a new store to null because we cannot modify the CFG here.
11633 new StoreInst(ConstantInt::getTrue(*Context),
11634 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11635 return EraseInstFromFunction(FI);
11636 }
11637
11638 // If we have 'free null' delete the instruction. This can happen in stl code
11639 // when lots of inlining happens.
11640 if (isa<ConstantPointerNull>(Op))
11641 return EraseInstFromFunction(FI);
11642
Victor Hernandez046e78c2009-10-26 23:43:48 +000011643 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011644 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011645 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11646 if (Op->hasOneUse() && CI->hasOneUse()) {
11647 EraseInstFromFunction(FI);
11648 EraseInstFromFunction(*CI);
11649 return EraseInstFromFunction(*cast<Instruction>(Op));
11650 }
11651 } else {
11652 // Op is a call to malloc
11653 if (Op->hasOneUse()) {
11654 EraseInstFromFunction(FI);
11655 return EraseInstFromFunction(*cast<Instruction>(Op));
11656 }
11657 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011658 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011659
11660 return 0;
11661}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011662
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011663/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011664static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011665 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011666 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011667 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011668 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011669
Mon P Wang6753f952009-02-07 22:19:29 +000011670 const PointerType *DestTy = cast<PointerType>(CI->getType());
11671 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011672 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011673
11674 // If the address spaces don't match, don't eliminate the cast.
11675 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11676 return 0;
11677
Chris Lattnerb89e0712004-07-13 01:49:43 +000011678 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011679
Reid Spencer42230162007-01-22 05:51:25 +000011680 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011681 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011682 // If the source is an array, the code below will not succeed. Check to
11683 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11684 // constants.
11685 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11686 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11687 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011688 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011689 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11690 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011691 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011692 SrcTy = cast<PointerType>(CastOp->getType());
11693 SrcPTy = SrcTy->getElementType();
11694 }
11695
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011696 if (IC.getTargetData() &&
11697 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011698 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011699 // Do not allow turning this into a load of an integer, which is then
11700 // casted to a pointer, this pessimizes pointer analysis a lot.
11701 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011702 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11703 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011704
Chris Lattnerf9527852005-01-31 04:50:46 +000011705 // Okay, we are casting from one integer or pointer type to another of
11706 // the same size. Instead of casting the pointer before the load, cast
11707 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011708 Value *NewLoad =
11709 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011710 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011711 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011712 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011713 }
11714 }
11715 return 0;
11716}
11717
Chris Lattner833b8a42003-06-26 05:06:25 +000011718Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11719 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011720
Dan Gohman9941f742007-07-20 16:34:21 +000011721 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011722 if (TD) {
11723 unsigned KnownAlign =
11724 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11725 if (KnownAlign >
11726 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11727 LI.getAlignment()))
11728 LI.setAlignment(KnownAlign);
11729 }
Dan Gohman9941f742007-07-20 16:34:21 +000011730
Chris Lattner963f4ba2009-08-30 20:36:46 +000011731 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011732 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011733 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011734 return Res;
11735
11736 // None of the following transforms are legal for volatile loads.
11737 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011738
Dan Gohman2276a7b2008-10-15 23:19:35 +000011739 // Do really simple store-to-load forwarding and load CSE, to catch cases
11740 // where there are several consequtive memory accesses to the same location,
11741 // separated by a few arithmetic operations.
11742 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011743 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11744 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011745
Chris Lattner878e4942009-10-22 06:25:11 +000011746 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011747 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11748 const Value *GEPI0 = GEPI->getOperand(0);
11749 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011750 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011751 // Insert a new store to null instruction before the load to indicate
11752 // that this code is not reachable. We do this instead of inserting
11753 // an unreachable instruction directly because we cannot modify the
11754 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011755 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011756 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011757 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011758 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011759 }
Chris Lattner37366c12005-05-01 04:24:53 +000011760
Chris Lattner878e4942009-10-22 06:25:11 +000011761 // load null/undef -> unreachable
11762 // TODO: Consider a target hook for valid address spaces for this xform.
11763 if (isa<UndefValue>(Op) ||
11764 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11765 // Insert a new store to null instruction before the load to indicate that
11766 // this code is not reachable. We do this instead of inserting an
11767 // unreachable instruction directly because we cannot modify the CFG.
11768 new StoreInst(UndefValue::get(LI.getType()),
11769 Constant::getNullValue(Op->getType()), &LI);
11770 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011771 }
Chris Lattner878e4942009-10-22 06:25:11 +000011772
11773 // Instcombine load (constantexpr_cast global) -> cast (load global)
11774 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11775 if (CE->isCast())
11776 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11777 return Res;
11778
Chris Lattner37366c12005-05-01 04:24:53 +000011779 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011780 // Change select and PHI nodes to select values instead of addresses: this
11781 // helps alias analysis out a lot, allows many others simplifications, and
11782 // exposes redundancy in the code.
11783 //
11784 // Note that we cannot do the transformation unless we know that the
11785 // introduced loads cannot trap! Something like this is valid as long as
11786 // the condition is always false: load (select bool %C, int* null, int* %G),
11787 // but it would not be valid if we transformed it to load from null
11788 // unconditionally.
11789 //
11790 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11791 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011792 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11793 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011794 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11795 SI->getOperand(1)->getName()+".val");
11796 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11797 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011798 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011799 }
11800
Chris Lattner684fe212004-09-23 15:46:00 +000011801 // load (select (cond, null, P)) -> load P
11802 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11803 if (C->isNullValue()) {
11804 LI.setOperand(0, SI->getOperand(2));
11805 return &LI;
11806 }
11807
11808 // load (select (cond, P, null)) -> load P
11809 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11810 if (C->isNullValue()) {
11811 LI.setOperand(0, SI->getOperand(1));
11812 return &LI;
11813 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011814 }
11815 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011816 return 0;
11817}
11818
Reid Spencer55af2b52007-01-19 21:20:31 +000011819/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011820/// when possible. This makes it generally easy to do alias analysis and/or
11821/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011822static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11823 User *CI = cast<User>(SI.getOperand(1));
11824 Value *CastOp = CI->getOperand(0);
11825
11826 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011827 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11828 if (SrcTy == 0) return 0;
11829
11830 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011831
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011832 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11833 return 0;
11834
Chris Lattner3914f722009-01-24 01:00:13 +000011835 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11836 /// to its first element. This allows us to handle things like:
11837 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11838 /// on 32-bit hosts.
11839 SmallVector<Value*, 4> NewGEPIndices;
11840
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011841 // If the source is an array, the code below will not succeed. Check to
11842 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11843 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011844 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11845 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011846 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011847 NewGEPIndices.push_back(Zero);
11848
11849 while (1) {
11850 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011851 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011852 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011853 NewGEPIndices.push_back(Zero);
11854 SrcPTy = STy->getElementType(0);
11855 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11856 NewGEPIndices.push_back(Zero);
11857 SrcPTy = ATy->getElementType();
11858 } else {
11859 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011860 }
Chris Lattner3914f722009-01-24 01:00:13 +000011861 }
11862
Owen Andersondebcb012009-07-29 22:17:13 +000011863 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011864 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011865
11866 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11867 return 0;
11868
Chris Lattner71759c42009-01-16 20:12:52 +000011869 // If the pointers point into different address spaces or if they point to
11870 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011871 if (!IC.getTargetData() ||
11872 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011873 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011874 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11875 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011876 return 0;
11877
11878 // Okay, we are casting from one integer or pointer type to another of
11879 // the same size. Instead of casting the pointer before
11880 // the store, cast the value to be stored.
11881 Value *NewCast;
11882 Value *SIOp0 = SI.getOperand(0);
11883 Instruction::CastOps opcode = Instruction::BitCast;
11884 const Type* CastSrcTy = SIOp0->getType();
11885 const Type* CastDstTy = SrcPTy;
11886 if (isa<PointerType>(CastDstTy)) {
11887 if (CastSrcTy->isInteger())
11888 opcode = Instruction::IntToPtr;
11889 } else if (isa<IntegerType>(CastDstTy)) {
11890 if (isa<PointerType>(SIOp0->getType()))
11891 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011892 }
Chris Lattner3914f722009-01-24 01:00:13 +000011893
11894 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11895 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011896 if (!NewGEPIndices.empty())
11897 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11898 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011899
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011900 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11901 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011902 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011903}
11904
Chris Lattner4aebaee2008-11-27 08:56:30 +000011905/// equivalentAddressValues - Test if A and B will obviously have the same
11906/// value. This includes recognizing that %t0 and %t1 will have the same
11907/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011908/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011909/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011910/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011911/// %t2 = load i32* %t1
11912///
11913static bool equivalentAddressValues(Value *A, Value *B) {
11914 // Test if the values are trivially equivalent.
11915 if (A == B) return true;
11916
11917 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011918 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11919 // its only used to compare two uses within the same basic block, which
11920 // means that they'll always either have the same value or one of them
11921 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011922 if (isa<BinaryOperator>(A) ||
11923 isa<CastInst>(A) ||
11924 isa<PHINode>(A) ||
11925 isa<GetElementPtrInst>(A))
11926 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011927 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011928 return true;
11929
11930 // Otherwise they may not be equivalent.
11931 return false;
11932}
11933
Dale Johannesen4945c652009-03-03 21:26:39 +000011934// If this instruction has two uses, one of which is a llvm.dbg.declare,
11935// return the llvm.dbg.declare.
11936DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11937 if (!V->hasNUses(2))
11938 return 0;
11939 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11940 UI != E; ++UI) {
11941 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11942 return DI;
11943 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11944 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11945 return DI;
11946 }
11947 }
11948 return 0;
11949}
11950
Chris Lattner2f503e62005-01-31 05:36:43 +000011951Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11952 Value *Val = SI.getOperand(0);
11953 Value *Ptr = SI.getOperand(1);
11954
11955 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011956 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011957 ++NumCombined;
11958 return 0;
11959 }
Chris Lattner836692d2007-01-15 06:51:56 +000011960
11961 // If the RHS is an alloca with a single use, zapify the store, making the
11962 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011963 // If the RHS is an alloca with a two uses, the other one being a
11964 // llvm.dbg.declare, zapify the store and the declare, making the
11965 // alloca dead. We must do this to prevent declare's from affecting
11966 // codegen.
11967 if (!SI.isVolatile()) {
11968 if (Ptr->hasOneUse()) {
11969 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011970 EraseInstFromFunction(SI);
11971 ++NumCombined;
11972 return 0;
11973 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011974 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11975 if (isa<AllocaInst>(GEP->getOperand(0))) {
11976 if (GEP->getOperand(0)->hasOneUse()) {
11977 EraseInstFromFunction(SI);
11978 ++NumCombined;
11979 return 0;
11980 }
11981 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11982 EraseInstFromFunction(*DI);
11983 EraseInstFromFunction(SI);
11984 ++NumCombined;
11985 return 0;
11986 }
11987 }
11988 }
11989 }
11990 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11991 EraseInstFromFunction(*DI);
11992 EraseInstFromFunction(SI);
11993 ++NumCombined;
11994 return 0;
11995 }
Chris Lattner836692d2007-01-15 06:51:56 +000011996 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011997
Dan Gohman9941f742007-07-20 16:34:21 +000011998 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011999 if (TD) {
12000 unsigned KnownAlign =
12001 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12002 if (KnownAlign >
12003 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12004 SI.getAlignment()))
12005 SI.setAlignment(KnownAlign);
12006 }
Dan Gohman9941f742007-07-20 16:34:21 +000012007
Dale Johannesenacb51a32009-03-03 01:43:03 +000012008 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012009 // stores to the same location, separated by a few arithmetic operations. This
12010 // situation often occurs with bitfield accesses.
12011 BasicBlock::iterator BBI = &SI;
12012 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12013 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012014 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012015 // Don't count debug info directives, lest they affect codegen,
12016 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12017 // It is necessary for correctness to skip those that feed into a
12018 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012019 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012020 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012021 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012022 continue;
12023 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012024
12025 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12026 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012027 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12028 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012029 ++NumDeadStore;
12030 ++BBI;
12031 EraseInstFromFunction(*PrevSI);
12032 continue;
12033 }
12034 break;
12035 }
12036
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012037 // If this is a load, we have to stop. However, if the loaded value is from
12038 // the pointer we're loading and is producing the pointer we're storing,
12039 // then *this* store is dead (X = load P; store X -> P).
12040 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012041 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12042 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012043 EraseInstFromFunction(SI);
12044 ++NumCombined;
12045 return 0;
12046 }
12047 // Otherwise, this is a load from some other location. Stores before it
12048 // may not be dead.
12049 break;
12050 }
12051
Chris Lattner9ca96412006-02-08 03:25:32 +000012052 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012053 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012054 break;
12055 }
12056
12057
12058 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012059
12060 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012061 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012062 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012063 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012064 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012065 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012066 ++NumCombined;
12067 }
12068 return 0; // Do not modify these!
12069 }
12070
12071 // store undef, Ptr -> noop
12072 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012073 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012074 ++NumCombined;
12075 return 0;
12076 }
12077
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012078 // If the pointer destination is a cast, see if we can fold the cast into the
12079 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012080 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012081 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12082 return Res;
12083 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012084 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012085 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12086 return Res;
12087
Chris Lattner408902b2005-09-12 23:23:25 +000012088
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012089 // If this store is the last instruction in the basic block (possibly
12090 // excepting debug info instructions and the pointer bitcasts that feed
12091 // into them), and if the block ends with an unconditional branch, try
12092 // to move it to the successor block.
12093 BBI = &SI;
12094 do {
12095 ++BBI;
12096 } while (isa<DbgInfoIntrinsic>(BBI) ||
12097 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012098 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012099 if (BI->isUnconditional())
12100 if (SimplifyStoreAtEndOfBlock(SI))
12101 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012102
Chris Lattner2f503e62005-01-31 05:36:43 +000012103 return 0;
12104}
12105
Chris Lattner3284d1f2007-04-15 00:07:55 +000012106/// SimplifyStoreAtEndOfBlock - Turn things like:
12107/// if () { *P = v1; } else { *P = v2 }
12108/// into a phi node with a store in the successor.
12109///
Chris Lattner31755a02007-04-15 01:02:18 +000012110/// Simplify things like:
12111/// *P = v1; if () { *P = v2; }
12112/// into a phi node with a store in the successor.
12113///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012114bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12115 BasicBlock *StoreBB = SI.getParent();
12116
12117 // Check to see if the successor block has exactly two incoming edges. If
12118 // so, see if the other predecessor contains a store to the same location.
12119 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012120 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012121
12122 // Determine whether Dest has exactly two predecessors and, if so, compute
12123 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012124 pred_iterator PI = pred_begin(DestBB);
12125 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012126 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012127 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012128 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012129 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012130 return false;
12131
12132 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012133 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012134 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012135 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012136 }
Chris Lattner31755a02007-04-15 01:02:18 +000012137 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012138 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012139
12140 // Bail out if all the relevant blocks aren't distinct (this can happen,
12141 // for example, if SI is in an infinite loop)
12142 if (StoreBB == DestBB || OtherBB == DestBB)
12143 return false;
12144
Chris Lattner31755a02007-04-15 01:02:18 +000012145 // Verify that the other block ends in a branch and is not otherwise empty.
12146 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012147 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012148 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012149 return false;
12150
Chris Lattner31755a02007-04-15 01:02:18 +000012151 // If the other block ends in an unconditional branch, check for the 'if then
12152 // else' case. there is an instruction before the branch.
12153 StoreInst *OtherStore = 0;
12154 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012155 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012156 // Skip over debugging info.
12157 while (isa<DbgInfoIntrinsic>(BBI) ||
12158 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12159 if (BBI==OtherBB->begin())
12160 return false;
12161 --BBI;
12162 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012163 // If this isn't a store, isn't a store to the same location, or if the
12164 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012165 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012166 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12167 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012168 return false;
12169 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012170 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012171 // destinations is StoreBB, then we have the if/then case.
12172 if (OtherBr->getSuccessor(0) != StoreBB &&
12173 OtherBr->getSuccessor(1) != StoreBB)
12174 return false;
12175
12176 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012177 // if/then triangle. See if there is a store to the same ptr as SI that
12178 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012179 for (;; --BBI) {
12180 // Check to see if we find the matching store.
12181 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012182 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12183 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012184 return false;
12185 break;
12186 }
Eli Friedman6903a242008-06-13 22:02:12 +000012187 // If we find something that may be using or overwriting the stored
12188 // value, or if we run out of instructions, we can't do the xform.
12189 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012190 BBI == OtherBB->begin())
12191 return false;
12192 }
12193
12194 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012195 // make sure nothing reads or overwrites the stored value in
12196 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012197 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12198 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012199 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012200 return false;
12201 }
12202 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012203
Chris Lattner31755a02007-04-15 01:02:18 +000012204 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012205 Value *MergedVal = OtherStore->getOperand(0);
12206 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012207 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012208 PN->reserveOperandSpace(2);
12209 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012210 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12211 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012212 }
12213
12214 // Advance to a place where it is safe to insert the new store and
12215 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012216 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012217 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012218 OtherStore->isVolatile(),
12219 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012220
12221 // Nuke the old stores.
12222 EraseInstFromFunction(SI);
12223 EraseInstFromFunction(*OtherStore);
12224 ++NumCombined;
12225 return true;
12226}
12227
Chris Lattner2f503e62005-01-31 05:36:43 +000012228
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012229Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12230 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012231 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012232 BasicBlock *TrueDest;
12233 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012234 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012235 !isa<Constant>(X)) {
12236 // Swap Destinations and condition...
12237 BI.setCondition(X);
12238 BI.setSuccessor(0, FalseDest);
12239 BI.setSuccessor(1, TrueDest);
12240 return &BI;
12241 }
12242
Reid Spencere4d87aa2006-12-23 06:05:41 +000012243 // Cannonicalize fcmp_one -> fcmp_oeq
12244 FCmpInst::Predicate FPred; Value *Y;
12245 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012246 TrueDest, FalseDest)) &&
12247 BI.getCondition()->hasOneUse())
12248 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12249 FPred == FCmpInst::FCMP_OGE) {
12250 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12251 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12252
12253 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012254 BI.setSuccessor(0, FalseDest);
12255 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012256 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012257 return &BI;
12258 }
12259
12260 // Cannonicalize icmp_ne -> icmp_eq
12261 ICmpInst::Predicate IPred;
12262 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012263 TrueDest, FalseDest)) &&
12264 BI.getCondition()->hasOneUse())
12265 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12266 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12267 IPred == ICmpInst::ICMP_SGE) {
12268 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12269 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12270 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012271 BI.setSuccessor(0, FalseDest);
12272 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012273 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012274 return &BI;
12275 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012276
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012277 return 0;
12278}
Chris Lattner0864acf2002-11-04 16:18:53 +000012279
Chris Lattner46238a62004-07-03 00:26:11 +000012280Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12281 Value *Cond = SI.getCondition();
12282 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12283 if (I->getOpcode() == Instruction::Add)
12284 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12285 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12286 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012287 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012288 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012289 AddRHS));
12290 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012291 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012292 return &SI;
12293 }
12294 }
12295 return 0;
12296}
12297
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012298Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012299 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012300
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012301 if (!EV.hasIndices())
12302 return ReplaceInstUsesWith(EV, Agg);
12303
12304 if (Constant *C = dyn_cast<Constant>(Agg)) {
12305 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012306 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012307
12308 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012309 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012310
12311 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12312 // Extract the element indexed by the first index out of the constant
12313 Value *V = C->getOperand(*EV.idx_begin());
12314 if (EV.getNumIndices() > 1)
12315 // Extract the remaining indices out of the constant indexed by the
12316 // first index
12317 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12318 else
12319 return ReplaceInstUsesWith(EV, V);
12320 }
12321 return 0; // Can't handle other constants
12322 }
12323 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12324 // We're extracting from an insertvalue instruction, compare the indices
12325 const unsigned *exti, *exte, *insi, *inse;
12326 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12327 exte = EV.idx_end(), inse = IV->idx_end();
12328 exti != exte && insi != inse;
12329 ++exti, ++insi) {
12330 if (*insi != *exti)
12331 // The insert and extract both reference distinctly different elements.
12332 // This means the extract is not influenced by the insert, and we can
12333 // replace the aggregate operand of the extract with the aggregate
12334 // operand of the insert. i.e., replace
12335 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12336 // %E = extractvalue { i32, { i32 } } %I, 0
12337 // with
12338 // %E = extractvalue { i32, { i32 } } %A, 0
12339 return ExtractValueInst::Create(IV->getAggregateOperand(),
12340 EV.idx_begin(), EV.idx_end());
12341 }
12342 if (exti == exte && insi == inse)
12343 // Both iterators are at the end: Index lists are identical. Replace
12344 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12345 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12346 // with "i32 42"
12347 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12348 if (exti == exte) {
12349 // The extract list is a prefix of the insert list. i.e. replace
12350 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12351 // %E = extractvalue { i32, { i32 } } %I, 1
12352 // with
12353 // %X = extractvalue { i32, { i32 } } %A, 1
12354 // %E = insertvalue { i32 } %X, i32 42, 0
12355 // by switching the order of the insert and extract (though the
12356 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012357 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12358 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012359 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12360 insi, inse);
12361 }
12362 if (insi == inse)
12363 // The insert list is a prefix of the extract list
12364 // We can simply remove the common indices from the extract and make it
12365 // operate on the inserted value instead of the insertvalue result.
12366 // i.e., replace
12367 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12368 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12369 // with
12370 // %E extractvalue { i32 } { i32 42 }, 0
12371 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12372 exti, exte);
12373 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012374 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12375 // We're extracting from an intrinsic, see if we're the only user, which
12376 // allows us to simplify multiple result intrinsics to simpler things that
12377 // just get one value..
12378 if (II->hasOneUse()) {
12379 // Check if we're grabbing the overflow bit or the result of a 'with
12380 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12381 // and replace it with a traditional binary instruction.
12382 switch (II->getIntrinsicID()) {
12383 case Intrinsic::uadd_with_overflow:
12384 case Intrinsic::sadd_with_overflow:
12385 if (*EV.idx_begin() == 0) { // Normal result.
12386 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12387 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12388 EraseInstFromFunction(*II);
12389 return BinaryOperator::CreateAdd(LHS, RHS);
12390 }
12391 break;
12392 case Intrinsic::usub_with_overflow:
12393 case Intrinsic::ssub_with_overflow:
12394 if (*EV.idx_begin() == 0) { // Normal result.
12395 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12396 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12397 EraseInstFromFunction(*II);
12398 return BinaryOperator::CreateSub(LHS, RHS);
12399 }
12400 break;
12401 case Intrinsic::umul_with_overflow:
12402 case Intrinsic::smul_with_overflow:
12403 if (*EV.idx_begin() == 0) { // Normal result.
12404 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12405 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12406 EraseInstFromFunction(*II);
12407 return BinaryOperator::CreateMul(LHS, RHS);
12408 }
12409 break;
12410 default:
12411 break;
12412 }
12413 }
12414 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012415 // Can't simplify extracts from other values. Note that nested extracts are
12416 // already simplified implicitely by the above (extract ( extract (insert) )
12417 // will be translated into extract ( insert ( extract ) ) first and then just
12418 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012419 return 0;
12420}
12421
Chris Lattner220b0cf2006-03-05 00:22:33 +000012422/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12423/// is to leave as a vector operation.
12424static bool CheapToScalarize(Value *V, bool isConstant) {
12425 if (isa<ConstantAggregateZero>(V))
12426 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012427 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012428 if (isConstant) return true;
12429 // If all elts are the same, we can extract.
12430 Constant *Op0 = C->getOperand(0);
12431 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12432 if (C->getOperand(i) != Op0)
12433 return false;
12434 return true;
12435 }
12436 Instruction *I = dyn_cast<Instruction>(V);
12437 if (!I) return false;
12438
12439 // Insert element gets simplified to the inserted element or is deleted if
12440 // this is constant idx extract element and its a constant idx insertelt.
12441 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12442 isa<ConstantInt>(I->getOperand(2)))
12443 return true;
12444 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12445 return true;
12446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12447 if (BO->hasOneUse() &&
12448 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12449 CheapToScalarize(BO->getOperand(1), isConstant)))
12450 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012451 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12452 if (CI->hasOneUse() &&
12453 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12454 CheapToScalarize(CI->getOperand(1), isConstant)))
12455 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012456
12457 return false;
12458}
12459
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012460/// Read and decode a shufflevector mask.
12461///
12462/// It turns undef elements into values that are larger than the number of
12463/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012464static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12465 unsigned NElts = SVI->getType()->getNumElements();
12466 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12467 return std::vector<unsigned>(NElts, 0);
12468 if (isa<UndefValue>(SVI->getOperand(2)))
12469 return std::vector<unsigned>(NElts, 2*NElts);
12470
12471 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012472 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012473 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12474 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012475 Result.push_back(NElts*2); // undef -> 8
12476 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012477 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012478 return Result;
12479}
12480
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012481/// FindScalarElement - Given a vector and an element number, see if the scalar
12482/// value is already around as a register, for example if it were inserted then
12483/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012484static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012485 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012486 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12487 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012488 unsigned Width = PTy->getNumElements();
12489 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012490 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012491
12492 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012493 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012494 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012495 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012496 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012497 return CP->getOperand(EltNo);
12498 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12499 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012500 if (!isa<ConstantInt>(III->getOperand(2)))
12501 return 0;
12502 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012503
12504 // If this is an insert to the element we are looking for, return the
12505 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012506 if (EltNo == IIElt)
12507 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012508
12509 // Otherwise, the insertelement doesn't modify the value, recurse on its
12510 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012511 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012512 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012513 unsigned LHSWidth =
12514 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012515 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012516 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012517 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012518 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012519 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012520 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012521 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012522 }
12523
12524 // Otherwise, we don't know.
12525 return 0;
12526}
12527
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012528Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012529 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012530 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012531 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012532
Dan Gohman07a96762007-07-16 14:29:03 +000012533 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012534 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012535 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012536
Reid Spencer9d6565a2007-02-15 02:26:10 +000012537 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012538 // If vector val is constant with all elements the same, replace EI with
12539 // that element. When the elements are not identical, we cannot replace yet
12540 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012541 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012542 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012543 if (C->getOperand(i) != op0) {
12544 op0 = 0;
12545 break;
12546 }
12547 if (op0)
12548 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012549 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012550
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012551 // If extracting a specified index from the vector, see if we can recursively
12552 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012553 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012554 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012555 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012556
12557 // If this is extracting an invalid index, turn this into undef, to avoid
12558 // crashing the code below.
12559 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012560 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012561
Chris Lattner867b99f2006-10-05 06:55:50 +000012562 // This instruction only demands the single element from the input vector.
12563 // If the input vector has a single use, simplify it based on this use
12564 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012565 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012566 APInt UndefElts(VectorWidth, 0);
12567 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012568 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012569 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012570 EI.setOperand(0, V);
12571 return &EI;
12572 }
12573 }
12574
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012576 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012577
12578 // If the this extractelement is directly using a bitcast from a vector of
12579 // the same number of elements, see if we can find the source element from
12580 // it. In this case, we will end up needing to bitcast the scalars.
12581 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12582 if (const VectorType *VT =
12583 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12584 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012585 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12586 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012587 return new BitCastInst(Elt, EI.getType());
12588 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012589 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012590
Chris Lattner73fa49d2006-05-25 22:53:38 +000012591 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012592 // Push extractelement into predecessor operation if legal and
12593 // profitable to do so
12594 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12595 if (I->hasOneUse() &&
12596 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12597 Value *newEI0 =
12598 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12599 EI.getName()+".lhs");
12600 Value *newEI1 =
12601 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12602 EI.getName()+".rhs");
12603 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012604 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012605 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012606 // Extracting the inserted element?
12607 if (IE->getOperand(2) == EI.getOperand(1))
12608 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12609 // If the inserted and extracted elements are constants, they must not
12610 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012611 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012612 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012613 EI.setOperand(0, IE->getOperand(0));
12614 return &EI;
12615 }
12616 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12617 // If this is extracting an element from a shufflevector, figure out where
12618 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012619 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12620 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012621 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012622 unsigned LHSWidth =
12623 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12624
12625 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012626 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012627 else if (SrcIdx < LHSWidth*2) {
12628 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012629 Src = SVI->getOperand(1);
12630 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012631 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012632 }
Eric Christophera3500da2009-07-25 02:28:41 +000012633 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012634 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12635 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012636 }
12637 }
Eli Friedman2451a642009-07-18 23:06:53 +000012638 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012639 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012640 return 0;
12641}
12642
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012643/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12644/// elements from either LHS or RHS, return the shuffle mask and true.
12645/// Otherwise, return false.
12646static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012647 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012648 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012649 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12650 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012651 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012652
12653 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012654 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012655 return true;
12656 } else if (V == LHS) {
12657 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012658 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012659 return true;
12660 } else if (V == RHS) {
12661 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012662 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012663 return true;
12664 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12665 // If this is an insert of an extract from some other vector, include it.
12666 Value *VecOp = IEI->getOperand(0);
12667 Value *ScalarOp = IEI->getOperand(1);
12668 Value *IdxOp = IEI->getOperand(2);
12669
Chris Lattnerd929f062006-04-27 21:14:21 +000012670 if (!isa<ConstantInt>(IdxOp))
12671 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012672 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012673
12674 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12675 // Okay, we can handle this if the vector we are insertinting into is
12676 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012677 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012678 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012679 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012680 return true;
12681 }
12682 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12683 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012684 EI->getOperand(0)->getType() == V->getType()) {
12685 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012686 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012687
12688 // This must be extracting from either LHS or RHS.
12689 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12690 // Okay, we can handle this if the vector we are insertinting into is
12691 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012692 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012693 // If so, update the mask to reflect the inserted value.
12694 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012695 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012696 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012697 } else {
12698 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012699 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012700 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012701
12702 }
12703 return true;
12704 }
12705 }
12706 }
12707 }
12708 }
12709 // TODO: Handle shufflevector here!
12710
12711 return false;
12712}
12713
12714/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12715/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12716/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012717static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012718 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012719 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012720 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012721 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012722 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012723
12724 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012725 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012726 return V;
12727 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012728 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012729 return V;
12730 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12731 // If this is an insert of an extract from some other vector, include it.
12732 Value *VecOp = IEI->getOperand(0);
12733 Value *ScalarOp = IEI->getOperand(1);
12734 Value *IdxOp = IEI->getOperand(2);
12735
12736 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12737 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12738 EI->getOperand(0)->getType() == V->getType()) {
12739 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012740 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12741 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012742
12743 // Either the extracted from or inserted into vector must be RHSVec,
12744 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012745 if (EI->getOperand(0) == RHS || RHS == 0) {
12746 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012747 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012748 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012749 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012750 return V;
12751 }
12752
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012753 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012754 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12755 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012756 // Everything but the extracted element is replaced with the RHS.
12757 for (unsigned i = 0; i != NumElts; ++i) {
12758 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012759 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012760 }
12761 return V;
12762 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012763
12764 // If this insertelement is a chain that comes from exactly these two
12765 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012766 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12767 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012768 return EI->getOperand(0);
12769
Chris Lattnerefb47352006-04-15 01:39:45 +000012770 }
12771 }
12772 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012773 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012774
12775 // Otherwise, can't do anything fancy. Return an identity vector.
12776 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012777 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012778 return V;
12779}
12780
12781Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12782 Value *VecOp = IE.getOperand(0);
12783 Value *ScalarOp = IE.getOperand(1);
12784 Value *IdxOp = IE.getOperand(2);
12785
Chris Lattner599ded12007-04-09 01:11:16 +000012786 // Inserting an undef or into an undefined place, remove this.
12787 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12788 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012789
Chris Lattnerefb47352006-04-15 01:39:45 +000012790 // If the inserted element was extracted from some other vector, and if the
12791 // indexes are constant, try to turn this into a shufflevector operation.
12792 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12793 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12794 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012795 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012796 unsigned ExtractedIdx =
12797 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012798 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012799
12800 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12801 return ReplaceInstUsesWith(IE, VecOp);
12802
12803 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012804 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012805
12806 // If we are extracting a value from a vector, then inserting it right
12807 // back into the same place, just use the input vector.
12808 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12809 return ReplaceInstUsesWith(IE, VecOp);
12810
Chris Lattnerefb47352006-04-15 01:39:45 +000012811 // If this insertelement isn't used by some other insertelement, turn it
12812 // (and any insertelements it points to), into one big shuffle.
12813 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12814 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012815 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012816 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012817 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012818 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012819 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012820 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012821 }
12822 }
12823 }
12824
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012825 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12826 APInt UndefElts(VWidth, 0);
12827 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12828 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12829 return &IE;
12830
Chris Lattnerefb47352006-04-15 01:39:45 +000012831 return 0;
12832}
12833
12834
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012835Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12836 Value *LHS = SVI.getOperand(0);
12837 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012838 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012839
12840 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012841
Chris Lattner867b99f2006-10-05 06:55:50 +000012842 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012843 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012844 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012845
Dan Gohman488fbfc2008-09-09 18:11:14 +000012846 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012847
12848 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12849 return 0;
12850
Evan Cheng388df622009-02-03 10:05:09 +000012851 APInt UndefElts(VWidth, 0);
12852 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12853 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012854 LHS = SVI.getOperand(0);
12855 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012856 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012857 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012858
Chris Lattner863bcff2006-05-25 23:48:38 +000012859 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12860 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12861 if (LHS == RHS || isa<UndefValue>(LHS)) {
12862 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012863 // shuffle(undef,undef,mask) -> undef.
12864 return ReplaceInstUsesWith(SVI, LHS);
12865 }
12866
Chris Lattner863bcff2006-05-25 23:48:38 +000012867 // Remap any references to RHS to use LHS.
12868 std::vector<Constant*> Elts;
12869 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012870 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012871 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012872 else {
12873 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012874 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012875 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012876 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012877 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012878 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012879 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012880 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012881 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012882 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012883 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012884 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012885 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012886 LHS = SVI.getOperand(0);
12887 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012888 MadeChange = true;
12889 }
12890
Chris Lattner7b2e27922006-05-26 00:29:06 +000012891 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012892 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012893
Chris Lattner863bcff2006-05-25 23:48:38 +000012894 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12895 if (Mask[i] >= e*2) continue; // Ignore undef values.
12896 // Is this an identity shuffle of the LHS value?
12897 isLHSID &= (Mask[i] == i);
12898
12899 // Is this an identity shuffle of the RHS value?
12900 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012901 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012902
Chris Lattner863bcff2006-05-25 23:48:38 +000012903 // Eliminate identity shuffles.
12904 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12905 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012906
Chris Lattner7b2e27922006-05-26 00:29:06 +000012907 // If the LHS is a shufflevector itself, see if we can combine it with this
12908 // one without producing an unusual shuffle. Here we are really conservative:
12909 // we are absolutely afraid of producing a shuffle mask not in the input
12910 // program, because the code gen may not be smart enough to turn a merged
12911 // shuffle into two specific shuffles: it may produce worse code. As such,
12912 // we only merge two shuffles if the result is one of the two input shuffle
12913 // masks. In this case, merging the shuffles just removes one instruction,
12914 // which we know is safe. This is good for things like turning:
12915 // (splat(splat)) -> splat.
12916 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12917 if (isa<UndefValue>(RHS)) {
12918 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12919
12920 std::vector<unsigned> NewMask;
12921 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12922 if (Mask[i] >= 2*e)
12923 NewMask.push_back(2*e);
12924 else
12925 NewMask.push_back(LHSMask[Mask[i]]);
12926
12927 // If the result mask is equal to the src shuffle or this shuffle mask, do
12928 // the replacement.
12929 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012930 unsigned LHSInNElts =
12931 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012932 std::vector<Constant*> Elts;
12933 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012934 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012935 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012936 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012937 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012938 }
12939 }
12940 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12941 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012942 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012943 }
12944 }
12945 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012946
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012947 return MadeChange ? &SVI : 0;
12948}
12949
12950
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012951
Chris Lattnerea1c4542004-12-08 23:43:58 +000012952
12953/// TryToSinkInstruction - Try to move the specified instruction from its
12954/// current block into the beginning of DestBlock, which can only happen if it's
12955/// safe to move the instruction past all of the instructions between it and the
12956/// end of its block.
12957static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12958 assert(I->hasOneUse() && "Invariants didn't hold!");
12959
Chris Lattner108e9022005-10-27 17:13:11 +000012960 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012961 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012962 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012963
Chris Lattnerea1c4542004-12-08 23:43:58 +000012964 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012965 if (isa<AllocaInst>(I) && I->getParent() ==
12966 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012967 return false;
12968
Chris Lattner96a52a62004-12-09 07:14:34 +000012969 // We can only sink load instructions if there is nothing between the load and
12970 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012971 if (I->mayReadFromMemory()) {
12972 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012973 Scan != E; ++Scan)
12974 if (Scan->mayWriteToMemory())
12975 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012976 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012977
Dan Gohman02dea8b2008-05-23 21:05:58 +000012978 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012979
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012980 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012981 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012982 ++NumSunkInst;
12983 return true;
12984}
12985
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012986
12987/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12988/// all reachable code to the worklist.
12989///
12990/// This has a couple of tricks to make the code faster and more powerful. In
12991/// particular, we constant fold and DCE instructions as we go, to avoid adding
12992/// them to the worklist (this significantly speeds up instcombine on code where
12993/// many instructions are dead or constant). Additionally, if we find a branch
12994/// whose condition is a known constant, we only visit the reachable successors.
12995///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012996static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012997 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012998 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012999 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013000 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013001 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013002 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013003
13004 std::vector<Instruction*> InstrsForInstCombineWorklist;
13005 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013006
Chris Lattner2ee743b2009-10-15 04:59:28 +000013007 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13008
Chris Lattner2c7718a2007-03-23 19:17:18 +000013009 while (!Worklist.empty()) {
13010 BB = Worklist.back();
13011 Worklist.pop_back();
13012
13013 // We have now visited this block! If we've already been here, ignore it.
13014 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013015
Chris Lattner2c7718a2007-03-23 19:17:18 +000013016 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13017 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013018
Chris Lattner2c7718a2007-03-23 19:17:18 +000013019 // DCE instruction if trivially dead.
13020 if (isInstructionTriviallyDead(Inst)) {
13021 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013022 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013023 Inst->eraseFromParent();
13024 continue;
13025 }
13026
13027 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013028 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013029 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013030 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13031 << *Inst << '\n');
13032 Inst->replaceAllUsesWith(C);
13033 ++NumConstProp;
13034 Inst->eraseFromParent();
13035 continue;
13036 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013037
13038
13039
13040 if (TD) {
13041 // See if we can constant fold its operands.
13042 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13043 i != e; ++i) {
13044 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13045 if (CE == 0) continue;
13046
13047 // If we already folded this constant, don't try again.
13048 if (!FoldedConstants.insert(CE))
13049 continue;
13050
Chris Lattner7b550cc2009-11-06 04:27:31 +000013051 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013052 if (NewC && NewC != CE) {
13053 *i = NewC;
13054 MadeIRChange = true;
13055 }
13056 }
13057 }
13058
Devang Patel7fe1dec2008-11-19 18:56:50 +000013059
Chris Lattner67f7d542009-10-12 03:58:40 +000013060 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013061 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013062
13063 // Recursively visit successors. If this is a branch or switch on a
13064 // constant, only visit the reachable successor.
13065 TerminatorInst *TI = BB->getTerminator();
13066 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13067 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13068 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013069 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013070 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013071 continue;
13072 }
13073 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13074 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13075 // See if this is an explicit destination.
13076 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13077 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013078 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013079 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013080 continue;
13081 }
13082
13083 // Otherwise it is the default destination.
13084 Worklist.push_back(SI->getSuccessor(0));
13085 continue;
13086 }
13087 }
13088
13089 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13090 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013091 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013092
13093 // Once we've found all of the instructions to add to instcombine's worklist,
13094 // add them in reverse order. This way instcombine will visit from the top
13095 // of the function down. This jives well with the way that it adds all uses
13096 // of instructions to the worklist after doing a transformation, thus avoiding
13097 // some N^2 behavior in pathological cases.
13098 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13099 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013100
13101 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013102}
13103
Chris Lattnerec9c3582007-03-03 02:04:50 +000013104bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013105 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013106
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013107 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13108 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013109
Chris Lattnerb3d59702005-07-07 20:40:38 +000013110 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013111 // Do a depth-first traversal of the function, populate the worklist with
13112 // the reachable instructions. Ignore blocks that are not reachable. Keep
13113 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013114 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013115 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013116
Chris Lattnerb3d59702005-07-07 20:40:38 +000013117 // Do a quick scan over the function. If we find any blocks that are
13118 // unreachable, remove any instructions inside of them. This prevents
13119 // the instcombine code from having to deal with some bad special cases.
13120 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13121 if (!Visited.count(BB)) {
13122 Instruction *Term = BB->getTerminator();
13123 while (Term != BB->begin()) { // Remove instrs bottom-up
13124 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013125
Chris Lattnerbdff5482009-08-23 04:37:46 +000013126 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013127 // A debug intrinsic shouldn't force another iteration if we weren't
13128 // going to do one without it.
13129 if (!isa<DbgInfoIntrinsic>(I)) {
13130 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013131 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013132 }
Devang Patel228ebd02009-10-13 22:56:32 +000013133
Devang Patel228ebd02009-10-13 22:56:32 +000013134 // If I is not void type then replaceAllUsesWith undef.
13135 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013136 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013137 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013138 I->eraseFromParent();
13139 }
13140 }
13141 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013142
Chris Lattner873ff012009-08-30 05:55:36 +000013143 while (!Worklist.isEmpty()) {
13144 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013145 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013146
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013147 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013148 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013149 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013150 EraseInstFromFunction(*I);
13151 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013152 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013153 continue;
13154 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013155
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013156 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013157 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013158 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013159 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013160
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013161 // Add operands to the worklist.
13162 ReplaceInstUsesWith(*I, C);
13163 ++NumConstProp;
13164 EraseInstFromFunction(*I);
13165 MadeIRChange = true;
13166 continue;
13167 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013168
Chris Lattnerea1c4542004-12-08 23:43:58 +000013169 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013170 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013171 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013172 Instruction *UserInst = cast<Instruction>(I->use_back());
13173 BasicBlock *UserParent;
13174
13175 // Get the block the use occurs in.
13176 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13177 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13178 else
13179 UserParent = UserInst->getParent();
13180
Chris Lattnerea1c4542004-12-08 23:43:58 +000013181 if (UserParent != BB) {
13182 bool UserIsSuccessor = false;
13183 // See if the user is one of our successors.
13184 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13185 if (*SI == UserParent) {
13186 UserIsSuccessor = true;
13187 break;
13188 }
13189
13190 // If the user is one of our immediate successors, and if that successor
13191 // only has us as a predecessors (we'd have to split the critical edge
13192 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013193 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013194 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013195 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013196 }
13197 }
13198
Chris Lattner74381062009-08-30 07:44:24 +000013199 // Now that we have an instruction, try combining it to simplify it.
13200 Builder->SetInsertPoint(I->getParent(), I);
13201
Reid Spencera9b81012007-03-26 17:44:01 +000013202#ifndef NDEBUG
13203 std::string OrigI;
13204#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013205 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013206 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13207
Chris Lattner90ac28c2002-08-02 19:29:35 +000013208 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013209 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013210 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013211 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013212 DEBUG(errs() << "IC: Old = " << *I << '\n'
13213 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013214
Chris Lattnerf523d062004-06-09 05:08:07 +000013215 // Everything uses the new instruction now.
13216 I->replaceAllUsesWith(Result);
13217
13218 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013219 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013220 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013221
Chris Lattner6934a042007-02-11 01:23:03 +000013222 // Move the name to the new instruction first.
13223 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013224
13225 // Insert the new instruction into the basic block...
13226 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013227 BasicBlock::iterator InsertPos = I;
13228
13229 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13230 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13231 ++InsertPos;
13232
13233 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013234
Chris Lattner7a1e9242009-08-30 06:13:40 +000013235 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013236 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013237#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013238 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13239 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013240#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013241
Chris Lattner90ac28c2002-08-02 19:29:35 +000013242 // If the instruction was modified, it's possible that it is now dead.
13243 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013244 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013245 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013246 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013247 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013248 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013249 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013250 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013251 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013252 }
13253 }
13254
Chris Lattner873ff012009-08-30 05:55:36 +000013255 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013256 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013257}
13258
Chris Lattnerec9c3582007-03-03 02:04:50 +000013259
13260bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013261 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013262 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013263 TD = getAnalysisIfAvailable<TargetData>();
13264
Chris Lattner74381062009-08-30 07:44:24 +000013265
13266 /// Builder - This is an IRBuilder that automatically inserts new
13267 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013268 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013269 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013270 InstCombineIRInserter(Worklist));
13271 Builder = &TheBuilder;
13272
Chris Lattnerec9c3582007-03-03 02:04:50 +000013273 bool EverMadeChange = false;
13274
13275 // Iterate while there is work to do.
13276 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013277 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013278 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013279
13280 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013281 return EverMadeChange;
13282}
13283
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013284FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013285 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013286}