blob: 609bbc04109f854e27ec40c92ff62f87045ba77b [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 Lattner3df5c6f2010-01-04 06:30:00 +000038#include "InstCombineWorklist.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000041#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000044#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000045#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000046#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000047#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000048#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000049#include "llvm/Target/TargetData.h"
50#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000053#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000054#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000055#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000056#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000058#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000059#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000060#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000061#include "llvm/Support/TargetFolder.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattnerb109b5c2009-12-21 06:03:05 +000076/// SelectPatternFlavor - We can match a variety of different patterns for
77/// select operations.
78enum SelectPatternFlavor {
79 SPF_UNKNOWN = 0,
80 SPF_SMIN, SPF_UMIN,
81 SPF_SMAX, SPF_UMAX
82 //SPF_ABS - TODO.
83};
84
Chris Lattner873ff012009-08-30 05:55:36 +000085
86namespace {
Chris Lattner74381062009-08-30 07:44:24 +000087 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
88 /// just like the normal insertion helper, but also adds any new instructions
89 /// to the instcombine worklist.
90 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
91 InstCombineWorklist &Worklist;
92 public:
93 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
94
95 void InsertHelper(Instruction *I, const Twine &Name,
96 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
97 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
98 Worklist.Add(I);
99 }
100 };
101} // end anonymous namespace
102
103
104namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000105 class InstCombiner : public FunctionPass,
106 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000107 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000108 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000109 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000111 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000112 InstCombineWorklist Worklist;
113
Chris Lattner74381062009-08-30 07:44:24 +0000114 /// Builder - This is an IRBuilder that automatically inserts new
115 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000116 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000117 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000118
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000119 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000120 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000121
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000122 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000123 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000124
125 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126
Chris Lattner97e52e42002-04-28 21:27:06 +0000127 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000128 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000129 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000130 }
131
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000132 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000133
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000134 // Visitation implementation - Implement instruction combining for different
135 // instruction types. The semantics are as follows:
136 // Return Value:
137 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000138 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000139 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000140 //
Chris Lattner7e708292002-06-25 16:13:24 +0000141 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000142 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000143 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000144 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000145 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000146 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000147 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000148 Instruction *visitURem(BinaryOperator &I);
149 Instruction *visitSRem(BinaryOperator &I);
150 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000151 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000152 Instruction *commonRemTransforms(BinaryOperator &I);
153 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000154 Instruction *commonDivTransforms(BinaryOperator &I);
155 Instruction *commonIDivTransforms(BinaryOperator &I);
156 Instruction *visitUDiv(BinaryOperator &I);
157 Instruction *visitSDiv(BinaryOperator &I);
158 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000159 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000160 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000161 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000162 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000163 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000164 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000165 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000166 Instruction *visitOr (BinaryOperator &I);
167 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000168 Instruction *visitShl(BinaryOperator &I);
169 Instruction *visitAShr(BinaryOperator &I);
170 Instruction *visitLShr(BinaryOperator &I);
171 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000172 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
173 Constant *RHSC);
Chris Lattner1f12e442010-01-02 08:12:04 +0000174 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +0000175 GlobalVariable *GV, CmpInst &ICI,
176 ConstantInt *AndCst = 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000177 Instruction *visitFCmpInst(FCmpInst &I);
178 Instruction *visitICmpInst(ICmpInst &I);
179 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000180 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
181 Instruction *LHS,
182 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000183 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
184 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000185 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000186 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000187 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000189 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000190 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000191 Instruction *commonCastTransforms(CastInst &CI);
192 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000193 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000194 Instruction *visitTrunc(TruncInst &CI);
195 Instruction *visitZExt(ZExtInst &CI);
196 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000197 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000198 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000199 Instruction *visitFPToUI(FPToUIInst &FI);
200 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *visitUIToFP(CastInst &CI);
202 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000203 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000204 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000206 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
207 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000208 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000209 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
210 Value *A, Value *B, Instruction &Outer,
211 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000212 Instruction *visitSelectInst(SelectInst &SI);
213 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000214 Instruction *visitCallInst(CallInst &CI);
215 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000216
217 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000218 Instruction *visitPHINode(PHINode &PN);
219 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000220 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000221 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000222 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000223 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000224 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000225 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000226 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000227 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000228 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000229 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000230
231 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000232 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000233
Chris Lattner9fe38862003-06-19 17:00:31 +0000234 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000235 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000237 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000238 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
239 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000240 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000241 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
242
Chris Lattner9fe38862003-06-19 17:00:31 +0000243
Chris Lattner28977af2004-04-05 01:30:19 +0000244 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000245 // InsertNewInstBefore - insert an instruction New before instruction Old
246 // in the program. Add the new instruction to the worklist.
247 //
Chris Lattner955f3312004-09-28 21:48:02 +0000248 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000249 assert(New && New->getParent() == 0 &&
250 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000251 BasicBlock *BB = Old.getParent();
252 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000253 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000254 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000255 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000256
Chris Lattner8b170942002-08-09 23:47:40 +0000257 // ReplaceInstUsesWith - This method is to be used when an instruction is
258 // found to be dead, replacable with another preexisting expression. Here
259 // we add all uses of I to the worklist, replace all uses of I with the new
260 // value, then return I, so that the inst combiner will know that I was
261 // modified.
262 //
263 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000264 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000265
266 // If we are replacing the instruction with itself, this must be in a
267 // segment of unreachable code, so just clobber the instruction.
268 if (&I == V)
269 V = UndefValue::get(I.getType());
270
271 I.replaceAllUsesWith(V);
272 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000273 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000274
275 // EraseInstFromFunction - When dealing with an instruction that has side
276 // effects or produces a void value, we can't rely on DCE to delete the
277 // instruction. Instead, visit methods should return the value returned by
278 // this function.
279 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000280 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000281
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000283 // Make sure that we reprocess all operands now that we reduced their
284 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000285 if (I.getNumOperands() < 8) {
286 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
287 if (Instruction *Op = dyn_cast<Instruction>(*i))
288 Worklist.Add(Op);
289 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000290 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000291 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000292 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293 return 0; // Don't do anything with FI
294 }
Chris Lattner173234a2008-06-02 01:18:21 +0000295
296 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
297 APInt &KnownOne, unsigned Depth = 0) const {
298 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
299 }
300
301 bool MaskedValueIsZero(Value *V, const APInt &Mask,
302 unsigned Depth = 0) const {
303 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
304 }
305 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
306 return llvm::ComputeNumSignBits(Op, TD, Depth);
307 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000308
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000309 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000310
Reid Spencere4d87aa2006-12-23 06:05:41 +0000311 /// SimplifyCommutative - This performs a few simplifications for
312 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000313 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000314
Chris Lattner886ab6c2009-01-31 08:15:18 +0000315 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
316 /// based on the demanded bits.
317 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
318 APInt& KnownZero, APInt& KnownOne,
319 unsigned Depth);
320 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000321 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000322 unsigned Depth=0);
323
324 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
325 /// SimplifyDemandedBits knows about. See if the instruction has any
326 /// properties that allow us to simplify its operands.
327 bool SimplifyDemandedInstructionBits(Instruction &Inst);
328
Evan Cheng388df622009-02-03 10:05:09 +0000329 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
330 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000331
Chris Lattner5d1704d2009-09-27 19:57:57 +0000332 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
333 // which has a PHI node as operand #0, see if we can fold the instruction
334 // into the PHI (which is only possible if all operands to the PHI are
335 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000336 //
337 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
338 // that would normally be unprofitable because they strongly encourage jump
339 // threading.
340 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000341
Chris Lattnerbac32862004-11-14 19:13:23 +0000342 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
343 // operator and they all are only used by the PHI, PHI together their
344 // inputs, and do the operation once, to the result of the PHI.
345 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000346 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000347 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000348 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000349
Chris Lattner7da52b22006-11-01 04:51:18 +0000350
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000351 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
352 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000353
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000354 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000355 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000356 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000357 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000358 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000359 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000360 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000361 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000362 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000363
Chris Lattnerafe91a52006-06-15 19:07:26 +0000364
Reid Spencerc55b2432006-12-13 18:21:21 +0000365 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000366
Dan Gohman6de29f82009-06-15 22:12:54 +0000367 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000368 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000369 unsigned GetOrEnforceKnownAlignment(Value *V,
370 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000371
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000372 };
Chris Lattner873ff012009-08-30 05:55:36 +0000373} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000374
Dan Gohman844731a2008-05-13 00:00:25 +0000375char InstCombiner::ID = 0;
376static RegisterPass<InstCombiner>
377X("instcombine", "Combine redundant instructions");
378
Chris Lattner4f98c562003-03-10 21:43:22 +0000379// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000381static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000382 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000383 if (BinaryOperator::isNeg(V) ||
384 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000385 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000386 return 3;
387 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000388 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000389 if (isa<Argument>(V)) return 3;
390 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000391}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392
Chris Lattnerc8802d22003-03-11 00:12:48 +0000393// isOnlyUse - Return true if this instruction will be deleted if we stop using
394// it.
395static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000396 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000397}
398
Chris Lattner4cb170c2004-02-23 06:38:22 +0000399// getPromotedType - Return the specified type promoted as it would be to pass
400// though a va_arg area...
401static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000402 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
403 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000404 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000405 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000406 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000407}
408
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000409/// ShouldChangeType - Return true if it is desirable to convert a computation
410/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
411/// type for example, or from a smaller to a larger illegal type.
412static bool ShouldChangeType(const Type *From, const Type *To,
413 const TargetData *TD) {
414 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
415
416 // If we don't have TD, we don't know if the source/dest are legal.
417 if (!TD) return false;
418
419 unsigned FromWidth = From->getPrimitiveSizeInBits();
420 unsigned ToWidth = To->getPrimitiveSizeInBits();
421 bool FromLegal = TD->isLegalInteger(FromWidth);
422 bool ToLegal = TD->isLegalInteger(ToWidth);
423
424 // If this is a legal integer from type, and the result would be an illegal
425 // type, don't do the transformation.
426 if (FromLegal && !ToLegal)
427 return false;
428
429 // Otherwise, if both are illegal, do not increase the size of the result. We
430 // do allow things like i160 -> i64, but not i64 -> i160.
431 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
432 return false;
433
434 return true;
435}
436
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000437/// getBitCastOperand - If the specified operand is a CastInst, a constant
438/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000440static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000441 if (Operator *O = dyn_cast<Operator>(V)) {
442 if (O->getOpcode() == Instruction::BitCast)
443 return O->getOperand(0);
444 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
445 if (GEP->hasAllZeroIndices())
446 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 }
Chris Lattnereed48272005-09-13 00:40:14 +0000448 return 0;
449}
450
Reid Spencer3da59db2006-11-27 01:05:10 +0000451/// This function is a wrapper around CastInst::isEliminableCastPair. It
452/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000453static Instruction::CastOps
454isEliminableCastPair(
455 const CastInst *CI, ///< The first cast instruction
456 unsigned opcode, ///< The opcode of the second cast instruction
457 const Type *DstTy, ///< The target type for the second cast instruction
458 TargetData *TD ///< The target data for pointer size
459) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000460
Reid Spencer3da59db2006-11-27 01:05:10 +0000461 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
462 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000463
Reid Spencer3da59db2006-11-27 01:05:10 +0000464 // Get the opcodes of the two Cast instructions
465 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
466 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000467
Chris Lattnera0e69692009-03-24 18:35:40 +0000468 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000469 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000470 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000471
472 // We don't want to form an inttoptr or ptrtoint that converts to an integer
473 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000474 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000475 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000476 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000477 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000478 Res = 0;
479
480 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000481}
482
483/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
484/// in any code being generated. It does not require codegen if V is simple
485/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000486static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
487 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (V->getType() == Ty || isa<Constant>(V)) return false;
489
Chris Lattner01575b72006-05-25 23:24:33 +0000490 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000491 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000492 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000493 return false;
494 return true;
495}
496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// SimplifyCommutative - This performs a few simplifications for commutative
498// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000499//
Chris Lattner4f98c562003-03-10 21:43:22 +0000500// 1. Order operands such that they are listed from right (least complex) to
501// left (most complex). This puts constants before unary operators before
502// binary operators.
503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
505// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000506//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000508 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000509 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000511
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 if (!I.isAssociative()) return Changed;
513 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000514 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
515 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
516 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000517 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000518 cast<Constant>(I.getOperand(1)),
519 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 I.setOperand(0, Op->getOperand(0));
521 I.setOperand(1, Folded);
522 return true;
523 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
524 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
525 isOnlyUse(Op) && isOnlyUse(Op1)) {
526 Constant *C1 = cast<Constant>(Op->getOperand(1));
527 Constant *C2 = cast<Constant>(Op1->getOperand(1));
528
529 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000530 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000531 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 Op1->getOperand(0),
533 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000534 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 I.setOperand(0, New);
536 I.setOperand(1, Folded);
537 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000538 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000539 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000541}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000542
Chris Lattner8d969642003-03-10 23:06:50 +0000543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000545//
Dan Gohman186a6362009-08-12 16:04:34 +0000546static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000547 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000548 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000549
Chris Lattner0ce85802004-12-14 20:08:06 +0000550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000552 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000556 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000557
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559}
560
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000561// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
562// instruction if the LHS is a constant negative zero (which is the 'negate'
563// form).
564//
Dan Gohman186a6362009-08-12 16:04:34 +0000565static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000566 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000567 return BinaryOperator::getFNegArgument(V);
568
569 // Constants can be considered to be negated values if they can be folded.
570 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000571 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000572
573 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
574 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000575 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000576
577 return 0;
578}
579
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000580/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
581/// returning the kind and providing the out parameter results if we
582/// successfully match.
583static SelectPatternFlavor
584MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
585 SelectInst *SI = dyn_cast<SelectInst>(V);
586 if (SI == 0) return SPF_UNKNOWN;
587
588 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
589 if (ICI == 0) return SPF_UNKNOWN;
590
591 LHS = ICI->getOperand(0);
592 RHS = ICI->getOperand(1);
593
594 // (icmp X, Y) ? X : Y
595 if (SI->getTrueValue() == ICI->getOperand(0) &&
596 SI->getFalseValue() == ICI->getOperand(1)) {
597 switch (ICI->getPredicate()) {
598 default: return SPF_UNKNOWN; // Equality.
599 case ICmpInst::ICMP_UGT:
600 case ICmpInst::ICMP_UGE: return SPF_UMAX;
601 case ICmpInst::ICMP_SGT:
602 case ICmpInst::ICMP_SGE: return SPF_SMAX;
603 case ICmpInst::ICMP_ULT:
604 case ICmpInst::ICMP_ULE: return SPF_UMIN;
605 case ICmpInst::ICMP_SLT:
606 case ICmpInst::ICMP_SLE: return SPF_SMIN;
607 }
608 }
609
610 // (icmp X, Y) ? Y : X
611 if (SI->getTrueValue() == ICI->getOperand(1) &&
612 SI->getFalseValue() == ICI->getOperand(0)) {
613 switch (ICI->getPredicate()) {
614 default: return SPF_UNKNOWN; // Equality.
615 case ICmpInst::ICMP_UGT:
616 case ICmpInst::ICMP_UGE: return SPF_UMIN;
617 case ICmpInst::ICMP_SGT:
618 case ICmpInst::ICMP_SGE: return SPF_SMIN;
619 case ICmpInst::ICMP_ULT:
620 case ICmpInst::ICMP_ULE: return SPF_UMAX;
621 case ICmpInst::ICMP_SLT:
622 case ICmpInst::ICMP_SLE: return SPF_SMAX;
623 }
624 }
625
626 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
627
628 return SPF_UNKNOWN;
629}
630
Chris Lattner48b59ec2009-10-26 15:40:07 +0000631/// isFreeToInvert - Return true if the specified value is free to invert (apply
632/// ~ to). This happens in cases where the ~ can be eliminated.
633static inline bool isFreeToInvert(Value *V) {
634 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000635 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000636 return true;
637
638 // Constants can be considered to be not'ed values.
639 if (isa<ConstantInt>(V))
640 return true;
641
642 // Compares can be inverted if they have a single use.
643 if (CmpInst *CI = dyn_cast<CmpInst>(V))
644 return CI->hasOneUse();
645
646 return false;
647}
648
649static inline Value *dyn_castNotVal(Value *V) {
650 // If this is not(not(x)) don't return that this is a not: we want the two
651 // not's to be folded first.
652 if (BinaryOperator::isNot(V)) {
653 Value *Operand = BinaryOperator::getNotArgument(V);
654 if (!isFreeToInvert(Operand))
655 return Operand;
656 }
Chris Lattner8d969642003-03-10 23:06:50 +0000657
658 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000659 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000660 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000661 return 0;
662}
663
Chris Lattner48b59ec2009-10-26 15:40:07 +0000664
665
Chris Lattnerc8802d22003-03-11 00:12:48 +0000666// dyn_castFoldableMul - If this value is a multiply that can be folded into
667// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000668// non-constant operand of the multiply, and set CST to point to the multiplier.
669// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000670//
Dan Gohman186a6362009-08-12 16:04:34 +0000671static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000672 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000673 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000674 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000675 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000676 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000677 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000678 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000679 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000680 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000681 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000682 CST = ConstantInt::get(V->getType()->getContext(),
683 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000684 return I->getOperand(0);
685 }
686 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000687 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000688}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000689
Reid Spencer7177c3a2007-03-25 05:33:51 +0000690/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000691static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000692 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000693 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000694}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000695/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000696static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000697 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000698 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000699}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000700/// MultiplyOverflows - True if the multiply can not be expressed in an int
701/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000702static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000703 uint32_t W = C1->getBitWidth();
704 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
705 if (sign) {
706 LHSExt.sext(W * 2);
707 RHSExt.sext(W * 2);
708 } else {
709 LHSExt.zext(W * 2);
710 RHSExt.zext(W * 2);
711 }
712
713 APInt MulExt = LHSExt * RHSExt;
714
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000715 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000716 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000717
718 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
719 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
720 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000721}
Chris Lattner955f3312004-09-28 21:48:02 +0000722
Reid Spencere7816b52007-03-08 01:52:58 +0000723
Chris Lattner255d8912006-02-11 09:31:47 +0000724/// ShrinkDemandedConstant - Check to see if the specified operand of the
725/// specified instruction is a constant integer. If so, check to see if there
726/// are any bits set in the constant that are not demanded. If so, shrink the
727/// constant and return true.
728static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000729 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000730 assert(I && "No instruction?");
731 assert(OpNo < I->getNumOperands() && "Operand index too large");
732
733 // If the operand is not a constant integer, nothing to do.
734 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
735 if (!OpC) return false;
736
737 // If there are no bits set that aren't demanded, nothing to do.
738 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
739 if ((~Demanded & OpC->getValue()) == 0)
740 return false;
741
742 // This instruction is producing bits that are not demanded. Shrink the RHS.
743 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000744 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000745 return true;
746}
747
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000748// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
749// set of known zero and one bits, compute the maximum and minimum values that
750// could have the specified known zero and known one bits, returning them in
751// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000752static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000753 const APInt& KnownOne,
754 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000755 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756 KnownZero.getBitWidth() == Min.getBitWidth() &&
757 KnownZero.getBitWidth() == Max.getBitWidth() &&
758 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000759 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000760
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000761 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
762 // bit if it is unknown.
763 Min = KnownOne;
764 Max = KnownOne|UnknownBits;
765
Dan Gohman1c8491e2009-04-25 17:12:48 +0000766 if (UnknownBits.isNegative()) { // Sign bit is unknown
767 Min.set(Min.getBitWidth()-1);
768 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000769 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000770}
771
772// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
773// a set of known zero and one bits, compute the maximum and minimum values that
774// could have the specified known zero and known one bits, returning them in
775// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000776static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000777 const APInt &KnownOne,
778 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000779 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
780 KnownZero.getBitWidth() == Min.getBitWidth() &&
781 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000782 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000783 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000784
785 // The minimum value is when the unknown bits are all zeros.
786 Min = KnownOne;
787 // The maximum value is when the unknown bits are all ones.
788 Max = KnownOne|UnknownBits;
789}
Chris Lattner255d8912006-02-11 09:31:47 +0000790
Chris Lattner886ab6c2009-01-31 08:15:18 +0000791/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
792/// SimplifyDemandedBits knows about. See if the instruction has any
793/// properties that allow us to simplify its operands.
794bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000795 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000796 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
797 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
798
799 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
800 KnownZero, KnownOne, 0);
801 if (V == 0) return false;
802 if (V == &Inst) return true;
803 ReplaceInstUsesWith(Inst, V);
804 return true;
805}
806
807/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
808/// specified instruction operand if possible, updating it in place. It returns
809/// true if it made any change and false otherwise.
810bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
811 APInt &KnownZero, APInt &KnownOne,
812 unsigned Depth) {
813 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
814 KnownZero, KnownOne, Depth);
815 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000816 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000817 return true;
818}
819
820
821/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
822/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000823/// that only the bits set in DemandedMask of the result of V are ever used
824/// downstream. Consequently, depending on the mask and V, it may be possible
825/// to replace V with a constant or one of its operands. In such cases, this
826/// function does the replacement and returns true. In all other cases, it
827/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000828/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000829/// to be zero in the expression. These are provided to potentially allow the
830/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
831/// the expression. KnownOne and KnownZero always follow the invariant that
832/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
833/// the bits in KnownOne and KnownZero may only be accurate for those bits set
834/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
835/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000836///
837/// This returns null if it did not change anything and it permits no
838/// simplification. This returns V itself if it did some simplification of V's
839/// operands based on the information about what bits are demanded. This returns
840/// some other non-null value if it found out that V is equal to another value
841/// in the context where the specified bits are demanded, but not for all users.
842Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
843 APInt &KnownZero, APInt &KnownOne,
844 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000845 assert(V != 0 && "Null pointer of Value???");
846 assert(Depth <= 6 && "Limit Search Depth");
847 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000848 const Type *VTy = V->getType();
849 assert((TD || !isa<PointerType>(VTy)) &&
850 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000851 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
852 (!VTy->isIntOrIntVector() ||
853 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000854 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000855 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000856 "Value *V, DemandedMask, KnownZero and KnownOne "
857 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000858 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
859 // We know all of the bits for a constant!
860 KnownOne = CI->getValue() & DemandedMask;
861 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000862 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000863 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000864 if (isa<ConstantPointerNull>(V)) {
865 // We know all of the bits for a constant!
866 KnownOne.clear();
867 KnownZero = DemandedMask;
868 return 0;
869 }
870
Chris Lattner08d2cc72009-01-31 07:26:06 +0000871 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000872 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000873 if (DemandedMask == 0) { // Not demanding any bits from V.
874 if (isa<UndefValue>(V))
875 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000876 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000877 }
878
Chris Lattner4598c942009-01-31 08:24:16 +0000879 if (Depth == 6) // Limit search depth.
880 return 0;
881
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000882 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
883 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
884
Dan Gohman1c8491e2009-04-25 17:12:48 +0000885 Instruction *I = dyn_cast<Instruction>(V);
886 if (!I) {
887 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
888 return 0; // Only analyze instructions.
889 }
890
Chris Lattner4598c942009-01-31 08:24:16 +0000891 // If there are multiple uses of this value and we aren't at the root, then
892 // we can't do any simplifications of the operands, because DemandedMask
893 // only reflects the bits demanded by *one* of the users.
894 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000895 // Despite the fact that we can't simplify this instruction in all User's
896 // context, we can at least compute the knownzero/knownone bits, and we can
897 // do simplifications that apply to *just* the one user if we know that
898 // this instruction has a simpler value in that context.
899 if (I->getOpcode() == Instruction::And) {
900 // If either the LHS or the RHS are Zero, the result is zero.
901 ComputeMaskedBits(I->getOperand(1), DemandedMask,
902 RHSKnownZero, RHSKnownOne, Depth+1);
903 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
904 LHSKnownZero, LHSKnownOne, Depth+1);
905
906 // If all of the demanded bits are known 1 on one side, return the other.
907 // These bits cannot contribute to the result of the 'and' in this
908 // context.
909 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
910 (DemandedMask & ~LHSKnownZero))
911 return I->getOperand(0);
912 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
913 (DemandedMask & ~RHSKnownZero))
914 return I->getOperand(1);
915
916 // If all of the demanded bits in the inputs are known zeros, return zero.
917 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000918 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000919
920 } else if (I->getOpcode() == Instruction::Or) {
921 // We can simplify (X|Y) -> X or Y in the user's context if we know that
922 // only bits from X or Y are demanded.
923
924 // If either the LHS or the RHS are One, the result is One.
925 ComputeMaskedBits(I->getOperand(1), DemandedMask,
926 RHSKnownZero, RHSKnownOne, Depth+1);
927 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
928 LHSKnownZero, LHSKnownOne, Depth+1);
929
930 // If all of the demanded bits are known zero on one side, return the
931 // other. These bits cannot contribute to the result of the 'or' in this
932 // context.
933 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
934 (DemandedMask & ~LHSKnownOne))
935 return I->getOperand(0);
936 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
937 (DemandedMask & ~RHSKnownOne))
938 return I->getOperand(1);
939
940 // If all of the potentially set bits on one side are known to be set on
941 // the other side, just use the 'other' side.
942 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
943 (DemandedMask & (~RHSKnownZero)))
944 return I->getOperand(0);
945 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
946 (DemandedMask & (~LHSKnownZero)))
947 return I->getOperand(1);
948 }
949
Chris Lattner4598c942009-01-31 08:24:16 +0000950 // Compute the KnownZero/KnownOne bits to simplify things downstream.
951 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
952 return 0;
953 }
954
955 // If this is the root being simplified, allow it to have multiple uses,
956 // just set the DemandedMask to all bits so that we can try to simplify the
957 // operands. This allows visitTruncInst (for example) to simplify the
958 // operand of a trunc without duplicating all the logic below.
959 if (Depth == 0 && !V->hasOneUse())
960 DemandedMask = APInt::getAllOnesValue(BitWidth);
961
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000963 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000965 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000966 case Instruction::And:
967 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
969 RHSKnownZero, RHSKnownOne, Depth+1) ||
970 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000971 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I;
973 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
974 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If all of the demanded bits are known 1 on one side, return the other.
977 // These bits cannot contribute to the result of the 'and'.
978 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
979 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000981 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
982 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // If all of the demanded bits in the inputs are known zeros, return zero.
986 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000987 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000990 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000991 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000992
993 // Output known-1 bits are only known if set in both the LHS & RHS.
994 RHSKnownOne &= LHSKnownOne;
995 // Output known-0 are known to be clear if zero in either the LHS | RHS.
996 RHSKnownZero |= LHSKnownZero;
997 break;
998 case Instruction::Or:
999 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'or'.
1010 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1011 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001013 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1014 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001016
1017 // If all of the potentially set bits on one side are known to be set on
1018 // the other side, just use the 'other' side.
1019 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1020 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1023 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025
1026 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001027 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001029
1030 // Output known-0 bits are only known if clear in both the LHS & RHS.
1031 RHSKnownZero &= LHSKnownZero;
1032 // Output known-1 are known to be set if set in either the LHS | RHS.
1033 RHSKnownOne |= LHSKnownOne;
1034 break;
1035 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1037 RHSKnownZero, RHSKnownOne, Depth+1) ||
1038 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001039 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 return I;
1041 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1042 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001043
1044 // If all of the demanded bits are known zero on one side, return the other.
1045 // These bits cannot contribute to the result of the 'xor'.
1046 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001050
1051 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1052 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1053 (RHSKnownOne & LHSKnownOne);
1054 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1055 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1056 (RHSKnownOne & LHSKnownZero);
1057
1058 // If all of the demanded bits are known to be zero on one side or the
1059 // other, turn this into an *inclusive* or.
1060 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001061 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1062 Instruction *Or =
1063 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1064 I->getName());
1065 return InsertNewInstBefore(Or, *I);
1066 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001067
1068 // If all of the demanded bits on one side are known, and all of the set
1069 // bits on that side are also known to be set on the other side, turn this
1070 // into an AND, as we know the bits will be cleared.
1071 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1072 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1073 // all known
1074 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001075 Constant *AndC = Constant::getIntegerValue(VTy,
1076 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001077 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001078 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001079 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001080 }
1081 }
1082
1083 // If the RHS is a constant, see if we can simplify it.
1084 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001085 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001087
Chris Lattnerd0883142009-10-11 22:22:13 +00001088 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1089 // are flipping are known to be set, then the xor is just resetting those
1090 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1091 // simplifying both of them.
1092 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1093 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1094 isa<ConstantInt>(I->getOperand(1)) &&
1095 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1096 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1097 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1098 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1099 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1100
1101 Constant *AndC =
1102 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1103 Instruction *NewAnd =
1104 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1105 InsertNewInstBefore(NewAnd, *I);
1106
1107 Constant *XorC =
1108 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1109 Instruction *NewXor =
1110 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1111 return InsertNewInstBefore(NewXor, *I);
1112 }
1113
1114
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 RHSKnownZero = KnownZeroOut;
1116 RHSKnownOne = KnownOneOut;
1117 break;
1118 }
1119 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1121 RHSKnownZero, RHSKnownOne, Depth+1) ||
1122 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001124 return I;
1125 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1126 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
1128 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001129 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1130 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
1133 // Only known if known in both the LHS and RHS.
1134 RHSKnownOne &= LHSKnownOne;
1135 RHSKnownZero &= LHSKnownZero;
1136 break;
1137 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001138 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001139 DemandedMask.zext(truncBf);
1140 RHSKnownZero.zext(truncBf);
1141 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 DemandedMask.trunc(BitWidth);
1146 RHSKnownZero.trunc(BitWidth);
1147 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 break;
1150 }
1151 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001152 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001154
1155 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1156 if (const VectorType *SrcVTy =
1157 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1158 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1159 // Don't touch a bitcast between vectors of different element counts.
1160 return false;
1161 } else
1162 // Don't touch a scalar-to-vector bitcast.
1163 return false;
1164 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1165 // Don't touch a vector-to-scalar bitcast.
1166 return false;
1167
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
1171 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001172 break;
1173 case Instruction::ZExt: {
1174 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001175 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
Zhou Shengd48653a2007-03-29 04:45:55 +00001177 DemandedMask.trunc(SrcBitWidth);
1178 RHSKnownZero.trunc(SrcBitWidth);
1179 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001181 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001183 DemandedMask.zext(BitWidth);
1184 RHSKnownZero.zext(BitWidth);
1185 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 break;
1190 }
1191 case Instruction::SExt: {
1192 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001193 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001196 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
Zhou Sheng01542f32007-03-29 02:26:30 +00001198 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 // If any of the sign extended bits are demanded, we know that the sign
1200 // bit is demanded.
1201 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001202 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
Zhou Shengd48653a2007-03-29 04:45:55 +00001204 InputDemandedBits.trunc(SrcBitWidth);
1205 RHSKnownZero.trunc(SrcBitWidth);
1206 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001209 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 InputDemandedBits.zext(BitWidth);
1211 RHSKnownZero.zext(BitWidth);
1212 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // If the sign bit of the input is known set or clear, then we know the
1216 // top bits of the result.
1217
1218 // If the input sign bit is known zero, or if the NewBits are not demanded
1219 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001220 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001221 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1223 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001226 }
1227 break;
1228 }
1229 case Instruction::Add: {
1230 // Figure out what the input bits are. If the top bits of the and result
1231 // are not demanded, then the add doesn't demand them from its input
1232 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001234
1235 // If there is a constant on the RHS, there are a variety of xformations
1236 // we can do.
1237 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1238 // If null, this should be simplified elsewhere. Some of the xforms here
1239 // won't work if the RHS is zero.
1240 if (RHS->isZero())
1241 break;
1242
1243 // If the top bit of the output is demanded, demand everything from the
1244 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001245 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001246
1247 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001248 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001250 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001251
1252 // If the RHS of the add has bits set that can't affect the input, reduce
1253 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001254 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001256
1257 // Avoid excess work.
1258 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1259 break;
1260
1261 // Turn it into OR if input bits are zero.
1262 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1263 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001264 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 }
1268
1269 // We can say something about the output known-zero and known-one bits,
1270 // depending on potential carries from the input constant and the
1271 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1272 // bits set and the RHS constant is 0x01001, then we know we have a known
1273 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1274
1275 // To compute this, we first compute the potential carry bits. These are
1276 // the bits which may be modified. I'm not aware of a better way to do
1277 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001278 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001279 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001280
1281 // Now that we know which bits have carries, compute the known-1/0 sets.
1282
1283 // Bits are known one if they are known zero in one operand and one in the
1284 // other, and there is no input carry.
1285 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1286 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1287
1288 // Bits are known zero if they are known zero in both operands and there
1289 // is no input carry.
1290 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1291 } else {
1292 // If the high-bits of this ADD are not demanded, then it does not demand
1293 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001294 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 // Right fill the mask of bits for this ADD to demand the most
1296 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1299 LHSKnownZero, LHSKnownOne, Depth+1) ||
1300 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001302 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 }
1304 }
1305 break;
1306 }
1307 case Instruction::Sub:
1308 // If the high-bits of this SUB are not demanded, then it does not demand
1309 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001310 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 // Right fill the mask of bits for this SUB to demand the most
1312 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001313 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001315 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1316 LHSKnownZero, LHSKnownOne, Depth+1) ||
1317 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001318 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001321 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1322 // the known zeros and ones.
1323 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 break;
1325 case Instruction::Shl:
1326 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001327 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001328 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001331 return I;
1332 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 RHSKnownZero <<= ShiftAmt;
1334 RHSKnownOne <<= ShiftAmt;
1335 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001336 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001337 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 }
1339 break;
1340 case Instruction::LShr:
1341 // For a logical shift right
1342 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001343 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344
Reid Spencer8cb68342007-03-12 17:25:59 +00001345 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001346 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 return I;
1350 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1352 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001353 if (ShiftAmt) {
1354 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001355 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001356 RHSKnownZero |= HighBits; // high bits known zero.
1357 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001358 }
1359 break;
1360 case Instruction::AShr:
1361 // If this is an arithmetic shift right and only the low-bit is set, we can
1362 // always convert this into a logical shr, even if the shift amount is
1363 // variable. The low bit of the shift cannot be an input sign bit unless
1364 // the shift amount is >= the size of the datatype, which is undefined.
1365 if (DemandedMask == 1) {
1366 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001371
1372 // If the sign bit is the only bit demanded by this ashr, then there is no
1373 // need to do it, the shift doesn't change the high bit.
1374 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001376
1377 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001378 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001379
Reid Spencer8cb68342007-03-12 17:25:59 +00001380 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001381 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001382 // If any of the "high bits" are demanded, we should set the sign bit as
1383 // demanded.
1384 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1385 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001386 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001388 return I;
1389 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001391 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001392 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1393 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1394
1395 // Handle the sign bits.
1396 APInt SignBit(APInt::getSignBit(BitWidth));
1397 // Adjust to where it is now in the mask.
1398 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1399
1400 // If the input sign bit is known to be zero, or if none of the top bits
1401 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001402 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001403 (HighBits & ~DemandedMask) == HighBits) {
1404 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001405 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001406 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001407 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1409 RHSKnownOne |= HighBits;
1410 }
1411 }
1412 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001413 case Instruction::SRem:
1414 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001415 APInt RA = Rem->getValue().abs();
1416 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001417 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001418 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001419
Nick Lewycky8e394322008-11-02 02:41:50 +00001420 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001421 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001422 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001423 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001424 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001425
1426 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1427 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001428
1429 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001430
Chris Lattner886ab6c2009-01-31 08:15:18 +00001431 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001432 }
1433 }
1434 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001435 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001436 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1437 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001438 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1439 KnownZero2, KnownOne2, Depth+1) ||
1440 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001441 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001442 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001443
Chris Lattner455e9ab2009-01-21 18:09:24 +00001444 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001445 Leaders = std::max(Leaders,
1446 KnownZero2.countLeadingOnes());
1447 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001448 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001449 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001450 case Instruction::Call:
1451 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1452 switch (II->getIntrinsicID()) {
1453 default: break;
1454 case Intrinsic::bswap: {
1455 // If the only bits demanded come from one byte of the bswap result,
1456 // just shift the input byte into position to eliminate the bswap.
1457 unsigned NLZ = DemandedMask.countLeadingZeros();
1458 unsigned NTZ = DemandedMask.countTrailingZeros();
1459
1460 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1461 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1462 // have 14 leading zeros, round to 8.
1463 NLZ &= ~7;
1464 NTZ &= ~7;
1465 // If we need exactly one byte, we can do this transformation.
1466 if (BitWidth-NLZ-NTZ == 8) {
1467 unsigned ResultBit = NTZ;
1468 unsigned InputBit = BitWidth-NTZ-8;
1469
1470 // Replace this with either a left or right shift to get the byte into
1471 // the right place.
1472 Instruction *NewVal;
1473 if (InputBit > ResultBit)
1474 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001475 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001476 else
1477 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001478 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001479 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001480 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001481 }
1482
1483 // TODO: Could compute known zero/one bits based on the input.
1484 break;
1485 }
1486 }
1487 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001488 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001489 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001490 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
1492 // If the client is only demanding bits that we know, return the known
1493 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001494 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1495 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001496 return false;
1497}
1498
Chris Lattner867b99f2006-10-05 06:55:50 +00001499
Mon P Wangaeb06d22008-11-10 04:46:22 +00001500/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001501/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001502/// actually used by the caller. This method analyzes which elements of the
1503/// operand are undef and returns that information in UndefElts.
1504///
1505/// If the information about demanded elements can be used to simplify the
1506/// operation, the operation is simplified, then the resultant value is
1507/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001508Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1509 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001511 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001512 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001513 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001514
1515 if (isa<UndefValue>(V)) {
1516 // If the entire vector is undefined, just return this info.
1517 UndefElts = EltMask;
1518 return 0;
1519 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1520 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001521 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001523
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001525 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1526 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001527 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001528
1529 std::vector<Constant*> Elts;
1530 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001531 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001533 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001534 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1535 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001536 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 } else { // Otherwise, defined.
1538 Elts.push_back(CP->getOperand(i));
1539 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001540
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001542 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 return NewCP != CP ? NewCP : 0;
1544 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001546 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001547
1548 // Check if this is identity. If so, return 0 since we are not simplifying
1549 // anything.
1550 if (DemandedElts == ((1ULL << VWidth) -1))
1551 return 0;
1552
Reid Spencer9d6565a2007-02-15 02:26:10 +00001553 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001554 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001555 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001556 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001557 for (unsigned i = 0; i != VWidth; ++i) {
1558 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1559 Elts.push_back(Elt);
1560 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001562 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001563 }
1564
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 // Limit search depth.
1566 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001567 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568
1569 // If multiple users are using the root value, procede with
1570 // simplification conservatively assuming that all elements
1571 // are needed.
1572 if (!V->hasOneUse()) {
1573 // Quit if we find multiple users of a non-root value though.
1574 // They'll be handled when it's their turn to be visited by
1575 // the main instcombine process.
1576 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001577 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001578 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001579
1580 // Conservatively assume that all elements are needed.
1581 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001582 }
1583
1584 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001585 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001586
1587 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001588 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001589 Value *TmpV;
1590 switch (I->getOpcode()) {
1591 default: break;
1592
1593 case Instruction::InsertElement: {
1594 // If this is a variable index, we don't know which element it overwrites.
1595 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001596 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 if (Idx == 0) {
1598 // Note that we can't propagate undef elt info, because we don't know
1599 // which elt is getting updated.
1600 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1601 UndefElts2, Depth+1);
1602 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1603 break;
1604 }
1605
1606 // If this is inserting an element that isn't demanded, remove this
1607 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001608 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001609 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1610 Worklist.Add(I);
1611 return I->getOperand(0);
1612 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001613
1614 // Otherwise, the element inserted overwrites whatever was there, so the
1615 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001616 APInt DemandedElts2 = DemandedElts;
1617 DemandedElts2.clear(IdxNo);
1618 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001619 UndefElts, Depth+1);
1620 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1621
1622 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001623 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 break;
1625 }
1626 case Instruction::ShuffleVector: {
1627 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001628 uint64_t LHSVWidth =
1629 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001630 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001631 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001632 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 unsigned MaskVal = Shuffle->getMaskValue(i);
1634 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001635 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001636 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001637 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001638 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001639 else
Evan Cheng388df622009-02-03 10:05:09 +00001640 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001641 }
1642 }
1643 }
1644
Nate Begeman7b254672009-02-11 22:36:25 +00001645 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001646 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001647 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001648 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1649
Nate Begeman7b254672009-02-11 22:36:25 +00001650 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001651 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1652 UndefElts3, Depth+1);
1653 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1654
1655 bool NewUndefElts = false;
1656 for (unsigned i = 0; i < VWidth; i++) {
1657 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001658 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001659 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001660 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001661 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001662 NewUndefElts = true;
1663 UndefElts.set(i);
1664 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001665 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001666 if (UndefElts3[MaskVal - LHSVWidth]) {
1667 NewUndefElts = true;
1668 UndefElts.set(i);
1669 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001670 }
1671 }
1672
1673 if (NewUndefElts) {
1674 // Add additional discovered undefs.
1675 std::vector<Constant*> Elts;
1676 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001677 if (UndefElts[i])
Chris Lattner4de84762010-01-04 07:02:48 +00001678 Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001679 else
Chris Lattner4de84762010-01-04 07:02:48 +00001680 Elts.push_back(ConstantInt::get(Type::getInt32Ty(I->getContext()),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001681 Shuffle->getMaskValue(i)));
1682 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001683 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001684 MadeChange = true;
1685 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001686 break;
1687 }
Chris Lattner69878332007-04-14 22:29:23 +00001688 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001689 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001690 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1691 if (!VTy) break;
1692 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001693 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001694 unsigned Ratio;
1695
1696 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001697 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001698 // elements as are demanded of us.
1699 Ratio = 1;
1700 InputDemandedElts = DemandedElts;
1701 } else if (VWidth > InVWidth) {
1702 // Untested so far.
1703 break;
1704
1705 // If there are more elements in the result than there are in the source,
1706 // then an input element is live if any of the corresponding output
1707 // elements are live.
1708 Ratio = VWidth/InVWidth;
1709 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001710 if (DemandedElts[OutIdx])
1711 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001712 }
1713 } else {
1714 // Untested so far.
1715 break;
1716
1717 // If there are more elements in the source than there are in the result,
1718 // then an input element is live if the corresponding output element is
1719 // live.
1720 Ratio = InVWidth/VWidth;
1721 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001722 if (DemandedElts[InIdx/Ratio])
1723 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001724 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001725
Chris Lattner69878332007-04-14 22:29:23 +00001726 // div/rem demand all inputs, because they don't want divide by zero.
1727 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1728 UndefElts2, Depth+1);
1729 if (TmpV) {
1730 I->setOperand(0, TmpV);
1731 MadeChange = true;
1732 }
1733
1734 UndefElts = UndefElts2;
1735 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001736 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001737 // If there are more elements in the result than there are in the source,
1738 // then an output element is undef if the corresponding input element is
1739 // undef.
1740 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001741 if (UndefElts2[OutIdx/Ratio])
1742 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001743 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001744 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001745 // If there are more elements in the source than there are in the result,
1746 // then a result element is undef if all of the corresponding input
1747 // elements are undef.
1748 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1749 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001750 if (!UndefElts2[InIdx]) // Not undef?
1751 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001752 }
1753 break;
1754 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 case Instruction::And:
1756 case Instruction::Or:
1757 case Instruction::Xor:
1758 case Instruction::Add:
1759 case Instruction::Sub:
1760 case Instruction::Mul:
1761 // div/rem demand all inputs, because they don't want divide by zero.
1762 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1763 UndefElts, Depth+1);
1764 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1765 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1766 UndefElts2, Depth+1);
1767 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1768
1769 // Output elements are undefined if both are undefined. Consider things
1770 // like undef&0. The result is known zero, not undef.
1771 UndefElts &= UndefElts2;
1772 break;
1773
1774 case Instruction::Call: {
1775 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1776 if (!II) break;
1777 switch (II->getIntrinsicID()) {
1778 default: break;
1779
1780 // Binary vector operations that work column-wise. A dest element is a
1781 // function of the corresponding input elements from the two inputs.
1782 case Intrinsic::x86_sse_sub_ss:
1783 case Intrinsic::x86_sse_mul_ss:
1784 case Intrinsic::x86_sse_min_ss:
1785 case Intrinsic::x86_sse_max_ss:
1786 case Intrinsic::x86_sse2_sub_sd:
1787 case Intrinsic::x86_sse2_mul_sd:
1788 case Intrinsic::x86_sse2_min_sd:
1789 case Intrinsic::x86_sse2_max_sd:
1790 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1791 UndefElts, Depth+1);
1792 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1793 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1794 UndefElts2, Depth+1);
1795 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1796
1797 // If only the low elt is demanded and this is a scalarizable intrinsic,
1798 // scalarize it now.
1799 if (DemandedElts == 1) {
1800 switch (II->getIntrinsicID()) {
1801 default: break;
1802 case Intrinsic::x86_sse_sub_ss:
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse2_sub_sd:
1805 case Intrinsic::x86_sse2_mul_sd:
1806 // TODO: Lower MIN/MAX/ABS/etc
1807 Value *LHS = II->getOperand(1);
1808 Value *RHS = II->getOperand(2);
1809 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001810 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Chris Lattner4de84762010-01-04 07:02:48 +00001811 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001812 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Chris Lattner4de84762010-01-04 07:02:48 +00001813 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U)), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001814
1815 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001816 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 case Intrinsic::x86_sse_sub_ss:
1818 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001819 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001820 II->getName()), *II);
1821 break;
1822 case Intrinsic::x86_sse_mul_ss:
1823 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001824 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001825 II->getName()), *II);
1826 break;
1827 }
1828
1829 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001830 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001831 UndefValue::get(II->getType()), TmpV,
Chris Lattner4de84762010-01-04 07:02:48 +00001832 ConstantInt::get(Type::getInt32Ty(I->getContext()), 0U, false),
1833 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001834 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001835 return New;
1836 }
1837 }
1838
1839 // Output elements are undefined if both are undefined. Consider things
1840 // like undef&0. The result is known zero, not undef.
1841 UndefElts &= UndefElts2;
1842 break;
1843 }
1844 break;
1845 }
1846 }
1847 return MadeChange ? I : 0;
1848}
1849
Dan Gohman45b4e482008-05-19 22:14:15 +00001850
Chris Lattner564a7272003-08-13 19:01:45 +00001851/// AssociativeOpt - Perform an optimization on an associative operator. This
1852/// function is designed to check a chain of associative operators for a
1853/// potential to apply a certain optimization. Since the optimization may be
1854/// applicable if the expression was reassociated, this checks the chain, then
1855/// reassociates the expression as necessary to expose the optimization
1856/// opportunity. This makes use of a special Functor, which must define
1857/// 'shouldApply' and 'apply' methods.
1858///
1859template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001860static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001861 unsigned Opcode = Root.getOpcode();
1862 Value *LHS = Root.getOperand(0);
1863
1864 // Quick check, see if the immediate LHS matches...
1865 if (F.shouldApply(LHS))
1866 return F.apply(Root);
1867
1868 // Otherwise, if the LHS is not of the same opcode as the root, return.
1869 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001870 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001871 // Should we apply this transform to the RHS?
1872 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1873
1874 // If not to the RHS, check to see if we should apply to the LHS...
1875 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1876 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1877 ShouldApply = true;
1878 }
1879
1880 // If the functor wants to apply the optimization to the RHS of LHSI,
1881 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1882 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001883 // Now all of the instructions are in the current basic block, go ahead
1884 // and perform the reassociation.
1885 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1886
1887 // First move the selected RHS to the LHS of the root...
1888 Root.setOperand(0, LHSI->getOperand(1));
1889
1890 // Make what used to be the LHS of the root be the user of the root...
1891 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001892 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001893 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001894 return 0;
1895 }
Chris Lattner65725312004-04-16 18:08:07 +00001896 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001897 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001898 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001899 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001900 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001901
1902 // Now propagate the ExtraOperand down the chain of instructions until we
1903 // get to LHSI.
1904 while (TmpLHSI != LHSI) {
1905 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001906 // Move the instruction to immediately before the chain we are
1907 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001908 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001909 ARI = NextLHSI;
1910
Chris Lattner564a7272003-08-13 19:01:45 +00001911 Value *NextOp = NextLHSI->getOperand(1);
1912 NextLHSI->setOperand(1, ExtraOperand);
1913 TmpLHSI = NextLHSI;
1914 ExtraOperand = NextOp;
1915 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001916
Chris Lattner564a7272003-08-13 19:01:45 +00001917 // Now that the instructions are reassociated, have the functor perform
1918 // the transformation...
1919 return F.apply(Root);
1920 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattner564a7272003-08-13 19:01:45 +00001922 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1923 }
1924 return 0;
1925}
1926
Dan Gohman844731a2008-05-13 00:00:25 +00001927namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001928
Nick Lewycky02d639f2008-05-23 04:34:58 +00001929// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001930struct AddRHS {
1931 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001932 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001933 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1934 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001935 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001936 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001937 }
1938};
1939
1940// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1941// iff C1&C2 == 0
1942struct AddMaskingAnd {
1943 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001944 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001945 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001946 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001947 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001948 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001949 }
1950 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001951 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001952 }
1953};
1954
Dan Gohman844731a2008-05-13 00:00:25 +00001955}
1956
Chris Lattner6e7ba452005-01-01 16:22:27 +00001957static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001958 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001959 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001960 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001961
Chris Lattner2eefe512004-04-09 19:05:30 +00001962 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001963 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1964 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001965
Chris Lattner2eefe512004-04-09 19:05:30 +00001966 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1967 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001968 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1969 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001970 }
1971
1972 Value *Op0 = SO, *Op1 = ConstOperand;
1973 if (!ConstIsRHS)
1974 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001975
Chris Lattner6e7ba452005-01-01 16:22:27 +00001976 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001977 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1978 SO->getName()+".op");
1979 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1980 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1981 SO->getName()+".cmp");
1982 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1983 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1984 SO->getName()+".cmp");
1985 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001986}
1987
1988// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1989// constant as the other operand, try to fold the binary operator into the
1990// select arguments. This also works for Cast instructions, which obviously do
1991// not have a second operand.
1992static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1993 InstCombiner *IC) {
1994 // Don't modify shared select instructions
1995 if (!SI->hasOneUse()) return 0;
1996 Value *TV = SI->getOperand(1);
1997 Value *FV = SI->getOperand(2);
1998
1999 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002000 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner4de84762010-01-04 07:02:48 +00002001 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002002
Chris Lattner6e7ba452005-01-01 16:22:27 +00002003 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2004 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2005
Gabor Greif051a9502008-04-06 20:25:17 +00002006 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2007 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002008 }
2009 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002010}
2011
Chris Lattner4e998b22004-09-29 05:07:12 +00002012
Chris Lattner5d1704d2009-09-27 19:57:57 +00002013/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2014/// has a PHI node as operand #0, see if we can fold the instruction into the
2015/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002016///
2017/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2018/// that would normally be unprofitable because they strongly encourage jump
2019/// threading.
2020Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2021 bool AllowAggressive) {
2022 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002024 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002025 if (NumPHIValues == 0 ||
2026 // We normally only transform phis with a single use, unless we're trying
2027 // hard to make jump threading happen.
2028 (!PN->hasOneUse() && !AllowAggressive))
2029 return 0;
2030
2031
Chris Lattner5d1704d2009-09-27 19:57:57 +00002032 // Check to see if all of the operands of the PHI are simple constants
2033 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002034 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2035 // bail out. We don't do arbitrary constant expressions here because moving
2036 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002037 BasicBlock *NonConstBB = 0;
2038 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002039 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2040 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002041 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002042 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002043 NonConstBB = PN->getIncomingBlock(i);
2044
2045 // If the incoming non-constant value is in I's block, we have an infinite
2046 // loop.
2047 if (NonConstBB == I.getParent())
2048 return 0;
2049 }
2050
2051 // If there is exactly one non-constant value, we can insert a copy of the
2052 // operation in that block. However, if this is a critical edge, we would be
2053 // inserting the computation one some other paths (e.g. inside a loop). Only
2054 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002055 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002056 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2057 if (!BI || !BI->isUnconditional()) return 0;
2058 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002059
2060 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002061 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002062 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002063 InsertNewInstBefore(NewPN, *PN);
2064 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002065
2066 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002067 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2068 // We only currently try to fold the condition of a select when it is a phi,
2069 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002070 Value *TrueV = SI->getTrueValue();
2071 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002072 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002073 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002074 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002075 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2076 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002077 Value *InV = 0;
2078 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002079 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002080 } else {
2081 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002082 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2083 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002084 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002085 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002086 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002087 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002088 }
2089 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002090 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002091 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002092 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002093 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002094 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002095 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002096 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002097 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002098 } else {
2099 assert(PN->getIncomingBlock(i) == NonConstBB);
2100 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002101 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002102 PN->getIncomingValue(i), C, "phitmp",
2103 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002104 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002105 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002106 CI->getPredicate(),
2107 PN->getIncomingValue(i), C, "phitmp",
2108 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002109 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002110 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002111
2112 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002113 }
2114 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002115 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002116 } else {
2117 CastInst *CI = cast<CastInst>(&I);
2118 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002119 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002120 Value *InV;
2121 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002122 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002123 } else {
2124 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002125 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002126 I.getType(), "phitmp",
2127 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002128 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002129 }
2130 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002131 }
2132 }
2133 return ReplaceInstUsesWith(I, NewPN);
2134}
2135
Chris Lattner2454a2e2008-01-29 06:52:45 +00002136
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002137/// WillNotOverflowSignedAdd - Return true if we can prove that:
2138/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2139/// This basically requires proving that the add in the original type would not
2140/// overflow to change the sign bit or have a carry out.
2141bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2142 // There are different heuristics we can use for this. Here are some simple
2143 // ones.
2144
2145 // Add has the property that adding any two 2's complement numbers can only
2146 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002147 // have at least two sign bits, we know that the addition of the two values
2148 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002149 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2150 return true;
2151
2152
2153 // If one of the operands only has one non-zero bit, and if the other operand
2154 // has a known-zero bit in a more significant place than it (not including the
2155 // sign bit) the ripple may go up to and fill the zero, but won't change the
2156 // sign. For example, (X & ~4) + 1.
2157
2158 // TODO: Implement.
2159
2160 return false;
2161}
2162
Chris Lattner2454a2e2008-01-29 06:52:45 +00002163
Chris Lattner7e708292002-06-25 16:13:24 +00002164Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002165 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002166 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002167
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002168 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2169 I.hasNoUnsignedWrap(), TD))
2170 return ReplaceInstUsesWith(I, V);
2171
2172
Chris Lattner66331a42004-04-10 22:01:55 +00002173 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002174 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002175 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002176 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002177 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002178 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002180
2181 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2182 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002183 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002184 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002185
Eli Friedman709b33d2009-07-13 22:27:52 +00002186 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002187 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Chris Lattner4de84762010-01-04 07:02:48 +00002188 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00002189 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002190 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002191
2192 if (isa<PHINode>(LHS))
2193 if (Instruction *NV = FoldOpIntoPhi(I))
2194 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002195
Chris Lattner4f637d42006-01-06 17:59:59 +00002196 ConstantInt *XorRHS = 0;
2197 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002198 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002199 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002200 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002201 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002202
Zhou Sheng4351c642007-04-02 08:20:41 +00002203 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002204 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2205 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002206 do {
2207 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002208 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2209 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2211 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002212 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002213 if (!MaskedValueIsZero(XorLHS,
2214 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002215 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002216 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002217 }
2218 }
2219 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002220 C0080Val = APIntOps::lshr(C0080Val, Size);
2221 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2222 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002223
Reid Spencer35c38852007-03-28 01:36:16 +00002224 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002225 // with funny bit widths then this switch statement should be removed. It
2226 // is just here to get the size of the "middle" type back up to something
2227 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002228 const Type *MiddleType = 0;
2229 switch (Size) {
2230 default: break;
Chris Lattner4de84762010-01-04 07:02:48 +00002231 case 32:
2232 case 16:
2233 case 8: MiddleType = IntegerType::get(I.getContext(), Size); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002234 }
2235 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002236 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002237 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002238 }
2239 }
Chris Lattner66331a42004-04-10 22:01:55 +00002240 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002241
Chris Lattner4de84762010-01-04 07:02:48 +00002242 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002243 return BinaryOperator::CreateXor(LHS, RHS);
2244
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002245 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002246 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002247 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002248 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002249
2250 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2251 if (RHSI->getOpcode() == Instruction::Sub)
2252 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2253 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2254 }
2255 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2256 if (LHSI->getOpcode() == Instruction::Sub)
2257 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2258 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2259 }
Robert Bocchino71698282004-07-27 21:02:21 +00002260 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002261
Chris Lattner5c4afb92002-05-08 22:46:53 +00002262 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002263 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002264 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002265 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002266 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002267 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002268 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002269 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002270 }
2271
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002272 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002273 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002274
2275 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002276 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002277 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002278 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002279
Misha Brukmanfd939082005-04-21 23:48:37 +00002280
Chris Lattner50af16a2004-11-13 19:50:12 +00002281 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002282 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002283 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002284 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002285
2286 // X*C1 + X*C2 --> X * (C1+C2)
2287 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002288 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002289 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002290 }
2291
2292 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002293 if (dyn_castFoldableMul(RHS, C2) == LHS)
2294 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002295
Chris Lattnere617c9e2007-01-05 02:17:46 +00002296 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002297 if (dyn_castNotVal(LHS) == RHS ||
2298 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002299 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002300
Chris Lattnerad3448c2003-02-18 19:57:07 +00002301
Chris Lattner564a7272003-08-13 19:01:45 +00002302 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002303 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2304 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002305 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002306
2307 // A+B --> A|B iff A and B have no bits set in common.
2308 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2309 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2310 APInt LHSKnownOne(IT->getBitWidth(), 0);
2311 APInt LHSKnownZero(IT->getBitWidth(), 0);
2312 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2313 if (LHSKnownZero != 0) {
2314 APInt RHSKnownOne(IT->getBitWidth(), 0);
2315 APInt RHSKnownZero(IT->getBitWidth(), 0);
2316 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2317
2318 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002319 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002320 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002321 }
2322 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002323
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002324 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002325 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002326 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002327 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2328 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002329 if (W != Y) {
2330 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002331 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002332 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002333 std::swap(W, X);
2334 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002335 std::swap(Y, Z);
2336 std::swap(W, X);
2337 }
2338 }
2339
2340 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002341 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002342 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002343 }
2344 }
2345 }
2346
Chris Lattner6b032052003-10-02 15:11:26 +00002347 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002348 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002349 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002350 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002351
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002352 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002353 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002354 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002355 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002356 if (Anded == CRHS) {
2357 // See if all bits from the first bit set in the Add RHS up are included
2358 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002359 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002360
2361 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002362 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002363
2364 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002365 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002366
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002367 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2368 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002369 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002370 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002371 }
2372 }
2373 }
2374
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002375 // Try to fold constant add into select arguments.
2376 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002378 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002379 }
2380
Chris Lattner42790482007-12-20 01:56:58 +00002381 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002382 {
2383 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002384 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002385 if (!SI) {
2386 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002387 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002388 }
Chris Lattner42790482007-12-20 01:56:58 +00002389 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002390 Value *TV = SI->getTrueValue();
2391 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002393
2394 // Can we fold the add into the argument of the select?
2395 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002396 if (match(FV, m_Zero()) &&
2397 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002398 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002399 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002400 if (match(TV, m_Zero()) &&
2401 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002402 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002403 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002404 }
2405 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002406
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002407 // Check for (add (sext x), y), see if we can merge this into an
2408 // integer add followed by a sext.
2409 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2410 // (add (sext x), cst) --> (sext (add x, cst'))
2411 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2412 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002413 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002414 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002415 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002416 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2417 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002418 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2419 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002420 return new SExtInst(NewAdd, I.getType());
2421 }
2422 }
2423
2424 // (add (sext x), (sext y)) --> (sext (add int x, y))
2425 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2426 // Only do this if x/y have the same type, if at last one of them has a
2427 // single use (so we don't increase the number of sexts), and if the
2428 // integer add will not overflow.
2429 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2430 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2431 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2432 RHSConv->getOperand(0))) {
2433 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002434 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2435 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002436 return new SExtInst(NewAdd, I.getType());
2437 }
2438 }
2439 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002440
2441 return Changed ? &I : 0;
2442}
2443
2444Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2445 bool Changed = SimplifyCommutative(I);
2446 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2447
2448 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2449 // X + 0 --> X
2450 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002451 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002452 (I.getType())->getValueAPF()))
2453 return ReplaceInstUsesWith(I, LHS);
2454 }
2455
2456 if (isa<PHINode>(LHS))
2457 if (Instruction *NV = FoldOpIntoPhi(I))
2458 return NV;
2459 }
2460
2461 // -A + B --> B - A
2462 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002463 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002464 return BinaryOperator::CreateFSub(RHS, LHSV);
2465
2466 // A + -B --> A - B
2467 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002468 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002469 return BinaryOperator::CreateFSub(LHS, V);
2470
2471 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2472 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2473 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2474 return ReplaceInstUsesWith(I, LHS);
2475
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002476 // Check for (add double (sitofp x), y), see if we can merge this into an
2477 // integer add followed by a promotion.
2478 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2479 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2480 // ... if the constant fits in the integer value. This is useful for things
2481 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2482 // requires a constant pool load, and generally allows the add to be better
2483 // instcombined.
2484 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2485 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002486 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002487 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002488 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002489 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2490 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002491 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2492 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002493 return new SIToFPInst(NewAdd, I.getType());
2494 }
2495 }
2496
2497 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2498 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2499 // Only do this if x/y have the same type, if at last one of them has a
2500 // single use (so we don't increase the number of int->fp conversions),
2501 // and if the integer add will not overflow.
2502 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2503 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2504 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2505 RHSConv->getOperand(0))) {
2506 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002507 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002508 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002509 return new SIToFPInst(NewAdd, I.getType());
2510 }
2511 }
2512 }
2513
Chris Lattner7e708292002-06-25 16:13:24 +00002514 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002515}
2516
Chris Lattner092543c2009-11-04 08:05:20 +00002517
2518/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2519/// code necessary to compute the offset from the base pointer (without adding
2520/// in the base pointer). Return the result as a signed integer of intptr size.
2521static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2522 TargetData &TD = *IC.getTargetData();
2523 gep_type_iterator GTI = gep_type_begin(GEP);
2524 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2525 Value *Result = Constant::getNullValue(IntPtrTy);
2526
2527 // Build a mask for high order bits.
2528 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2529 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2530
2531 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2532 ++i, ++GTI) {
2533 Value *Op = *i;
2534 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2535 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2536 if (OpC->isZero()) continue;
2537
2538 // Handle a struct index, which adds its field offset to the pointer.
2539 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2540 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2541
2542 Result = IC.Builder->CreateAdd(Result,
2543 ConstantInt::get(IntPtrTy, Size),
2544 GEP->getName()+".offs");
2545 continue;
2546 }
2547
2548 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2549 Constant *OC =
2550 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2551 Scale = ConstantExpr::getMul(OC, Scale);
2552 // Emit an add instruction.
2553 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2554 continue;
2555 }
2556 // Convert to correct type.
2557 if (Op->getType() != IntPtrTy)
2558 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2559 if (Size != 1) {
2560 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2561 // We'll let instcombine(mul) convert this to a shl if possible.
2562 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2563 }
2564
2565 // Emit an add instruction.
2566 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2567 }
2568 return Result;
2569}
2570
2571
2572/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2573/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2574/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2575/// be complex, and scales are involved. The above expression would also be
2576/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2577/// This later form is less amenable to optimization though, and we are allowed
2578/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2579///
2580/// If we can't emit an optimized form for this expression, this returns null.
2581///
2582static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2583 InstCombiner &IC) {
2584 TargetData &TD = *IC.getTargetData();
2585 gep_type_iterator GTI = gep_type_begin(GEP);
2586
2587 // Check to see if this gep only has a single variable index. If so, and if
2588 // any constant indices are a multiple of its scale, then we can compute this
2589 // in terms of the scale of the variable index. For example, if the GEP
2590 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2591 // because the expression will cross zero at the same point.
2592 unsigned i, e = GEP->getNumOperands();
2593 int64_t Offset = 0;
2594 for (i = 1; i != e; ++i, ++GTI) {
2595 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2596 // Compute the aggregate offset of constant indices.
2597 if (CI->isZero()) continue;
2598
2599 // Handle a struct index, which adds its field offset to the pointer.
2600 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2601 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2602 } else {
2603 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2604 Offset += Size*CI->getSExtValue();
2605 }
2606 } else {
2607 // Found our variable index.
2608 break;
2609 }
2610 }
2611
2612 // If there are no variable indices, we must have a constant offset, just
2613 // evaluate it the general way.
2614 if (i == e) return 0;
2615
2616 Value *VariableIdx = GEP->getOperand(i);
2617 // Determine the scale factor of the variable element. For example, this is
2618 // 4 if the variable index is into an array of i32.
2619 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2620
2621 // Verify that there are no other variable indices. If so, emit the hard way.
2622 for (++i, ++GTI; i != e; ++i, ++GTI) {
2623 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2624 if (!CI) return 0;
2625
2626 // Compute the aggregate offset of constant indices.
2627 if (CI->isZero()) continue;
2628
2629 // Handle a struct index, which adds its field offset to the pointer.
2630 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2631 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2632 } else {
2633 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2634 Offset += Size*CI->getSExtValue();
2635 }
2636 }
2637
2638 // Okay, we know we have a single variable index, which must be a
2639 // pointer/array/vector index. If there is no offset, life is simple, return
2640 // the index.
2641 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2642 if (Offset == 0) {
2643 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2644 // we don't need to bother extending: the extension won't affect where the
2645 // computation crosses zero.
2646 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2647 VariableIdx = new TruncInst(VariableIdx,
2648 TD.getIntPtrType(VariableIdx->getContext()),
2649 VariableIdx->getName(), &I);
2650 return VariableIdx;
2651 }
2652
2653 // Otherwise, there is an index. The computation we will do will be modulo
2654 // the pointer size, so get it.
2655 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2656
2657 Offset &= PtrSizeMask;
2658 VariableScale &= PtrSizeMask;
2659
2660 // To do this transformation, any constant index must be a multiple of the
2661 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2662 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2663 // multiple of the variable scale.
2664 int64_t NewOffs = Offset / (int64_t)VariableScale;
2665 if (Offset != NewOffs*(int64_t)VariableScale)
2666 return 0;
2667
2668 // Okay, we can do this evaluation. Start by converting the index to intptr.
2669 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2670 if (VariableIdx->getType() != IntPtrTy)
2671 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2672 true /*SExt*/,
2673 VariableIdx->getName(), &I);
2674 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2675 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2676}
2677
2678
2679/// Optimize pointer differences into the same array into a size. Consider:
2680/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2681/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2682///
2683Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2684 const Type *Ty) {
2685 assert(TD && "Must have target data info for this");
2686
2687 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2688 // this.
2689 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002690 GetElementPtrInst *GEP = 0;
2691 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002692
Chris Lattner85c1c962010-01-01 22:42:29 +00002693 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2694 // For now we require one side to be the base pointer "A" or a constant
2695 // expression derived from it.
2696 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2697 // (gep X, ...) - X
2698 if (LHSGEP->getOperand(0) == RHS) {
2699 GEP = LHSGEP;
2700 Swapped = false;
2701 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2702 // (gep X, ...) - (ce_gep X, ...)
2703 if (CE->getOpcode() == Instruction::GetElementPtr &&
2704 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2705 CstGEP = CE;
2706 GEP = LHSGEP;
2707 Swapped = false;
2708 }
2709 }
2710 }
2711
2712 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2713 // X - (gep X, ...)
2714 if (RHSGEP->getOperand(0) == LHS) {
2715 GEP = RHSGEP;
2716 Swapped = true;
2717 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2718 // (ce_gep X, ...) - (gep X, ...)
2719 if (CE->getOpcode() == Instruction::GetElementPtr &&
2720 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2721 CstGEP = CE;
2722 GEP = RHSGEP;
2723 Swapped = true;
2724 }
2725 }
2726 }
2727
2728 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002729 return 0;
2730
Chris Lattner092543c2009-11-04 08:05:20 +00002731 // Emit the offset of the GEP and an intptr_t.
2732 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002733
2734 // If we had a constant expression GEP on the other side offsetting the
2735 // pointer, subtract it from the offset we have.
2736 if (CstGEP) {
2737 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2738 Result = Builder->CreateSub(Result, CstOffset);
2739 }
2740
Chris Lattner092543c2009-11-04 08:05:20 +00002741
2742 // If we have p - gep(p, ...) then we have to negate the result.
2743 if (Swapped)
2744 Result = Builder->CreateNeg(Result, "diff.neg");
2745
2746 return Builder->CreateIntCast(Result, Ty, true);
2747}
2748
2749
Chris Lattner7e708292002-06-25 16:13:24 +00002750Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002752
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002753 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002754 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002755
Chris Lattner3bf68152009-12-21 04:04:05 +00002756 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2757 if (Value *V = dyn_castNegVal(Op1)) {
2758 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2759 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2760 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2761 return Res;
2762 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002763
Chris Lattnere87597f2004-10-16 18:11:37 +00002764 if (isa<UndefValue>(Op0))
2765 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2766 if (isa<UndefValue>(Op1))
2767 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner4de84762010-01-04 07:02:48 +00002768 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattner092543c2009-11-04 08:05:20 +00002769 return BinaryOperator::CreateXor(Op0, Op1);
2770
Chris Lattnerd65460f2003-11-05 01:06:05 +00002771 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002772 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002773 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002774 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002775
Chris Lattnerd65460f2003-11-05 01:06:05 +00002776 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002777 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002778 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002779 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002780
Chris Lattner76b7a062007-01-15 07:02:54 +00002781 // -(X >>u 31) -> (X >>s 31)
2782 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002783 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002784 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002785 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002786 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002787 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002788 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002789 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002790 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002791 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002792 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002793 }
2794 }
Chris Lattner092543c2009-11-04 08:05:20 +00002795 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002796 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2797 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002798 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002799 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002800 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002802 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002803 }
2804 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002805 }
2806 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002807 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002808
2809 // Try to fold constant sub into select arguments.
2810 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002811 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002812 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002813
2814 // C - zext(bool) -> bool ? C - 1 : C
2815 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattner4de84762010-01-04 07:02:48 +00002816 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
Dan Gohman186a6362009-08-12 16:04:34 +00002817 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002818 }
2819
Chris Lattner43d84d62005-04-07 16:15:25 +00002820 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002821 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002822 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002823 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002824 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002825 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002826 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002827 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002828 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2829 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2830 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002831 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002832 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002833 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002834 }
2835
Chris Lattnerfd059242003-10-15 16:48:29 +00002836 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002837 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2838 // is not used by anyone else...
2839 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002840 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002841 // Swap the two operands of the subexpr...
2842 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2843 Op1I->setOperand(0, IIOp1);
2844 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002845
Chris Lattnera2881962003-02-18 19:28:33 +00002846 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002847 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002848 }
2849
2850 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2851 //
2852 if (Op1I->getOpcode() == Instruction::And &&
2853 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2854 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2855
Chris Lattner74381062009-08-30 07:44:24 +00002856 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002857 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002858 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002859
Reid Spencerac5209e2006-10-16 23:08:08 +00002860 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002861 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002862 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002863 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002864 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002865 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002866 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002867
Chris Lattnerad3448c2003-02-18 19:57:07 +00002868 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002869 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002870 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002871 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002872 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002873 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002874 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002875 }
Chris Lattner40371712002-05-09 01:29:19 +00002876 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002877 }
Chris Lattnera2881962003-02-18 19:28:33 +00002878
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002879 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2880 if (Op0I->getOpcode() == Instruction::Add) {
2881 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2882 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2883 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2884 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2885 } else if (Op0I->getOpcode() == Instruction::Sub) {
2886 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002887 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002888 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002889 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002890 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002891
Chris Lattner50af16a2004-11-13 19:50:12 +00002892 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002893 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002894 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002895 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002896
Chris Lattner50af16a2004-11-13 19:50:12 +00002897 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002898 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002899 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002900 }
Chris Lattner092543c2009-11-04 08:05:20 +00002901
2902 // Optimize pointer differences into the same array into a size. Consider:
2903 // &A[10] - &A[0]: we should compile this to "10".
2904 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002905 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002906 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2907 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002908 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2909 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002910
2911 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002912 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2913 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2914 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2915 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002916 }
2917
Chris Lattner3f5b8772002-05-06 16:14:14 +00002918 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002919}
2920
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002921Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923
2924 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002925 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 return BinaryOperator::CreateFAdd(Op0, V);
2927
2928 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2929 if (Op1I->getOpcode() == Instruction::FAdd) {
2930 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002931 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002932 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002933 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002934 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002935 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002936 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002937 }
2938
2939 return 0;
2940}
2941
Chris Lattnera0141b92007-07-15 20:42:37 +00002942/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2943/// comparison only checks the sign bit. If it only checks the sign bit, set
2944/// TrueIfSigned if the result of the comparison is true when the input value is
2945/// signed.
2946static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2947 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002948 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002949 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2950 TrueIfSigned = true;
2951 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002952 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2953 TrueIfSigned = true;
2954 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002955 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2956 TrueIfSigned = false;
2957 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002958 case ICmpInst::ICMP_UGT:
2959 // True if LHS u> RHS and RHS == high-bit-mask - 1
2960 TrueIfSigned = true;
2961 return RHS->getValue() ==
2962 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2963 case ICmpInst::ICMP_UGE:
2964 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2965 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002966 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002967 default:
2968 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002969 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002970}
2971
Chris Lattner7e708292002-06-25 16:13:24 +00002972Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002973 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002975
Chris Lattnera2498472009-10-11 21:36:10 +00002976 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002978
Chris Lattner8af304a2009-10-11 07:53:15 +00002979 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002980 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2981 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002982
2983 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002984 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002985 if (SI->getOpcode() == Instruction::Shl)
2986 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002987 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002988 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002989
Zhou Sheng843f07672007-04-19 05:39:12 +00002990 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002991 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002992 if (CI->equalsInt(1)) // X * 1 == X
2993 return ReplaceInstUsesWith(I, Op0);
2994 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002995 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002996
Zhou Sheng97b52c22007-03-29 01:57:21 +00002997 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002998 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002999 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003000 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003001 }
Chris Lattnera2498472009-10-11 21:36:10 +00003002 } else if (isa<VectorType>(Op1C->getType())) {
3003 if (Op1C->isNullValue())
3004 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003005
Chris Lattnera2498472009-10-11 21:36:10 +00003006 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003007 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003008 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003009
3010 // As above, vector X*splat(1.0) -> X in all defined cases.
3011 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003012 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3013 if (CI->equalsInt(1))
3014 return ReplaceInstUsesWith(I, Op0);
3015 }
3016 }
Chris Lattnera2881962003-02-18 19:28:33 +00003017 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003018
3019 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3020 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003021 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003022 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003023 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3024 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003025 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003026
3027 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003028
3029 // Try to fold constant mul into select arguments.
3030 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003031 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003032 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003033
3034 if (isa<PHINode>(Op0))
3035 if (Instruction *NV = FoldOpIntoPhi(I))
3036 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003037 }
3038
Dan Gohman186a6362009-08-12 16:04:34 +00003039 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003040 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003041 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003042
Nick Lewycky0c730792008-11-21 07:33:58 +00003043 // (X / Y) * Y = X - (X % Y)
3044 // (X / Y) * -Y = (X % Y) - X
3045 {
Chris Lattnera2498472009-10-11 21:36:10 +00003046 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003047 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3048 if (!BO ||
3049 (BO->getOpcode() != Instruction::UDiv &&
3050 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003051 Op1C = Op0;
3052 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003053 }
Chris Lattnera2498472009-10-11 21:36:10 +00003054 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003055 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003056 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003057 (BO->getOpcode() == Instruction::UDiv ||
3058 BO->getOpcode() == Instruction::SDiv)) {
3059 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3060
Dan Gohmanfa94b942009-08-12 16:33:09 +00003061 // If the division is exact, X % Y is zero.
3062 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3063 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003064 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003065 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003066 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003067 }
3068
Chris Lattner74381062009-08-30 07:44:24 +00003069 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003070 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003071 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003072 else
Chris Lattner74381062009-08-30 07:44:24 +00003073 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003074 Rem->takeName(BO);
3075
Chris Lattnera2498472009-10-11 21:36:10 +00003076 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003077 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003078 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003079 }
3080 }
3081
Chris Lattner8af304a2009-10-11 07:53:15 +00003082 /// i1 mul -> i1 and.
Chris Lattner4de84762010-01-04 07:02:48 +00003083 if (I.getType() == Type::getInt1Ty(I.getContext()))
Chris Lattnera2498472009-10-11 21:36:10 +00003084 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003085
Chris Lattner8af304a2009-10-11 07:53:15 +00003086 // X*(1 << Y) --> X << Y
3087 // (1 << Y)*X --> X << Y
3088 {
3089 Value *Y;
3090 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003091 return BinaryOperator::CreateShl(Op1, Y);
3092 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003093 return BinaryOperator::CreateShl(Op0, Y);
3094 }
3095
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003096 // If one of the operands of the multiply is a cast from a boolean value, then
3097 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003098 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3099 if (!isa<VectorType>(I.getType())) {
3100 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003101 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003102
Chris Lattnerd2c58362009-10-11 21:29:45 +00003103 Value *BoolCast = 0, *OtherOp = 0;
3104 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003105 BoolCast = Op0, OtherOp = Op1;
3106 else if (MaskedValueIsZero(Op1, Negative2))
3107 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003108
Chris Lattner0036e3a2009-10-11 21:22:21 +00003109 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003110 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3111 BoolCast, "tmp");
3112 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003113 }
3114 }
3115
Chris Lattner7e708292002-06-25 16:13:24 +00003116 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003117}
3118
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003119Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3120 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003122
3123 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003124 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3125 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003126 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3127 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3128 if (Op1F->isExactlyValue(1.0))
3129 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003130 } else if (isa<VectorType>(Op1C->getType())) {
3131 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003132 // As above, vector X*splat(1.0) -> X in all defined cases.
3133 if (Constant *Splat = Op1V->getSplatValue()) {
3134 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3135 if (F->isExactlyValue(1.0))
3136 return ReplaceInstUsesWith(I, Op0);
3137 }
3138 }
3139 }
3140
3141 // Try to fold constant mul into select arguments.
3142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3144 return R;
3145
3146 if (isa<PHINode>(Op0))
3147 if (Instruction *NV = FoldOpIntoPhi(I))
3148 return NV;
3149 }
3150
Dan Gohman186a6362009-08-12 16:04:34 +00003151 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003152 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003153 return BinaryOperator::CreateFMul(Op0v, Op1v);
3154
3155 return Changed ? &I : 0;
3156}
3157
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003158/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3159/// instruction.
3160bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3161 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3162
3163 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3164 int NonNullOperand = -1;
3165 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3166 if (ST->isNullValue())
3167 NonNullOperand = 2;
3168 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3169 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3170 if (ST->isNullValue())
3171 NonNullOperand = 1;
3172
3173 if (NonNullOperand == -1)
3174 return false;
3175
3176 Value *SelectCond = SI->getOperand(0);
3177
3178 // Change the div/rem to use 'Y' instead of the select.
3179 I.setOperand(1, SI->getOperand(NonNullOperand));
3180
3181 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3182 // problem. However, the select, or the condition of the select may have
3183 // multiple uses. Based on our knowledge that the operand must be non-zero,
3184 // propagate the known value for the select into other uses of it, and
3185 // propagate a known value of the condition into its other users.
3186
3187 // If the select and condition only have a single use, don't bother with this,
3188 // early exit.
3189 if (SI->use_empty() && SelectCond->hasOneUse())
3190 return true;
3191
3192 // Scan the current block backward, looking for other uses of SI.
3193 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3194
3195 while (BBI != BBFront) {
3196 --BBI;
3197 // If we found a call to a function, we can't assume it will return, so
3198 // information from below it cannot be propagated above it.
3199 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3200 break;
3201
3202 // Replace uses of the select or its condition with the known values.
3203 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3204 I != E; ++I) {
3205 if (*I == SI) {
3206 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003207 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003208 } else if (*I == SelectCond) {
Chris Lattner4de84762010-01-04 07:02:48 +00003209 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
3210 ConstantInt::getFalse(BBI->getContext());
Chris Lattner7a1e9242009-08-30 06:13:40 +00003211 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003212 }
3213 }
3214
3215 // If we past the instruction, quit looking for it.
3216 if (&*BBI == SI)
3217 SI = 0;
3218 if (&*BBI == SelectCond)
3219 SelectCond = 0;
3220
3221 // If we ran out of things to eliminate, break out of the loop.
3222 if (SelectCond == 0 && SI == 0)
3223 break;
3224
3225 }
3226 return true;
3227}
3228
3229
Reid Spencer1628cec2006-10-26 06:15:43 +00003230/// This function implements the transforms on div instructions that work
3231/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3232/// used by the visitors to those instructions.
3233/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003234Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003236
Chris Lattner50b2ca42008-02-19 06:12:18 +00003237 // undef / X -> 0 for integer.
3238 // undef / X -> undef for FP (the undef could be a snan).
3239 if (isa<UndefValue>(Op0)) {
3240 if (Op0->getType()->isFPOrFPVector())
3241 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003243 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003244
3245 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003246 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003247 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003248
Reid Spencer1628cec2006-10-26 06:15:43 +00003249 return 0;
3250}
Misha Brukmanfd939082005-04-21 23:48:37 +00003251
Reid Spencer1628cec2006-10-26 06:15:43 +00003252/// This function implements the transforms common to both integer division
3253/// instructions (udiv and sdiv). It is called by the visitors to those integer
3254/// division instructions.
3255/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003256Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3258
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003259 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003260 if (Op0 == Op1) {
3261 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003262 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003263 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003264 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003265 }
3266
Owen Andersoneed707b2009-07-24 23:12:02 +00003267 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003268 return ReplaceInstUsesWith(I, CI);
3269 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003270
Reid Spencer1628cec2006-10-26 06:15:43 +00003271 if (Instruction *Common = commonDivTransforms(I))
3272 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003273
3274 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3275 // This does not apply for fdiv.
3276 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3277 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003278
3279 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3280 // div X, 1 == X
3281 if (RHS->equalsInt(1))
3282 return ReplaceInstUsesWith(I, Op0);
3283
3284 // (X / C1) / C2 -> X / (C1*C2)
3285 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3286 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3287 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003288 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003289 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003291 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003292 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003293 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003294 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003295
Reid Spencerbca0e382007-03-23 20:05:17 +00003296 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003297 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3298 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3299 return R;
3300 if (isa<PHINode>(Op0))
3301 if (Instruction *NV = FoldOpIntoPhi(I))
3302 return NV;
3303 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003304 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003305
Chris Lattnera2881962003-02-18 19:28:33 +00003306 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003307 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003308 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003309 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003310
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003311 // It can't be division by zero, hence it must be division by one.
Chris Lattner4de84762010-01-04 07:02:48 +00003312 if (I.getType() == Type::getInt1Ty(I.getContext()))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003313 return ReplaceInstUsesWith(I, Op0);
3314
Nick Lewycky895f0852008-11-27 20:21:08 +00003315 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3316 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3317 // div X, 1 == X
3318 if (X->isOne())
3319 return ReplaceInstUsesWith(I, Op0);
3320 }
3321
Reid Spencer1628cec2006-10-26 06:15:43 +00003322 return 0;
3323}
3324
3325Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3326 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3327
3328 // Handle the integer div common cases
3329 if (Instruction *Common = commonIDivTransforms(I))
3330 return Common;
3331
Reid Spencer1628cec2006-10-26 06:15:43 +00003332 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003333 // X udiv C^2 -> X >> C
3334 // Check to see if this is an unsigned division with an exact power of 2,
3335 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003336 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003337 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003338 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003339
3340 // X udiv C, where C >= signbit
3341 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003342 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003343 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003344 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003345 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003346 }
3347
3348 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003349 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003350 if (RHSI->getOpcode() == Instruction::Shl &&
3351 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003352 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003353 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003354 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003355 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003356 if (uint32_t C2 = C1.logBase2())
3357 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003358 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003359 }
3360 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003361 }
3362
Reid Spencer1628cec2006-10-26 06:15:43 +00003363 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3364 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003365 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003366 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003367 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003368 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003369 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003370 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003371 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003373 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003374 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003375
3376 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003377 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003378 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003379
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003380 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003381 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003382 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003383 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003384 return 0;
3385}
3386
Reid Spencer1628cec2006-10-26 06:15:43 +00003387Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3388 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3389
3390 // Handle the integer div common cases
3391 if (Instruction *Common = commonIDivTransforms(I))
3392 return Common;
3393
3394 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3395 // sdiv X, -1 == -X
3396 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003397 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003398
Dan Gohmanfa94b942009-08-12 16:33:09 +00003399 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003400 if (cast<SDivOperator>(&I)->isExact() &&
3401 RHS->getValue().isNonNegative() &&
3402 RHS->getValue().isPowerOf2()) {
3403 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3404 RHS->getValue().exactLogBase2());
3405 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3406 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003407
3408 // -X/C --> X/-C provided the negation doesn't overflow.
3409 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3410 if (isa<Constant>(Sub->getOperand(0)) &&
3411 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003412 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003413 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3414 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003415 }
3416
3417 // If the sign bits of both operands are zero (i.e. we can prove they are
3418 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003419 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003420 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003421 if (MaskedValueIsZero(Op0, Mask)) {
3422 if (MaskedValueIsZero(Op1, Mask)) {
3423 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3424 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3425 }
3426 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003427 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003428 ShiftedInt->getValue().isPowerOf2()) {
3429 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3430 // Safe because the only negative value (1 << Y) can take on is
3431 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3432 // the sign bit set.
3433 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3434 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003435 }
Eli Friedman8be17392009-07-18 09:53:21 +00003436 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003437
3438 return 0;
3439}
3440
3441Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3442 return commonDivTransforms(I);
3443}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003444
Reid Spencer0a783f72006-11-02 01:53:59 +00003445/// This function implements the transforms on rem instructions that work
3446/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3447/// is used by the visitors to those instructions.
3448/// @brief Transforms common to all three rem instructions
3449Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003451
Chris Lattner50b2ca42008-02-19 06:12:18 +00003452 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3453 if (I.getType()->isFPOrFPVector())
3454 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003456 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003457 if (isa<UndefValue>(Op1))
3458 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003459
3460 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003461 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3462 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003463
Reid Spencer0a783f72006-11-02 01:53:59 +00003464 return 0;
3465}
3466
3467/// This function implements the transforms common to both integer remainder
3468/// instructions (urem and srem). It is called by the visitors to those integer
3469/// remainder instructions.
3470/// @brief Common integer remainder transforms
3471Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3473
3474 if (Instruction *common = commonRemTransforms(I))
3475 return common;
3476
Dale Johannesened6af242009-01-21 00:35:19 +00003477 // 0 % X == 0 for integer, we don't need to preserve faults!
3478 if (Constant *LHS = dyn_cast<Constant>(Op0))
3479 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003480 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003481
Chris Lattner857e8cd2004-12-12 21:48:58 +00003482 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003483 // X % 0 == undef, we don't need to preserve faults!
3484 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003485 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003486
Chris Lattnera2881962003-02-18 19:28:33 +00003487 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003488 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003489
Chris Lattner97943922006-02-28 05:49:21 +00003490 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3493 return R;
3494 } else if (isa<PHINode>(Op0I)) {
3495 if (Instruction *NV = FoldOpIntoPhi(I))
3496 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003497 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003498
3499 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003500 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003501 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003502 }
Chris Lattnera2881962003-02-18 19:28:33 +00003503 }
3504
Reid Spencer0a783f72006-11-02 01:53:59 +00003505 return 0;
3506}
3507
3508Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3510
3511 if (Instruction *common = commonIRemTransforms(I))
3512 return common;
3513
3514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3515 // X urem C^2 -> X and C
3516 // Check to see if this is an unsigned remainder with an exact power of 2,
3517 // if so, convert to a bitwise and.
3518 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003519 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003520 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003521 }
3522
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003523 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003524 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3525 if (RHSI->getOpcode() == Instruction::Shl &&
3526 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003527 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003528 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003529 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003531 }
3532 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003533 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003534
Reid Spencer0a783f72006-11-02 01:53:59 +00003535 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3536 // where C1&C2 are powers of two.
3537 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3538 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3539 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3540 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003541 if ((STO->getValue().isPowerOf2()) &&
3542 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003543 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3544 SI->getName()+".t");
3545 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3546 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003547 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003548 }
3549 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003550 }
3551
Chris Lattner3f5b8772002-05-06 16:14:14 +00003552 return 0;
3553}
3554
Reid Spencer0a783f72006-11-02 01:53:59 +00003555Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3557
Dan Gohmancff55092007-11-05 23:16:33 +00003558 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003559 if (Instruction *Common = commonIRemTransforms(I))
3560 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003561
Dan Gohman186a6362009-08-12 16:04:34 +00003562 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003563 if (!isa<Constant>(RHSNeg) ||
3564 (isa<ConstantInt>(RHSNeg) &&
3565 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003566 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003567 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003568 I.setOperand(1, RHSNeg);
3569 return &I;
3570 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003571
Dan Gohmancff55092007-11-05 23:16:33 +00003572 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003573 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003574 if (I.getType()->isInteger()) {
3575 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3576 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3577 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003578 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003579 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003580 }
3581
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003582 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003583 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3584 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003585
Nick Lewycky9dce8732008-12-20 16:48:00 +00003586 bool hasNegative = false;
3587 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3589 if (RHS->getValue().isNegative())
3590 hasNegative = true;
3591
3592 if (hasNegative) {
3593 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003594 for (unsigned i = 0; i != VWidth; ++i) {
3595 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3596 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003597 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003598 else
3599 Elts[i] = RHS;
3600 }
3601 }
3602
Owen Andersonaf7ec972009-07-28 21:19:26 +00003603 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003604 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003605 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003606 I.setOperand(1, NewRHSV);
3607 return &I;
3608 }
3609 }
3610 }
3611
Reid Spencer0a783f72006-11-02 01:53:59 +00003612 return 0;
3613}
3614
3615Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003616 return commonRemTransforms(I);
3617}
3618
Chris Lattner457dd822004-06-09 07:59:58 +00003619// isOneBitSet - Return true if there is exactly one bit set in the specified
3620// constant.
3621static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003622 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003623}
3624
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003625// isHighOnes - Return true if the constant is of the form 1+0+.
3626// This is the same as lowones(~X).
3627static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003628 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003629}
3630
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003632/// are carefully arranged to allow folding of expressions such as:
3633///
3634/// (A < B) | (A > B) --> (A != B)
3635///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636/// Note that this is only valid if the first and second predicates have the
3637/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003638///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639/// Three bits are used to represent the condition, as follows:
3640/// 0 A > B
3641/// 1 A == B
3642/// 2 A < B
3643///
3644/// <=> Value Definition
3645/// 000 0 Always false
3646/// 001 1 A > B
3647/// 010 2 A == B
3648/// 011 3 A >= B
3649/// 100 4 A < B
3650/// 101 5 A != B
3651/// 110 6 A <= B
3652/// 111 7 Always true
3653///
3654static unsigned getICmpCode(const ICmpInst *ICI) {
3655 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003656 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 case ICmpInst::ICMP_UGT: return 1; // 001
3658 case ICmpInst::ICMP_SGT: return 1; // 001
3659 case ICmpInst::ICMP_EQ: return 2; // 010
3660 case ICmpInst::ICMP_UGE: return 3; // 011
3661 case ICmpInst::ICMP_SGE: return 3; // 011
3662 case ICmpInst::ICMP_ULT: return 4; // 100
3663 case ICmpInst::ICMP_SLT: return 4; // 100
3664 case ICmpInst::ICMP_NE: return 5; // 101
3665 case ICmpInst::ICMP_ULE: return 6; // 110
3666 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003667 // True -> 7
3668 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003669 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003670 return 0;
3671 }
3672}
3673
Evan Cheng8db90722008-10-14 17:15:11 +00003674/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3675/// predicate into a three bit mask. It also returns whether it is an ordered
3676/// predicate by reference.
3677static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3678 isOrdered = false;
3679 switch (CC) {
3680 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3681 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003682 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3683 case FCmpInst::FCMP_UGT: return 1; // 001
3684 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3685 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003686 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3687 case FCmpInst::FCMP_UGE: return 3; // 011
3688 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3689 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003690 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3691 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003692 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3693 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003694 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003695 default:
3696 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003697 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003698 return 0;
3699 }
3700}
3701
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702/// getICmpValue - This is the complement of getICmpCode, which turns an
3703/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003704/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003705/// of predicate to use in the new icmp instruction.
Chris Lattner4de84762010-01-04 07:02:48 +00003706static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003708 default: llvm_unreachable("Illegal ICmp code!");
Chris Lattner4de84762010-01-04 07:02:48 +00003709 case 0: return ConstantInt::getFalse(LHS->getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003710 case 1:
3711 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003712 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003713 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003714 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3715 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716 case 3:
3717 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003718 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003719 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003720 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003721 case 4:
3722 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003723 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003725 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3726 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 case 6:
3728 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003731 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00003732 case 7: return ConstantInt::getTrue(LHS->getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003733 }
3734}
3735
Evan Cheng8db90722008-10-14 17:15:11 +00003736/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3737/// opcode and two operands into either a FCmp instruction. isordered is passed
3738/// in to determine which kind of predicate to use in the new fcmp instruction.
3739static Value *getFCmpValue(bool isordered, unsigned code,
Chris Lattner4de84762010-01-04 07:02:48 +00003740 Value *LHS, Value *RHS) {
Evan Cheng8db90722008-10-14 17:15:11 +00003741 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003742 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003743 case 0:
3744 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003746 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003748 case 1:
3749 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003751 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003752 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003753 case 2:
3754 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003755 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003756 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003757 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003758 case 3:
3759 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003760 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003761 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003762 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003763 case 4:
3764 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003765 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003766 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003767 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003768 case 5:
3769 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003770 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003771 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003772 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003773 case 6:
3774 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003775 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003776 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003777 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Chris Lattner4de84762010-01-04 07:02:48 +00003778 case 7: return ConstantInt::getTrue(LHS->getContext());
Evan Cheng8db90722008-10-14 17:15:11 +00003779 }
3780}
3781
Chris Lattnerb9553d62008-11-16 04:55:20 +00003782/// PredicatesFoldable - Return true if both predicates match sign or if at
3783/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003784static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003785 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3786 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3787 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788}
3789
3790namespace {
3791// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3792struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003793 InstCombiner &IC;
3794 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 ICmpInst::Predicate pred;
3796 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3797 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3798 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003799 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003800 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3801 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003802 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3803 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003804 return false;
3805 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003806 Instruction *apply(Instruction &Log) const {
3807 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3808 if (ICI->getOperand(0) != LHS) {
3809 assert(ICI->getOperand(1) == LHS);
3810 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003811 }
3812
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003813 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003815 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003816 unsigned Code;
3817 switch (Log.getOpcode()) {
3818 case Instruction::And: Code = LHSCode & RHSCode; break;
3819 case Instruction::Or: Code = LHSCode | RHSCode; break;
3820 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003821 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003822 }
3823
Nick Lewycky4a134af2009-10-25 05:20:17 +00003824 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Chris Lattner4de84762010-01-04 07:02:48 +00003825 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003826 if (Instruction *I = dyn_cast<Instruction>(RV))
3827 return I;
3828 // Otherwise, it's a constant boolean value...
3829 return IC.ReplaceInstUsesWith(Log, RV);
3830 }
3831};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003832} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003833
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003834// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3835// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003836// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003837Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003838 ConstantInt *OpRHS,
3839 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003840 BinaryOperator &TheAnd) {
3841 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003842 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003843 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003844 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003845
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003846 switch (Op->getOpcode()) {
3847 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003848 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003849 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003850 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003851 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003852 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003853 }
3854 break;
3855 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003856 if (Together == AndRHS) // (X | C) & C --> C
3857 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003858
Chris Lattner6e7ba452005-01-01 16:22:27 +00003859 if (Op->hasOneUse() && Together != OpRHS) {
3860 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003861 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003862 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003863 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003864 }
3865 break;
3866 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003867 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003868 // Adding a one to a single bit bit-field should be turned into an XOR
3869 // of the bit. First thing to check is to see if this AND is with a
3870 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003871 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003872
3873 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003874 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003875 // Ok, at this point, we know that we are masking the result of the
3876 // ADD down to exactly one bit. If the constant we are adding has
3877 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003878 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003879
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003880 // Check to see if any bits below the one bit set in AndRHSV are set.
3881 if ((AddRHS & (AndRHSV-1)) == 0) {
3882 // If not, the only thing that can effect the output of the AND is
3883 // the bit specified by AndRHSV. If that bit is set, the effect of
3884 // the XOR is to toggle the bit. If it is clear, then the ADD has
3885 // no effect.
3886 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3887 TheAnd.setOperand(0, X);
3888 return &TheAnd;
3889 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003890 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003891 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003892 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003893 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003894 }
3895 }
3896 }
3897 }
3898 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003899
3900 case Instruction::Shl: {
3901 // We know that the AND will not produce any of the bits shifted in, so if
3902 // the anded constant includes them, clear them now!
3903 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003904 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003905 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003906 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003907 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
3908 AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003909
Zhou Sheng290bec52007-03-29 08:15:12 +00003910 if (CI->getValue() == ShlMask) {
3911 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003912 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3913 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003914 TheAnd.setOperand(1, CI);
3915 return &TheAnd;
3916 }
3917 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003918 }
Chris Lattner4de84762010-01-04 07:02:48 +00003919 case Instruction::LShr: {
Chris Lattner62a355c2003-09-19 19:05:02 +00003920 // We know that the AND will not produce any of the bits shifted in, so if
3921 // the anded constant includes them, clear them now! This only applies to
3922 // unsigned shifts, because a signed shr may bring in set bits!
3923 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003924 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003925 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003926 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003927 ConstantInt *CI = ConstantInt::get(Op->getContext(),
3928 AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003929
Zhou Sheng290bec52007-03-29 08:15:12 +00003930 if (CI->getValue() == ShrMask) {
3931 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003932 return ReplaceInstUsesWith(TheAnd, Op);
3933 } else if (CI != AndRHS) {
3934 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3935 return &TheAnd;
3936 }
3937 break;
3938 }
3939 case Instruction::AShr:
3940 // Signed shr.
3941 // See if this is shifting in some sign extension, then masking it out
3942 // with an and.
3943 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003944 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003945 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003946 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Chris Lattner4de84762010-01-04 07:02:48 +00003947 Constant *C = ConstantInt::get(Op->getContext(),
3948 AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003949 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003950 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003951 // Make the argument unsigned.
3952 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003953 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003954 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003955 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003956 }
3957 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003958 }
3959 return 0;
3960}
3961
Chris Lattner8b170942002-08-09 23:47:40 +00003962
Chris Lattnera96879a2004-09-29 17:40:11 +00003963/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3964/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003965/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3966/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003967/// insert new instructions.
3968Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969 bool isSigned, bool Inside,
3970 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003971 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003972 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003973 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974
Chris Lattnera96879a2004-09-29 17:40:11 +00003975 if (Inside) {
3976 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003977 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003978
Reid Spencere4d87aa2006-12-23 06:05:41 +00003979 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003980 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003981 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003983 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 }
3985
3986 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003987 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003988 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003989 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003990 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003991 }
3992
3993 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003994 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003995
Reid Spencere4e40032007-03-21 23:19:50 +00003996 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003997 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003998 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 ICmpInst::Predicate pred = (isSigned ?
4000 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004001 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004002 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004003
Reid Spencere4e40032007-03-21 23:19:50 +00004004 // Emit V-Lo >u Hi-1-Lo
4005 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004006 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004007 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004008 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004009 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004010}
4011
Chris Lattner7203e152005-09-18 07:22:02 +00004012// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4013// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4014// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4015// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004016static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004017 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004018 uint32_t BitWidth = Val->getType()->getBitWidth();
4019 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004020
4021 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004022 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004023 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004024 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004025 return true;
4026}
4027
Chris Lattner7203e152005-09-18 07:22:02 +00004028/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4029/// where isSub determines whether the operator is a sub. If we can fold one of
4030/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004031///
4032/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4033/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4034/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4035///
4036/// return (A +/- B).
4037///
4038Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004039 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004040 Instruction &I) {
4041 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4042 if (!LHSI || LHSI->getNumOperands() != 2 ||
4043 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4044
4045 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4046
4047 switch (LHSI->getOpcode()) {
4048 default: return 0;
4049 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004050 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004051 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004052 if ((Mask->getValue().countLeadingZeros() +
4053 Mask->getValue().countPopulation()) ==
4054 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004055 break;
4056
4057 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4058 // part, we don't need any explicit masks to take them out of A. If that
4059 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004060 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004061 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004062 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004063 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004064 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004065 break;
4066 }
4067 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004068 return 0;
4069 case Instruction::Or:
4070 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004071 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004072 if ((Mask->getValue().countLeadingZeros() +
4073 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004074 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004075 break;
4076 return 0;
4077 }
4078
Chris Lattnerc8e77562005-09-18 04:24:45 +00004079 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004080 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4081 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004082}
4083
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004084/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4085Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4086 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004087 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004088 ConstantInt *LHSCst, *RHSCst;
4089 ICmpInst::Predicate LHSCC, RHSCC;
4090
Chris Lattnerea065fb2008-11-16 05:10:52 +00004091 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004092 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004093 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004094 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004095 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004096 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004097
Chris Lattner3f40e232009-11-29 00:51:17 +00004098 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4099 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4100 // where C is a power of 2
4101 if (LHSCC == ICmpInst::ICMP_ULT &&
4102 LHSCst->getValue().isPowerOf2()) {
4103 Value *NewOr = Builder->CreateOr(Val, Val2);
4104 return new ICmpInst(LHSCC, NewOr, LHSCst);
4105 }
4106
4107 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4108 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4109 Value *NewOr = Builder->CreateOr(Val, Val2);
4110 return new ICmpInst(LHSCC, NewOr, LHSCst);
4111 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004112 }
4113
4114 // From here on, we only handle:
4115 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4116 if (Val != Val2) return 0;
4117
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004118 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4119 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4120 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4121 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4122 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4123 return 0;
4124
4125 // We can't fold (ugt x, C) & (sgt x, C2).
4126 if (!PredicatesFoldable(LHSCC, RHSCC))
4127 return 0;
4128
4129 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004130 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004131 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004132 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004133 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004134 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004135 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004136 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4137
4138 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004139 std::swap(LHS, RHS);
4140 std::swap(LHSCst, RHSCst);
4141 std::swap(LHSCC, RHSCC);
4142 }
4143
4144 // At this point, we know we have have two icmp instructions
4145 // comparing a value against two constants and and'ing the result
4146 // together. Because of the above check, we know that we only have
4147 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4148 // (from the FoldICmpLogical check above), that the two constants
4149 // are not equal and that the larger constant is on the RHS
4150 assert(LHSCst != RHSCst && "Compares not folded above?");
4151
4152 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004153 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004154 case ICmpInst::ICMP_EQ:
4155 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004156 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004157 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4158 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4159 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00004160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004161 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4162 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4163 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4164 return ReplaceInstUsesWith(I, LHS);
4165 }
4166 case ICmpInst::ICMP_NE:
4167 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004168 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004169 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004170 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004171 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004172 break; // (X != 13 & X u< 15) -> no change
4173 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004174 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004175 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004176 break; // (X != 13 & X s< 15) -> no change
4177 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4178 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4179 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4180 return ReplaceInstUsesWith(I, RHS);
4181 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004182 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004183 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004184 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004185 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004186 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004187 }
4188 break; // (X != 13 & X != 15) -> no change
4189 }
4190 break;
4191 case ICmpInst::ICMP_ULT:
4192 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004193 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004194 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4195 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00004196 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4198 break;
4199 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4200 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4201 return ReplaceInstUsesWith(I, LHS);
4202 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4203 break;
4204 }
4205 break;
4206 case ICmpInst::ICMP_SLT:
4207 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004208 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004209 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4210 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Chris Lattner4de84762010-01-04 07:02:48 +00004211 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004212 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4213 break;
4214 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4215 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4216 return ReplaceInstUsesWith(I, LHS);
4217 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4218 break;
4219 }
4220 break;
4221 case ICmpInst::ICMP_UGT:
4222 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004223 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004224 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4225 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4226 return ReplaceInstUsesWith(I, RHS);
4227 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4228 break;
4229 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004230 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004231 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004232 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004233 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004234 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004235 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004236 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4237 break;
4238 }
4239 break;
4240 case ICmpInst::ICMP_SGT:
4241 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004242 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004243 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4244 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4245 return ReplaceInstUsesWith(I, RHS);
4246 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4247 break;
4248 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004249 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004250 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004251 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004252 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004253 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004254 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004255 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4256 break;
4257 }
4258 break;
4259 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004260
4261 return 0;
4262}
4263
Chris Lattner42d1be02009-07-23 05:14:02 +00004264Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4265 FCmpInst *RHS) {
4266
4267 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4268 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4269 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4270 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4271 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4272 // If either of the constants are nans, then the whole thing returns
4273 // false.
4274 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00004275 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004276 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004277 LHS->getOperand(0), RHS->getOperand(0));
4278 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004279
4280 // Handle vector zeros. This occurs because the canonical form of
4281 // "fcmp ord x,x" is "fcmp ord x, 0".
4282 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4283 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004284 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004285 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004286 return 0;
4287 }
4288
4289 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4290 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4291 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4292
4293
4294 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4295 // Swap RHS operands to match LHS.
4296 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4297 std::swap(Op1LHS, Op1RHS);
4298 }
4299
4300 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4301 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4302 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004303 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004304
4305 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Chris Lattner4de84762010-01-04 07:02:48 +00004306 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00004307 if (Op0CC == FCmpInst::FCMP_TRUE)
4308 return ReplaceInstUsesWith(I, RHS);
4309 if (Op1CC == FCmpInst::FCMP_TRUE)
4310 return ReplaceInstUsesWith(I, LHS);
4311
4312 bool Op0Ordered;
4313 bool Op1Ordered;
4314 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4315 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4316 if (Op1Pred == 0) {
4317 std::swap(LHS, RHS);
4318 std::swap(Op0Pred, Op1Pred);
4319 std::swap(Op0Ordered, Op1Ordered);
4320 }
4321 if (Op0Pred == 0) {
4322 // uno && ueq -> uno && (uno || eq) -> ueq
4323 // ord && olt -> ord && (ord && lt) -> olt
4324 if (Op0Ordered == Op1Ordered)
4325 return ReplaceInstUsesWith(I, RHS);
4326
4327 // uno && oeq -> uno && (ord && eq) -> false
4328 // uno && ord -> false
4329 if (!Op0Ordered)
Chris Lattner4de84762010-01-04 07:02:48 +00004330 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner42d1be02009-07-23 05:14:02 +00004331 // ord && ueq -> ord && (uno || eq) -> oeq
Chris Lattner4de84762010-01-04 07:02:48 +00004332 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
Chris Lattner42d1be02009-07-23 05:14:02 +00004333 }
4334 }
4335
4336 return 0;
4337}
4338
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004339
Chris Lattner7e708292002-06-25 16:13:24 +00004340Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004341 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004343
Chris Lattnerd06094f2009-11-10 00:55:12 +00004344 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4345 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004346
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004347 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004348 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004349 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004350 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004351
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004352 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004353 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004354 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004355
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004356 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004357 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004358 Value *Op0LHS = Op0I->getOperand(0);
4359 Value *Op0RHS = Op0I->getOperand(1);
4360 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004361 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004362 case Instruction::Xor:
4363 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004364 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004365 if (!Op0I->hasOneUse()) break;
4366
4367 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4368 // Not masking anything out for the LHS, move to RHS.
4369 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4370 Op0RHS->getName()+".masked");
4371 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4372 }
4373 if (!isa<Constant>(Op0RHS) &&
4374 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4375 // Not masking anything out for the RHS, move to LHS.
4376 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4377 Op0LHS->getName()+".masked");
4378 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004379 }
4380
Chris Lattner6e7ba452005-01-01 16:22:27 +00004381 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004382 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004383 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4384 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4385 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004387 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004388 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004389 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004390 break;
4391
4392 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004393 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4394 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4395 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004397 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004398
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004399 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4400 // has 1's for all bits that the subtraction with A might affect.
4401 if (Op0I->hasOneUse()) {
4402 uint32_t BitWidth = AndRHSMask.getBitWidth();
4403 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4404 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4405
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004406 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004407 if (!(A && A->isZero()) && // avoid infinite recursion.
4408 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004409 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004410 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4411 }
4412 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004413 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004414
4415 case Instruction::Shl:
4416 case Instruction::LShr:
4417 // (1 << x) & 1 --> zext(x == 0)
4418 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004419 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004420 Value *NewICmp =
4421 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004422 return new ZExtInst(NewICmp, I.getType());
4423 }
4424 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004425 }
4426
Chris Lattner58403262003-07-23 19:25:52 +00004427 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004428 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004429 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004430 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004431 // If this is an integer truncation or change from signed-to-unsigned, and
4432 // if the source is an and/or with immediate, transform it. This
4433 // frequently occurs for bitfield accesses.
4434 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004435 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004436 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004437 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004438 if (CastOp->getOpcode() == Instruction::And) {
4439 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004440 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4441 // This will fold the two constants together, which may allow
4442 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004443 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004444 CastOp->getOperand(0), I.getType(),
4445 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004446 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004447 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004448 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004449 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004450 } else if (CastOp->getOpcode() == Instruction::Or) {
4451 // Change: and (cast (or X, C1) to T), C2
4452 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004453 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004454 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004455 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004456 return ReplaceInstUsesWith(I, AndRHS);
4457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004458 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004459 }
Chris Lattner06782f82003-07-23 19:36:21 +00004460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004461
4462 // Try to fold constant and into select arguments.
4463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004465 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004466 if (isa<PHINode>(Op0))
4467 if (Instruction *NV = FoldOpIntoPhi(I))
4468 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004469 }
4470
Chris Lattner5b62aa72004-06-18 06:07:51 +00004471
Misha Brukmancb6267b2004-07-30 12:50:08 +00004472 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004473 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4474 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4475 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4476 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4477 I.getName()+".demorgan");
4478 return BinaryOperator::CreateNot(Or);
4479 }
4480
Chris Lattner2082ad92006-02-13 23:07:23 +00004481 {
Chris Lattner003b6202007-06-15 05:58:24 +00004482 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004483 // (A|B) & ~(A&B) -> A^B
4484 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4485 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4486 ((A == C && B == D) || (A == D && B == C)))
4487 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004488
Chris Lattnerd06094f2009-11-10 00:55:12 +00004489 // ~(A&B) & (A|B) -> A^B
4490 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4491 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4492 ((A == C && B == D) || (A == D && B == C)))
4493 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004494
4495 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004496 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004497 if (A == Op1) { // (A^B)&A -> A&(A^B)
4498 I.swapOperands(); // Simplify below
4499 std::swap(Op0, Op1);
4500 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4501 cast<BinaryOperator>(Op0)->swapOperands();
4502 I.swapOperands(); // Simplify below
4503 std::swap(Op0, Op1);
4504 }
4505 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004506
Chris Lattner64daab52006-04-01 08:03:55 +00004507 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004508 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004509 if (B == Op0) { // B&(A^B) -> B&(B^A)
4510 cast<BinaryOperator>(Op1)->swapOperands();
4511 std::swap(A, B);
4512 }
Chris Lattner74381062009-08-30 07:44:24 +00004513 if (A == Op0) // A&(A^B) -> A & ~B
4514 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004515 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004516
4517 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004518 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4519 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004520 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004521 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4522 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004523 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004524 }
4525
Reid Spencere4d87aa2006-12-23 06:05:41 +00004526 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4527 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004528 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004529 return R;
4530
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004531 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4532 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4533 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004534 }
4535
Chris Lattner6fc205f2006-05-05 06:39:07 +00004536 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004537 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4538 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4539 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4540 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004541 if (SrcTy == Op1C->getOperand(0)->getType() &&
4542 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004543 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4545 I.getType(), TD) &&
4546 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4547 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004548 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4549 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004550 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004551 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004552 }
Chris Lattnere511b742006-11-14 07:46:50 +00004553
4554 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004555 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4556 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4557 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004558 SI0->getOperand(1) == SI1->getOperand(1) &&
4559 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004560 Value *NewOp =
4561 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4562 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004563 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004564 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004565 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004566 }
4567
Evan Cheng8db90722008-10-14 17:15:11 +00004568 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004569 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004570 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4571 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4572 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004573 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004574
Chris Lattner7e708292002-06-25 16:13:24 +00004575 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004576}
4577
Chris Lattner8c34cd22008-10-05 02:13:19 +00004578/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4579/// capable of providing pieces of a bswap. The subexpression provides pieces
4580/// of a bswap if it is proven that each of the non-zero bytes in the output of
4581/// the expression came from the corresponding "byte swapped" byte in some other
4582/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4583/// we know that the expression deposits the low byte of %X into the high byte
4584/// of the bswap result and that all other bytes are zero. This expression is
4585/// accepted, the high byte of ByteValues is set to X to indicate a correct
4586/// match.
4587///
4588/// This function returns true if the match was unsuccessful and false if so.
4589/// On entry to the function the "OverallLeftShift" is a signed integer value
4590/// indicating the number of bytes that the subexpression is later shifted. For
4591/// example, if the expression is later right shifted by 16 bits, the
4592/// OverallLeftShift value would be -2 on entry. This is used to specify which
4593/// byte of ByteValues is actually being set.
4594///
4595/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4596/// byte is masked to zero by a user. For example, in (X & 255), X will be
4597/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4598/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4599/// always in the local (OverallLeftShift) coordinate space.
4600///
4601static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4602 SmallVector<Value*, 8> &ByteValues) {
4603 if (Instruction *I = dyn_cast<Instruction>(V)) {
4604 // If this is an or instruction, it may be an inner node of the bswap.
4605 if (I->getOpcode() == Instruction::Or) {
4606 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4607 ByteValues) ||
4608 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4609 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004610 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004611
4612 // If this is a logical shift by a constant multiple of 8, recurse with
4613 // OverallLeftShift and ByteMask adjusted.
4614 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4615 unsigned ShAmt =
4616 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4617 // Ensure the shift amount is defined and of a byte value.
4618 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4619 return true;
4620
4621 unsigned ByteShift = ShAmt >> 3;
4622 if (I->getOpcode() == Instruction::Shl) {
4623 // X << 2 -> collect(X, +2)
4624 OverallLeftShift += ByteShift;
4625 ByteMask >>= ByteShift;
4626 } else {
4627 // X >>u 2 -> collect(X, -2)
4628 OverallLeftShift -= ByteShift;
4629 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004630 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004631 }
4632
4633 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4634 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4635
4636 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4637 ByteValues);
4638 }
4639
4640 // If this is a logical 'and' with a mask that clears bytes, clear the
4641 // corresponding bytes in ByteMask.
4642 if (I->getOpcode() == Instruction::And &&
4643 isa<ConstantInt>(I->getOperand(1))) {
4644 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4645 unsigned NumBytes = ByteValues.size();
4646 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4647 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4648
4649 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4650 // If this byte is masked out by a later operation, we don't care what
4651 // the and mask is.
4652 if ((ByteMask & (1 << i)) == 0)
4653 continue;
4654
4655 // If the AndMask is all zeros for this byte, clear the bit.
4656 APInt MaskB = AndMask & Byte;
4657 if (MaskB == 0) {
4658 ByteMask &= ~(1U << i);
4659 continue;
4660 }
4661
4662 // If the AndMask is not all ones for this byte, it's not a bytezap.
4663 if (MaskB != Byte)
4664 return true;
4665
4666 // Otherwise, this byte is kept.
4667 }
4668
4669 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4670 ByteValues);
4671 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004672 }
4673
Chris Lattner8c34cd22008-10-05 02:13:19 +00004674 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4675 // the input value to the bswap. Some observations: 1) if more than one byte
4676 // is demanded from this input, then it could not be successfully assembled
4677 // into a byteswap. At least one of the two bytes would not be aligned with
4678 // their ultimate destination.
4679 if (!isPowerOf2_32(ByteMask)) return true;
4680 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004681
Chris Lattner8c34cd22008-10-05 02:13:19 +00004682 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4683 // is demanded, it needs to go into byte 0 of the result. This means that the
4684 // byte needs to be shifted until it lands in the right byte bucket. The
4685 // shift amount depends on the position: if the byte is coming from the high
4686 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4687 // low part, it must be shifted left.
4688 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4689 if (InputByteNo < ByteValues.size()/2) {
4690 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4691 return true;
4692 } else {
4693 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4694 return true;
4695 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004696
4697 // If the destination byte value is already defined, the values are or'd
4698 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004699 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004700 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004701 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004702 return false;
4703}
4704
4705/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4706/// If so, insert the new bswap intrinsic and return it.
4707Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004708 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004709 if (!ITy || ITy->getBitWidth() % 16 ||
4710 // ByteMask only allows up to 32-byte values.
4711 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004712 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004713
4714 /// ByteValues - For each byte of the result, we keep track of which value
4715 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004716 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004717 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004718
4719 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004720 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4721 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004722 return 0;
4723
4724 // Check to see if all of the bytes come from the same value.
4725 Value *V = ByteValues[0];
4726 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4727
4728 // Check to make sure that all of the bytes come from the same value.
4729 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4730 if (ByteValues[i] != V)
4731 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004732 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004733 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004734 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004735 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004736}
4737
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004738/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4739/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4740/// we can simplify this expression to "cond ? C : D or B".
4741static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Chris Lattner4de84762010-01-04 07:02:48 +00004742 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004743 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004744 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004745 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004746 return 0;
4747
Chris Lattnera6a474d2008-11-16 04:26:55 +00004748 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004749 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004750 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004751 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004752 return SelectInst::Create(Cond, C, B);
4753 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004754 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004755 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004756 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004757 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004758 return 0;
4759}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004760
Chris Lattner69d4ced2008-11-16 05:20:07 +00004761/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4762Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4763 ICmpInst *LHS, ICmpInst *RHS) {
4764 Value *Val, *Val2;
4765 ConstantInt *LHSCst, *RHSCst;
4766 ICmpInst::Predicate LHSCC, RHSCC;
4767
4768 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4770 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004771 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004772
4773
4774 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4775 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4776 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4777 Value *NewOr = Builder->CreateOr(Val, Val2);
4778 return new ICmpInst(LHSCC, NewOr, LHSCst);
4779 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004780
4781 // From here on, we only handle:
4782 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4783 if (Val != Val2) return 0;
4784
4785 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4786 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4787 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4788 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4789 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4790 return 0;
4791
4792 // We can't fold (ugt x, C) | (sgt x, C2).
4793 if (!PredicatesFoldable(LHSCC, RHSCC))
4794 return 0;
4795
4796 // Ensure that the larger constant is on the RHS.
4797 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004798 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004799 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004800 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004801 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4802 else
4803 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4804
4805 if (ShouldSwap) {
4806 std::swap(LHS, RHS);
4807 std::swap(LHSCst, RHSCst);
4808 std::swap(LHSCC, RHSCC);
4809 }
4810
4811 // At this point, we know we have have two icmp instructions
4812 // comparing a value against two constants and or'ing the result
4813 // together. Because of the above check, we know that we only have
4814 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4815 // FoldICmpLogical check above), that the two constants are not
4816 // equal.
4817 assert(LHSCst != RHSCst && "Compares not folded above?");
4818
4819 switch (LHSCC) {
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:
4822 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004823 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004824 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004825 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004826 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004827 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004828 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004829 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004830 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004831 }
4832 break; // (X == 13 | X == 15) -> no change
4833 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4834 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4835 break;
4836 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4837 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4838 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4839 return ReplaceInstUsesWith(I, RHS);
4840 }
4841 break;
4842 case ICmpInst::ICMP_NE:
4843 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004844 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004845 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4846 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4847 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4848 return ReplaceInstUsesWith(I, LHS);
4849 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4850 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4851 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004852 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004853 }
4854 break;
4855 case ICmpInst::ICMP_ULT:
4856 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004857 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004858 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4859 break;
4860 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4861 // If RHSCst is [us]MAXINT, it is always false. Not handling
4862 // this can cause overflow.
4863 if (RHSCst->isMaxValue(false))
4864 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004865 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004866 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004867 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4868 break;
4869 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4870 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4871 return ReplaceInstUsesWith(I, RHS);
4872 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4873 break;
4874 }
4875 break;
4876 case ICmpInst::ICMP_SLT:
4877 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004878 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004879 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4880 break;
4881 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4882 // If RHSCst is [us]MAXINT, it is always false. Not handling
4883 // this can cause overflow.
4884 if (RHSCst->isMaxValue(true))
4885 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004886 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004887 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004888 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4889 break;
4890 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4891 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4892 return ReplaceInstUsesWith(I, RHS);
4893 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4894 break;
4895 }
4896 break;
4897 case ICmpInst::ICMP_UGT:
4898 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004899 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004900 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4901 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4902 return ReplaceInstUsesWith(I, LHS);
4903 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4904 break;
4905 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4906 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004907 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004908 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4909 break;
4910 }
4911 break;
4912 case ICmpInst::ICMP_SGT:
4913 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004914 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004915 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4916 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4917 return ReplaceInstUsesWith(I, LHS);
4918 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4919 break;
4920 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4921 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Chris Lattner4de84762010-01-04 07:02:48 +00004922 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004923 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4924 break;
4925 }
4926 break;
4927 }
4928 return 0;
4929}
4930
Chris Lattner5414cc52009-07-23 05:46:22 +00004931Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4932 FCmpInst *RHS) {
4933 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4934 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4935 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4936 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4937 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4938 // If either of the constants are nans, then the whole thing returns
4939 // true.
4940 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner4de84762010-01-04 07:02:48 +00004941 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00004942
4943 // Otherwise, no need to compare the two constants, compare the
4944 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004945 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004946 LHS->getOperand(0), RHS->getOperand(0));
4947 }
4948
4949 // Handle vector zeros. This occurs because the canonical form of
4950 // "fcmp uno x,x" is "fcmp uno x, 0".
4951 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4952 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004953 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004954 LHS->getOperand(0), RHS->getOperand(0));
4955
4956 return 0;
4957 }
4958
4959 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4960 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4961 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4962
4963 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4964 // Swap RHS operands to match LHS.
4965 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4966 std::swap(Op1LHS, Op1RHS);
4967 }
4968 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4969 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4970 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004971 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004972 Op0LHS, Op0RHS);
4973 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Chris Lattner4de84762010-01-04 07:02:48 +00004974 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner5414cc52009-07-23 05:46:22 +00004975 if (Op0CC == FCmpInst::FCMP_FALSE)
4976 return ReplaceInstUsesWith(I, RHS);
4977 if (Op1CC == FCmpInst::FCMP_FALSE)
4978 return ReplaceInstUsesWith(I, LHS);
4979 bool Op0Ordered;
4980 bool Op1Ordered;
4981 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4982 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4983 if (Op0Ordered == Op1Ordered) {
4984 // If both are ordered or unordered, return a new fcmp with
4985 // or'ed predicates.
Chris Lattner4de84762010-01-04 07:02:48 +00004986 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +00004987 if (Instruction *I = dyn_cast<Instruction>(RV))
4988 return I;
4989 // Otherwise, it's a constant boolean value...
4990 return ReplaceInstUsesWith(I, RV);
4991 }
4992 }
4993 return 0;
4994}
4995
Bill Wendlinga698a472008-12-01 08:23:25 +00004996/// FoldOrWithConstants - This helper function folds:
4997///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004998/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004999///
5000/// into:
5001///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005002/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005003///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005004/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005005Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005006 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005007 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5008 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005009
Bill Wendling286a0542008-12-02 06:24:20 +00005010 Value *V1 = 0;
5011 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005012 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005013
Bill Wendling29976b92008-12-02 06:18:11 +00005014 APInt Xor = CI1->getValue() ^ CI2->getValue();
5015 if (!Xor.isAllOnesValue()) return 0;
5016
Bill Wendling286a0542008-12-02 06:24:20 +00005017 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005018 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005019 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005020 }
5021
5022 return 0;
5023}
5024
Chris Lattner7e708292002-06-25 16:13:24 +00005025Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005026 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005028
Chris Lattnerd06094f2009-11-10 00:55:12 +00005029 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5030 return ReplaceInstUsesWith(I, V);
5031
5032
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005033 // See if we can simplify any instructions used by the instruction whose sole
5034 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005035 if (SimplifyDemandedInstructionBits(I))
5036 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005037
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005038 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005039 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005040 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005041 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005042 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005043 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005044 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005045 return BinaryOperator::CreateAnd(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00005046 ConstantInt::get(I.getContext(),
5047 RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005048 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005049
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005050 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005051 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005052 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005053 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005054 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005055 return BinaryOperator::CreateXor(Or,
Chris Lattner4de84762010-01-04 07:02:48 +00005056 ConstantInt::get(I.getContext(),
5057 C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005058 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005059
5060 // Try to fold constant and into select arguments.
5061 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005062 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005063 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005064 if (isa<PHINode>(Op0))
5065 if (Instruction *NV = FoldOpIntoPhi(I))
5066 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005067 }
5068
Chris Lattner4f637d42006-01-06 17:59:59 +00005069 Value *A = 0, *B = 0;
5070 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005071
Chris Lattner6423d4c2006-07-10 20:25:24 +00005072 // (A | B) | C and A | (B | C) -> bswap if possible.
5073 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005074 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5075 match(Op1, m_Or(m_Value(), m_Value())) ||
5076 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5077 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005078 if (Instruction *BSwap = MatchBSwap(I))
5079 return BSwap;
5080 }
5081
Chris Lattner6e4c6492005-05-09 04:58:36 +00005082 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005083 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005084 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005085 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005086 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005087 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005088 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005089 }
5090
5091 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005092 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005093 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005094 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005095 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005096 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005097 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005098 }
5099
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005100 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005101 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005102 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5103 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005104 Value *V1 = 0, *V2 = 0, *V3 = 0;
5105 C1 = dyn_cast<ConstantInt>(C);
5106 C2 = dyn_cast<ConstantInt>(D);
5107 if (C1 && C2) { // (A & C1)|(B & C2)
5108 // If we have: ((V + N) & C1) | (V & C2)
5109 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5110 // replace with V+N.
5111 if (C1->getValue() == ~C2->getValue()) {
5112 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005113 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005114 // Add commutes, try both ways.
5115 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5116 return ReplaceInstUsesWith(I, A);
5117 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5118 return ReplaceInstUsesWith(I, A);
5119 }
5120 // Or commutes, try both ways.
5121 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005122 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005123 // Add commutes, try both ways.
5124 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5125 return ReplaceInstUsesWith(I, B);
5126 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5127 return ReplaceInstUsesWith(I, B);
5128 }
5129 }
Chris Lattnere4412c12010-01-04 06:03:59 +00005130
5131 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
5132 // iff (C1&C2) == 0 and (N&~C1) == 0
5133 if ((C1->getValue() & C2->getValue()) == 0) {
5134 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
5135 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
5136 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
5137 return BinaryOperator::CreateAnd(A,
5138 ConstantInt::get(A->getContext(),
5139 C1->getValue()|C2->getValue()));
5140 // Or commutes, try both ways.
5141 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
5142 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
5143 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
5144 return BinaryOperator::CreateAnd(B,
5145 ConstantInt::get(B->getContext(),
5146 C1->getValue()|C2->getValue()));
5147 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00005148 }
5149
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005150 // Check to see if we have any common things being and'ed. If so, find the
5151 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005152 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00005153 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005154 if (A == B) // (A & C)|(A & D) == A & (C|D)
5155 V1 = A, V2 = C, V3 = D;
5156 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5157 V1 = A, V2 = B, V3 = C;
5158 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5159 V1 = C, V2 = A, V3 = D;
5160 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5161 V1 = C, V2 = A, V3 = B;
5162
5163 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005164 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005165 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005166 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005167 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005168
Dan Gohman1975d032008-10-30 20:40:10 +00005169 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattner4de84762010-01-04 07:02:48 +00005170 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005171 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00005172 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005173 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00005174 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005175 return Match;
Chris Lattner4de84762010-01-04 07:02:48 +00005176 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005177 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005178
Bill Wendlingb01865c2008-11-30 13:52:49 +00005179 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005180 if ((match(C, m_Not(m_Specific(D))) &&
5181 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005182 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005183 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005184 if ((match(A, m_Not(m_Specific(D))) &&
5185 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005186 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005187 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 if ((match(C, m_Not(m_Specific(B))) &&
5189 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005190 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005191 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005192 if ((match(A, m_Not(m_Specific(B))) &&
5193 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005194 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005195 }
Chris Lattnere511b742006-11-14 07:46:50 +00005196
5197 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005198 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5199 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5200 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005201 SI0->getOperand(1) == SI1->getOperand(1) &&
5202 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005203 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5204 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005205 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005206 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005207 }
5208 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005209
Bill Wendlingb3833d12008-12-01 01:07:11 +00005210 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005211 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5212 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005213 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005214 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005215 }
5216 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005217 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5218 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005219 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005220 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005221 }
5222
Chris Lattnerd06094f2009-11-10 00:55:12 +00005223 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5224 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5225 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5226 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5227 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5228 I.getName()+".demorgan");
5229 return BinaryOperator::CreateNot(And);
5230 }
Chris Lattnera2881962003-02-18 19:28:33 +00005231
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5233 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005234 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005235 return R;
5236
Chris Lattner69d4ced2008-11-16 05:20:07 +00005237 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5238 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5239 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005240 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005241
5242 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005243 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005244 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005245 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005246 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5247 !isa<ICmpInst>(Op1C->getOperand(0))) {
5248 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005249 if (SrcTy == Op1C->getOperand(0)->getType() &&
5250 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005251 // Only do this if the casts both really cause code to be
5252 // generated.
5253 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5254 I.getType(), TD) &&
5255 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5256 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005257 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5258 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005259 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005260 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005261 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005262 }
Chris Lattner99c65742007-10-24 05:38:08 +00005263 }
5264
5265
5266 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5267 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005268 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5269 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5270 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005271 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005272
Chris Lattner7e708292002-06-25 16:13:24 +00005273 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005274}
5275
Dan Gohman844731a2008-05-13 00:00:25 +00005276namespace {
5277
Chris Lattnerc317d392004-02-16 01:20:27 +00005278// XorSelf - Implements: X ^ X --> 0
5279struct XorSelf {
5280 Value *RHS;
5281 XorSelf(Value *rhs) : RHS(rhs) {}
5282 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5283 Instruction *apply(BinaryOperator &Xor) const {
5284 return &Xor;
5285 }
5286};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005287
Dan Gohman844731a2008-05-13 00:00:25 +00005288}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005289
Chris Lattner7e708292002-06-25 16:13:24 +00005290Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005291 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005293
Evan Chengd34af782008-03-25 20:07:13 +00005294 if (isa<UndefValue>(Op1)) {
5295 if (isa<UndefValue>(Op0))
5296 // Handle undef ^ undef -> 0 special case. This is a common
5297 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005299 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005300 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005301
Chris Lattnerc317d392004-02-16 01:20:27 +00005302 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005303 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005304 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005306 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005307
5308 // See if we can simplify any instructions used by the instruction whose sole
5309 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005310 if (SimplifyDemandedInstructionBits(I))
5311 return &I;
5312 if (isa<VectorType>(I.getType()))
5313 if (isa<ConstantAggregateZero>(Op1))
5314 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005315
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005316 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005317 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005318 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5319 if (Op0I->getOpcode() == Instruction::And ||
5320 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005321 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5322 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5323 if (dyn_castNotVal(Op0I->getOperand(1)))
5324 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005325 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005326 Value *NotY =
5327 Builder->CreateNot(Op0I->getOperand(1),
5328 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005329 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005330 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005331 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005332 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005333
5334 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5335 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5336 if (isFreeToInvert(Op0I->getOperand(0)) &&
5337 isFreeToInvert(Op0I->getOperand(1))) {
5338 Value *NotX =
5339 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5340 Value *NotY =
5341 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5342 if (Op0I->getOpcode() == Instruction::And)
5343 return BinaryOperator::CreateOr(NotX, NotY);
5344 return BinaryOperator::CreateAnd(NotX, NotY);
5345 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005346 }
5347 }
5348 }
5349
5350
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005352 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005353 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005354 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005355 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005357
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005358 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005359 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005360 FCI->getOperand(0), FCI->getOperand(1));
5361 }
5362
Nick Lewycky517e1f52008-05-31 19:01:33 +00005363 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5364 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5365 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5366 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5367 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005368 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5369 (RHS == ConstantExpr::getCast(Opcode,
Chris Lattner4de84762010-01-04 07:02:48 +00005370 ConstantInt::getTrue(I.getContext()),
Chris Lattner74381062009-08-30 07:44:24 +00005371 Op0C->getDestTy()))) {
5372 CI->setPredicate(CI->getInversePredicate());
5373 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005374 }
5375 }
5376 }
5377 }
5378
Reid Spencere4d87aa2006-12-23 06:05:41 +00005379 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005380 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005381 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5382 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005383 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5384 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005385 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005386 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005387 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005388
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005389 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005390 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005391 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005392 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005393 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005395 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005396 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005397 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005398 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005399 // (X + C) ^ signbit -> (X + C + signbit)
Chris Lattner4de84762010-01-04 07:02:48 +00005400 Constant *C = ConstantInt::get(I.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00005401 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005402 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005403
Chris Lattner7c4049c2004-01-12 19:35:11 +00005404 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005405 } else if (Op0I->getOpcode() == Instruction::Or) {
5406 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005407 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005408 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005409 // Anything in both C1 and C2 is known to be zero, remove it from
5410 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005411 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5412 NewRHS = ConstantExpr::getAnd(NewRHS,
5413 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005414 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005415 I.setOperand(0, Op0I->getOperand(0));
5416 I.setOperand(1, NewRHS);
5417 return &I;
5418 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005419 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005420 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005421 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005422
5423 // Try to fold constant and into select arguments.
5424 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005425 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005426 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005427 if (isa<PHINode>(Op0))
5428 if (Instruction *NV = FoldOpIntoPhi(I))
5429 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005430 }
5431
Dan Gohman186a6362009-08-12 16:04:34 +00005432 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005433 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005434 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005435
Dan Gohman186a6362009-08-12 16:04:34 +00005436 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005437 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005438 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005439
Chris Lattner318bf792007-03-18 22:51:34 +00005440
5441 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5442 if (Op1I) {
5443 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005444 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005445 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005446 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005447 I.swapOperands();
5448 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005449 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005450 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005451 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005452 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005453 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005454 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005455 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005456 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005457 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005458 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005459 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005460 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005461 std::swap(A, B);
5462 }
Chris Lattner318bf792007-03-18 22:51:34 +00005463 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005464 I.swapOperands(); // Simplified below.
5465 std::swap(Op0, Op1);
5466 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005467 }
Chris Lattner318bf792007-03-18 22:51:34 +00005468 }
5469
5470 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5471 if (Op0I) {
5472 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005473 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005474 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005475 if (A == Op1) // (B|A)^B == (A|B)^B
5476 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005477 if (B == Op1) // (A|B)^B == A & ~B
5478 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005479 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005480 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005481 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005482 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005483 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005484 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005485 if (A == Op1) // (A&B)^A -> (B&A)^A
5486 std::swap(A, B);
5487 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005488 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005489 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005490 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005491 }
Chris Lattner318bf792007-03-18 22:51:34 +00005492 }
5493
5494 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5495 if (Op0I && Op1I && Op0I->isShift() &&
5496 Op0I->getOpcode() == Op1I->getOpcode() &&
5497 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5498 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005499 Value *NewOp =
5500 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5501 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005502 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005503 Op1I->getOperand(1));
5504 }
5505
5506 if (Op0I && Op1I) {
5507 Value *A, *B, *C, *D;
5508 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005509 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5510 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005511 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005512 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005513 }
5514 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005515 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5516 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005517 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005518 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005519 }
5520
5521 // (A & B)^(C & D)
5522 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005523 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5524 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005525 // (X & Y)^(X & Y) -> (Y^Z) & X
5526 Value *X = 0, *Y = 0, *Z = 0;
5527 if (A == C)
5528 X = A, Y = B, Z = D;
5529 else if (A == D)
5530 X = A, Y = B, Z = C;
5531 else if (B == C)
5532 X = B, Y = A, Z = D;
5533 else if (B == D)
5534 X = B, Y = A, Z = C;
5535
5536 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005537 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005538 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005539 }
5540 }
5541 }
5542
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5544 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005545 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005546 return R;
5547
Chris Lattner6fc205f2006-05-05 06:39:07 +00005548 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005549 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005550 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005551 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5552 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005553 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005554 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005555 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5556 I.getType(), TD) &&
5557 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5558 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005559 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5560 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005561 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005562 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005563 }
Chris Lattner99c65742007-10-24 05:38:08 +00005564 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005565
Chris Lattner7e708292002-06-25 16:13:24 +00005566 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005567}
5568
Chris Lattner4de84762010-01-04 07:02:48 +00005569static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005570 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005571}
Chris Lattnera96879a2004-09-29 17:40:11 +00005572
Dan Gohman6de29f82009-06-15 22:12:54 +00005573static bool HasAddOverflow(ConstantInt *Result,
5574 ConstantInt *In1, ConstantInt *In2,
5575 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005576 if (IsSigned)
5577 if (In2->getValue().isNegative())
5578 return Result->getValue().sgt(In1->getValue());
5579 else
5580 return Result->getValue().slt(In1->getValue());
5581 else
5582 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005583}
5584
Dan Gohman6de29f82009-06-15 22:12:54 +00005585/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005586/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005587static bool AddWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00005588 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005589 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005590
Dan Gohman6de29f82009-06-15 22:12:54 +00005591 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5592 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00005593 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
5594 if (HasAddOverflow(ExtractElement(Result, Idx),
5595 ExtractElement(In1, Idx),
5596 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00005597 IsSigned))
5598 return true;
5599 }
5600 return false;
5601 }
5602
5603 return HasAddOverflow(cast<ConstantInt>(Result),
5604 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5605 IsSigned);
5606}
5607
5608static bool HasSubOverflow(ConstantInt *Result,
5609 ConstantInt *In1, ConstantInt *In2,
5610 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005611 if (IsSigned)
5612 if (In2->getValue().isNegative())
5613 return Result->getValue().slt(In1->getValue());
5614 else
5615 return Result->getValue().sgt(In1->getValue());
5616 else
5617 return Result->getValue().ugt(In1->getValue());
5618}
5619
Dan Gohman6de29f82009-06-15 22:12:54 +00005620/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5621/// overflowed for this type.
5622static bool SubWithOverflow(Constant *&Result, Constant *In1,
Chris Lattner4de84762010-01-04 07:02:48 +00005623 Constant *In2, bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005624 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005625
5626 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5627 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Chris Lattner4de84762010-01-04 07:02:48 +00005628 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i);
5629 if (HasSubOverflow(ExtractElement(Result, Idx),
5630 ExtractElement(In1, Idx),
5631 ExtractElement(In2, Idx),
Dan Gohman6de29f82009-06-15 22:12:54 +00005632 IsSigned))
5633 return true;
5634 }
5635 return false;
5636 }
5637
5638 return HasSubOverflow(cast<ConstantInt>(Result),
5639 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5640 IsSigned);
5641}
5642
Chris Lattner10c0d912008-04-22 02:53:33 +00005643
Reid Spencere4d87aa2006-12-23 06:05:41 +00005644/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005645/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005646Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 ICmpInst::Predicate Cond,
5648 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005649 // Look through bitcasts.
5650 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5651 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005652
Chris Lattner574da9b2005-01-13 20:14:25 +00005653 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005654 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005655 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005656 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005657 // know pointers can't overflow since the gep is inbounds. See if we can
5658 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005659 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5660
5661 // If not, synthesize the offset the hard way.
5662 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005663 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005664 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005665 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005666 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005667 // If the base pointers are different, but the indices are the same, just
5668 // compare the base pointer.
5669 if (PtrBase != GEPRHS->getOperand(0)) {
5670 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005671 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005672 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005673 if (IndicesTheSame)
5674 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5675 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5676 IndicesTheSame = false;
5677 break;
5678 }
5679
5680 // If all indices are the same, just compare the base pointers.
5681 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005683 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005684
5685 // Otherwise, the base pointers are different and the indices are
5686 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005687 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005688 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005689
Chris Lattnere9d782b2005-01-13 22:25:21 +00005690 // If one of the GEPs has all zero indices, recurse.
5691 bool AllZeros = true;
5692 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5693 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5694 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5695 AllZeros = false;
5696 break;
5697 }
5698 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5700 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005701
5702 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005703 AllZeros = true;
5704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5705 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5706 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5707 AllZeros = false;
5708 break;
5709 }
5710 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005712
Chris Lattner4401c9c2005-01-14 00:20:05 +00005713 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5714 // If the GEPs only differ by one index, compare it.
5715 unsigned NumDifferences = 0; // Keep track of # differences.
5716 unsigned DiffOperand = 0; // The operand that differs.
5717 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5718 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005719 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5720 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005721 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005722 NumDifferences = 2;
5723 break;
5724 } else {
5725 if (NumDifferences++) break;
5726 DiffOperand = i;
5727 }
5728 }
5729
5730 if (NumDifferences == 0) // SAME GEP?
5731 return ReplaceInstUsesWith(I, // No comparison is needed here.
Chris Lattner4de84762010-01-04 07:02:48 +00005732 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005733 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005734
Chris Lattner4401c9c2005-01-14 00:20:05 +00005735 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005736 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5737 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005738 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005739 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005740 }
5741 }
5742
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005744 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005745 if (TD &&
5746 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005747 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5748 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005749 Value *L = EmitGEPOffset(GEPLHS, *this);
5750 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005751 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005752 }
5753 }
5754 return 0;
5755}
5756
Chris Lattnera5406232008-05-19 20:18:56 +00005757/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5758///
5759Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5760 Instruction *LHSI,
5761 Constant *RHSC) {
5762 if (!isa<ConstantFP>(RHSC)) return 0;
5763 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5764
5765 // Get the width of the mantissa. We don't want to hack on conversions that
5766 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005767 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005768 if (MantissaWidth == -1) return 0; // Unknown.
5769
5770 // Check to see that the input is converted from an integer type that is small
5771 // enough that preserves all bits. TODO: check here for "known" sign bits.
5772 // 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 +00005773 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005774
5775 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005776 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5777 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005778 ++InputSize;
5779
5780 // If the conversion would lose info, don't hack on this.
5781 if ((int)InputSize > MantissaWidth)
5782 return 0;
5783
5784 // Otherwise, we can potentially simplify the comparison. We know that it
5785 // will always come through as an integer value and we know the constant is
5786 // not a NAN (it would have been previously simplified).
5787 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5788
5789 ICmpInst::Predicate Pred;
5790 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005791 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005792 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005793 case FCmpInst::FCMP_OEQ:
5794 Pred = ICmpInst::ICMP_EQ;
5795 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005796 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005797 case FCmpInst::FCMP_OGT:
5798 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5799 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005800 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005801 case FCmpInst::FCMP_OGE:
5802 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5803 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005804 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 case FCmpInst::FCMP_OLT:
5806 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5807 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005808 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005809 case FCmpInst::FCMP_OLE:
5810 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5811 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005812 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 case FCmpInst::FCMP_ONE:
5814 Pred = ICmpInst::ICMP_NE;
5815 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005816 case FCmpInst::FCMP_ORD:
Chris Lattner4de84762010-01-04 07:02:48 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00005818 case FCmpInst::FCMP_UNO:
Chris Lattner4de84762010-01-04 07:02:48 +00005819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattnera5406232008-05-19 20:18:56 +00005820 }
5821
5822 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5823
5824 // Now we know that the APFloat is a normal number, zero or inf.
5825
Chris Lattner85162782008-05-20 03:50:52 +00005826 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005827 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005828 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005829
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005830 if (!LHSUnsigned) {
5831 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5832 // and large values.
5833 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5834 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5835 APFloat::rmNearestTiesToEven);
5836 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5837 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5838 Pred == ICmpInst::ICMP_SLE)
Chris Lattner4de84762010-01-04 07:02:48 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5840 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005841 }
5842 } else {
5843 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5844 // +INF and large values.
5845 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5846 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5847 APFloat::rmNearestTiesToEven);
5848 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5849 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5850 Pred == ICmpInst::ICMP_ULE)
Chris Lattner4de84762010-01-04 07:02:48 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5852 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005853 }
Chris Lattnera5406232008-05-19 20:18:56 +00005854 }
5855
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005856 if (!LHSUnsigned) {
5857 // See if the RHS value is < SignedMin.
5858 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5859 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5860 APFloat::rmNearestTiesToEven);
5861 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5862 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5863 Pred == ICmpInst::ICMP_SGE)
Chris Lattner4de84762010-01-04 07:02:48 +00005864 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
5865 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005866 }
Chris Lattnera5406232008-05-19 20:18:56 +00005867 }
5868
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005869 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5870 // [0, UMAX], but it may still be fractional. See if it is fractional by
5871 // casting the FP value to the integer value and back, checking for equality.
5872 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005873 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005874 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5875 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005876 if (!RHS.isZero()) {
5877 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005878 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5879 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005880 if (!Equal) {
5881 // If we had a comparison against a fractional value, we have to adjust
5882 // the compare predicate and sometimes the value. RHSC is rounded towards
5883 // zero at this point.
5884 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005885 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005886 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005888 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Chris Lattner4de84762010-01-04 07:02:48 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005890 case ICmpInst::ICMP_ULE:
5891 // (float)int <= 4.4 --> int <= 4
5892 // (float)int <= -4.4 --> false
5893 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005895 break;
5896 case ICmpInst::ICMP_SLE:
5897 // (float)int <= 4.4 --> int <= 4
5898 // (float)int <= -4.4 --> int < -4
5899 if (RHS.isNegative())
5900 Pred = ICmpInst::ICMP_SLT;
5901 break;
5902 case ICmpInst::ICMP_ULT:
5903 // (float)int < -4.4 --> false
5904 // (float)int < 4.4 --> int <= 4
5905 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005907 Pred = ICmpInst::ICMP_ULE;
5908 break;
5909 case ICmpInst::ICMP_SLT:
5910 // (float)int < -4.4 --> int < -4
5911 // (float)int < 4.4 --> int <= 4
5912 if (!RHS.isNegative())
5913 Pred = ICmpInst::ICMP_SLE;
5914 break;
5915 case ICmpInst::ICMP_UGT:
5916 // (float)int > 4.4 --> int > 4
5917 // (float)int > -4.4 --> true
5918 if (RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005919 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005920 break;
5921 case ICmpInst::ICMP_SGT:
5922 // (float)int > 4.4 --> int > 4
5923 // (float)int > -4.4 --> int >= -4
5924 if (RHS.isNegative())
5925 Pred = ICmpInst::ICMP_SGE;
5926 break;
5927 case ICmpInst::ICMP_UGE:
5928 // (float)int >= -4.4 --> true
5929 // (float)int >= 4.4 --> int > 4
5930 if (!RHS.isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00005931 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005932 Pred = ICmpInst::ICMP_UGT;
5933 break;
5934 case ICmpInst::ICMP_SGE:
5935 // (float)int >= -4.4 --> int >= -4
5936 // (float)int >= 4.4 --> int > 4
5937 if (!RHS.isNegative())
5938 Pred = ICmpInst::ICMP_SGT;
5939 break;
5940 }
Chris Lattnera5406232008-05-19 20:18:56 +00005941 }
5942 }
5943
5944 // Lower this FP comparison into an appropriate integer version of the
5945 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005946 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005947}
5948
Chris Lattner1f12e442010-01-02 08:12:04 +00005949/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
5950/// cmp pred (load (gep GV, ...)), cmpcst
5951/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00005952/// this into some simple computation that does not need the load. For example
5953/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005954///
5955/// If AndCst is non-null, then the loaded value is masked with that constant
5956/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00005957Instruction *InstCombiner::
5958FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005959 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner56ba7a72010-01-03 03:03:27 +00005960 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
5961 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Chris Lattner1f12e442010-01-02 08:12:04 +00005962
5963 // There are many forms of this optimization we can handle, for now, just do
5964 // the simple index into a single-dimensional array.
5965 //
Chris Lattner56ba7a72010-01-03 03:03:27 +00005966 // Require: GEP GV, 0, i {{, constant indices}}
5967 if (GEP->getNumOperands() < 3 ||
Chris Lattner1f12e442010-01-02 08:12:04 +00005968 !isa<ConstantInt>(GEP->getOperand(1)) ||
Chris Lattner56ba7a72010-01-03 03:03:27 +00005969 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
5970 isa<Constant>(GEP->getOperand(2)))
Chris Lattner1f12e442010-01-02 08:12:04 +00005971 return 0;
Chris Lattner56ba7a72010-01-03 03:03:27 +00005972
5973 // Check that indices after the variable are constants and in-range for the
5974 // type they index. Collect the indices. This is typically for arrays of
5975 // structs.
5976 SmallVector<unsigned, 4> LaterIndices;
Chris Lattner1f12e442010-01-02 08:12:04 +00005977
Chris Lattner56ba7a72010-01-03 03:03:27 +00005978 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
5979 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
5980 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
5981 if (Idx == 0) return 0; // Variable index.
5982
5983 uint64_t IdxVal = Idx->getZExtValue();
5984 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
5985
5986 if (const StructType *STy = dyn_cast<StructType>(EltTy))
5987 EltTy = STy->getElementType(IdxVal);
5988 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
5989 if (IdxVal >= ATy->getNumElements()) return 0;
5990 EltTy = ATy->getElementType();
5991 } else {
5992 return 0; // Unknown type.
5993 }
5994
5995 LaterIndices.push_back(IdxVal);
5996 }
Chris Lattner1f12e442010-01-02 08:12:04 +00005997
Chris Lattner82602bc2010-01-02 20:20:33 +00005998 enum { Overdefined = -3, Undefined = -2 };
5999
Chris Lattner1f12e442010-01-02 08:12:04 +00006000 // Variables for our state machines.
6001
Chris Lattnerbef37372010-01-02 09:35:17 +00006002 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6003 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00006004 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00006005 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00006006 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
6007 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006008
Chris Lattnerbef37372010-01-02 09:35:17 +00006009 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6010 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00006011 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006012
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006013 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
6014 /// define a state machine that triggers for ranges of values that the index
6015 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
6016 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
6017 /// index in the range (inclusive). We use -2 for undefined here because we
6018 /// use relative comparisons and don't want 0-1 to match -1.
6019 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
6020
Chris Lattner10d514e2010-01-02 08:56:52 +00006021 // MagicBitvector - This is a magic bitvector where we set a bit if the
6022 // comparison is true for element 'i'. If there are 64 elements or less in
6023 // the array, this will fully represent all the comparison results.
6024 uint64_t MagicBitvector = 0;
6025
6026
Chris Lattner1f12e442010-01-02 08:12:04 +00006027 // Scan the array and see if one of our patterns matches.
6028 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6029 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006030 Constant *Elt = Init->getOperand(i);
6031
Chris Lattner56ba7a72010-01-03 03:03:27 +00006032 // If this is indexing an array of structures, get the structure element.
6033 if (!LaterIndices.empty())
6034 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
6035 LaterIndices.size());
6036
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006037 // If the element is masked, handle it.
6038 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
6039
Chris Lattner1f12e442010-01-02 08:12:04 +00006040 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006041 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00006042 CompareRHS, TD);
6043 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006044 if (isa<UndefValue>(C)) {
6045 // Extend range state machines to cover this element in case there is an
6046 // undef in the middle of the range.
6047 if (TrueRangeEnd == (int)i-1)
6048 TrueRangeEnd = i;
6049 if (FalseRangeEnd == (int)i-1)
6050 FalseRangeEnd = i;
6051 continue;
6052 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006053
6054 // If we can't compute the result for any of the elements, we have to give
6055 // up evaluating the entire conditional.
6056 if (!isa<ConstantInt>(C)) return 0;
6057
6058 // Otherwise, we know if the comparison is true or false for this element,
6059 // update our state machines.
6060 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6061
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006062 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00006063 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00006064 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006065 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006066 FirstTrueElement = TrueRangeEnd = i; // First true element.
6067 else {
6068 // Update double-compare state machine.
6069 if (SecondTrueElement == Undefined)
6070 SecondTrueElement = i;
6071 else
6072 SecondTrueElement = Overdefined;
6073
6074 // Update range state machine.
6075 if (TrueRangeEnd == (int)i-1)
6076 TrueRangeEnd = i;
6077 else
6078 TrueRangeEnd = Overdefined;
6079 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006080 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00006081 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006082 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006083 FirstFalseElement = FalseRangeEnd = i; // First false element.
6084 else {
6085 // Update double-compare state machine.
6086 if (SecondFalseElement == Undefined)
6087 SecondFalseElement = i;
6088 else
6089 SecondFalseElement = Overdefined;
6090
6091 // Update range state machine.
6092 if (FalseRangeEnd == (int)i-1)
6093 FalseRangeEnd = i;
6094 else
6095 FalseRangeEnd = Overdefined;
6096 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006097 }
6098
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006099
Chris Lattner10d514e2010-01-02 08:56:52 +00006100 // If this element is in range, update our magic bitvector.
6101 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00006102 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00006103
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006104 // If all of our states become overdefined, bail out early. Since the
6105 // predicate is expensive, only check it every 8 elements. This is only
6106 // really useful for really huge arrays.
6107 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
6108 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
6109 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006110 return 0;
6111 }
6112
6113 // Now that we've scanned the entire array, emit our new comparison(s). We
6114 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00006115 Value *Idx = GEP->getOperand(2);
6116
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006117
Chris Lattnerbef37372010-01-02 09:35:17 +00006118 // If the comparison is only true for one or two elements, emit direct
6119 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006120 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006121 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00006122 if (FirstTrueElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00006123 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00006124
Chris Lattnerbef37372010-01-02 09:35:17 +00006125 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6126
Chris Lattner1f12e442010-01-02 08:12:04 +00006127 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006128 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006129 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6130
6131 // True for two elements -> 'i == 47 | i == 72'.
6132 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6133 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6134 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6135 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006136 }
6137
Chris Lattnerbef37372010-01-02 09:35:17 +00006138 // If the comparison is only false for one or two elements, emit direct
6139 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006140 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006141 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00006142 if (FirstFalseElement == Undefined)
Chris Lattner4de84762010-01-04 07:02:48 +00006143 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(GEP->getContext()));
Chris Lattner1f12e442010-01-02 08:12:04 +00006144
Chris Lattnerbef37372010-01-02 09:35:17 +00006145 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6146
6147 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006148 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006149 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6150
6151 // False for two elements -> 'i != 47 & i != 72'.
6152 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6153 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6154 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6155 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006156 }
6157
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006158 // If the comparison can be replaced with a range comparison for the elements
6159 // where it is true, emit the range check.
6160 if (TrueRangeEnd != Overdefined) {
6161 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
6162
6163 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
6164 if (FirstTrueElement) {
6165 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
6166 Idx = Builder->CreateAdd(Idx, Offs);
6167 }
6168
6169 Value *End = ConstantInt::get(Idx->getType(),
6170 TrueRangeEnd-FirstTrueElement+1);
6171 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
6172 }
6173
6174 // False range check.
6175 if (FalseRangeEnd != Overdefined) {
6176 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
6177 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
6178 if (FirstFalseElement) {
6179 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
6180 Idx = Builder->CreateAdd(Idx, Offs);
6181 }
6182
6183 Value *End = ConstantInt::get(Idx->getType(),
6184 FalseRangeEnd-FirstFalseElement);
6185 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
6186 }
6187
6188
Chris Lattner10d514e2010-01-02 08:56:52 +00006189 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6190 // of this load, replace it with computation that does:
6191 // ((magic_cst >> i) & 1) != 0
6192 if (Init->getNumOperands() <= 32 ||
6193 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6194 const Type *Ty;
6195 if (Init->getNumOperands() <= 32)
6196 Ty = Type::getInt32Ty(Init->getContext());
6197 else
6198 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00006199 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00006200 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6201 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6202 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6203 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006204
Chris Lattner1f12e442010-01-02 08:12:04 +00006205 return 0;
6206}
6207
6208
Reid Spencere4d87aa2006-12-23 06:05:41 +00006209Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006210 bool Changed = false;
6211
6212 /// Orders the operands of the compare so that they are listed from most
6213 /// complex to least complex. This puts constants before unary operators,
6214 /// before binary operators.
6215 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6216 I.swapOperands();
6217 Changed = true;
6218 }
6219
Chris Lattner8b170942002-08-09 23:47:40 +00006220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006221
Chris Lattner210c5d42009-11-09 23:55:12 +00006222 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6223 return ReplaceInstUsesWith(I, V);
6224
Chris Lattner58e97462007-01-14 19:42:17 +00006225 // Simplify 'fcmp pred X, X'
6226 if (Op0 == Op1) {
6227 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006228 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006229 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6230 case FCmpInst::FCMP_ULT: // True if unordered or less than
6231 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6232 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6233 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6234 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006235 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006236 return &I;
6237
6238 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6239 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6240 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6241 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6242 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6243 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006244 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006245 return &I;
6246 }
6247 }
6248
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 // Handle fcmp with constant RHS
6250 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6251 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6252 switch (LHSI->getOpcode()) {
6253 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006254 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6255 // block. If in the same block, we're encouraging jump threading. If
6256 // not, we are just pessimizing the code by making an i1 phi.
6257 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006258 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006259 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006261 case Instruction::SIToFP:
6262 case Instruction::UIToFP:
6263 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6264 return NV;
6265 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00006266 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006267 // If either operand of the select is a constant, we can fold the
6268 // comparison into the select arms, which will cause one to be
6269 // constant folded and the select turned into a bitwise or.
6270 Value *Op1 = 0, *Op2 = 0;
6271 if (LHSI->hasOneUse()) {
6272 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6273 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006274 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006275 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006276 Op2 = Builder->CreateFCmp(I.getPredicate(),
6277 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006278 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6279 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006280 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006281 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006282 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6283 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006284 }
6285 }
6286
6287 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006288 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006289 break;
6290 }
Chris Lattner34e0c762010-01-02 08:20:51 +00006291 case Instruction::Load:
6292 if (GetElementPtrInst *GEP =
6293 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6294 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6295 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006296 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner34e0c762010-01-02 08:20:51 +00006297 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6298 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006299 }
6300 break;
6301 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006302 }
6303
6304 return Changed ? &I : 0;
6305}
6306
6307Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006308 bool Changed = false;
6309
6310 /// Orders the operands of the compare so that they are listed from most
6311 /// complex to least complex. This puts constants before unary operators,
6312 /// before binary operators.
6313 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6314 I.swapOperands();
6315 Changed = true;
6316 }
6317
Reid Spencere4d87aa2006-12-23 06:05:41 +00006318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006319
Chris Lattner210c5d42009-11-09 23:55:12 +00006320 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6321 return ReplaceInstUsesWith(I, V);
6322
6323 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006324
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // icmp's with boolean values can always be turned into bitwise operations
Chris Lattner4de84762010-01-04 07:02:48 +00006326 if (Ty == Type::getInt1Ty(I.getContext())) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006328 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006329 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006330 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006331 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006332 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006333 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006334 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006335
Reid Spencere4d87aa2006-12-23 06:05:41 +00006336 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006337 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006338 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006339 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006340 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006341 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006342 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006343 case ICmpInst::ICMP_SGT:
6344 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006345 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006346 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006347 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006348 return BinaryOperator::CreateAnd(Not, Op0);
6349 }
6350 case ICmpInst::ICMP_UGE:
6351 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6352 // FALL THROUGH
6353 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006354 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006355 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006356 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006357 case ICmpInst::ICMP_SGE:
6358 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6359 // FALL THROUGH
6360 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006361 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006362 return BinaryOperator::CreateOr(Not, Op0);
6363 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006364 }
Chris Lattner8b170942002-08-09 23:47:40 +00006365 }
6366
Dan Gohman1c8491e2009-04-25 17:12:48 +00006367 unsigned BitWidth = 0;
6368 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006369 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6370 else if (Ty->isIntOrIntVector())
6371 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006372
6373 bool isSignBit = false;
6374
Dan Gohman81b28ce2008-09-16 18:46:06 +00006375 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006376 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006377 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006378
Chris Lattnerb6566012008-01-05 01:18:20 +00006379 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006380 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006381 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006382 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006383 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006384 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006385
Dan Gohman81b28ce2008-09-16 18:46:06 +00006386 // If we have an icmp le or icmp ge instruction, turn it into the
6387 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006388 // them being folded in the code below. The SimplifyICmpInst code has
6389 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006390 switch (I.getPredicate()) {
6391 default: break;
6392 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006393 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006394 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006395 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006396 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006397 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006398 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006399 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006400 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006401 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006402 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006403 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006404 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006405 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006406 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006407 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006408 }
6409
Chris Lattner183661e2008-07-11 05:40:05 +00006410 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006411 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006412 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006413 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6414 }
6415
6416 // See if we can fold the comparison based on range information we can get
6417 // by checking whether bits are known to be zero or one in the input.
6418 if (BitWidth != 0) {
6419 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6420 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6421
6422 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006423 isSignBit ? APInt::getSignBit(BitWidth)
6424 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006425 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006426 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006427 if (SimplifyDemandedBits(I.getOperandUse(1),
6428 APInt::getAllOnesValue(BitWidth),
6429 Op1KnownZero, Op1KnownOne, 0))
6430 return &I;
6431
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006432 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006433 // in. Compute the Min, Max and RHS values based on the known bits. For the
6434 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006435 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6436 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006437 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006438 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6439 Op0Min, Op0Max);
6440 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6441 Op1Min, Op1Max);
6442 } else {
6443 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6444 Op0Min, Op0Max);
6445 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6446 Op1Min, Op1Max);
6447 }
6448
Chris Lattner183661e2008-07-11 05:40:05 +00006449 // If Min and Max are known to be the same, then SimplifyDemandedBits
6450 // figured out that the LHS is a constant. Just constant fold this now so
6451 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006452 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(I.getPredicate(),
Chris Lattner4de84762010-01-04 07:02:48 +00006454 ConstantInt::get(I.getContext(), Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006455 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006456 return new ICmpInst(I.getPredicate(), Op0,
Chris Lattner4de84762010-01-04 07:02:48 +00006457 ConstantInt::get(I.getContext(), Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006458
Chris Lattner183661e2008-07-11 05:40:05 +00006459 // Based on the range information we know about the LHS, see if we can
6460 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006461 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006462 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006463 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006464 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00006465 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006466 break;
6467 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006468 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner4de84762010-01-04 07:02:48 +00006469 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006470 break;
6471 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006472 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006473 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006474 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006475 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006476 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006477 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006478 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6479 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006480 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006481 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006482
6483 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6484 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006485 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006486 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006487 }
Chris Lattner84dff672008-07-11 05:08:55 +00006488 break;
6489 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006490 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006491 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006492 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006493 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006494
6495 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006496 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6498 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006499 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006500 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006501
6502 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6503 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006504 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006505 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006506 }
Chris Lattner84dff672008-07-11 05:08:55 +00006507 break;
6508 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006509 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner4de84762010-01-04 07:02:48 +00006510 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006511 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner4de84762010-01-04 07:02:48 +00006512 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006513 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006514 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006515 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6516 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006517 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006518 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006519 }
Chris Lattner84dff672008-07-11 05:08:55 +00006520 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006521 case ICmpInst::ICMP_SGT:
6522 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006523 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006524 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006525 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006526
6527 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006528 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006529 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6530 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006531 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006532 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006533 }
6534 break;
6535 case ICmpInst::ICMP_SGE:
6536 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6537 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006538 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006539 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006540 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006541 break;
6542 case ICmpInst::ICMP_SLE:
6543 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6544 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006545 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006546 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006547 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006548 break;
6549 case ICmpInst::ICMP_UGE:
6550 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6551 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006552 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006553 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006554 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006555 break;
6556 case ICmpInst::ICMP_ULE:
6557 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6558 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006559 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006560 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Chris Lattner4de84762010-01-04 07:02:48 +00006561 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
Chris Lattner84dff672008-07-11 05:08:55 +00006562 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006563 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006564
6565 // Turn a signed comparison into an unsigned one if both operands
6566 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006567 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006568 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6569 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006570 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006571 }
6572
6573 // Test if the ICmpInst instruction is used exclusively by a select as
6574 // part of a minimum or maximum operation. If so, refrain from doing
6575 // any other folding. This helps out other analyses which understand
6576 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6577 // and CodeGen. And in this case, at least one of the comparison
6578 // operands has at least one user besides the compare (the select),
6579 // which would often largely negate the benefit of folding anyway.
6580 if (I.hasOneUse())
6581 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6582 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6583 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6584 return 0;
6585
6586 // See if we are doing a comparison between a constant and an instruction that
6587 // can be folded into the comparison.
6588 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006589 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006590 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006591 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006592 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006593 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6594 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006595 }
6596
Chris Lattner01deb9d2007-04-03 17:43:25 +00006597 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006598 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6599 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6600 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006601 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006602 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006603 if (RHSC->isNullValue() &&
6604 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6605 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6606 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006607 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006608 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006609 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006610 // block. If in the same block, we're encouraging jump threading. If
6611 // not, we are just pessimizing the code by making an i1 phi.
6612 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006613 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006614 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006615 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006616 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006617 // If either operand of the select is a constant, we can fold the
6618 // comparison into the select arms, which will cause one to be
6619 // constant folded and the select turned into a bitwise or.
6620 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006621 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6622 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6623 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6624 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6625
6626 // We only want to perform this transformation if it will not lead to
6627 // additional code. This is true if either both sides of the select
6628 // fold to a constant (in which case the icmp is replaced with a select
6629 // which will usually simplify) or this is the only user of the
6630 // select (in which case we are trading a select+icmp for a simpler
6631 // select+icmp).
6632 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6633 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006634 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6635 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006636 if (!Op2)
6637 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6638 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006639 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006640 }
Chris Lattner6970b662005-04-23 15:31:55 +00006641 break;
6642 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006643 case Instruction::Call:
6644 // If we have (malloc != null), and if the malloc has a single use, we
6645 // can assume it is successful and remove the malloc.
6646 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6647 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006648 // Need to explicitly erase malloc call here, instead of adding it to
6649 // Worklist, because it won't get DCE'd from the Worklist since
6650 // isInstructionTriviallyDead() returns false for function calls.
6651 // It is OK to replace LHSI/MallocCall with Undef because the
6652 // instruction that uses it will be erased via Worklist.
6653 if (extractMallocCall(LHSI)) {
6654 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6655 EraseInstFromFunction(*LHSI);
6656 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00006657 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez83d63912009-09-18 22:35:49 +00006658 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006659 }
6660 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6661 if (MallocCall->hasOneUse()) {
6662 MallocCall->replaceAllUsesWith(
6663 UndefValue::get(MallocCall->getType()));
6664 EraseInstFromFunction(*MallocCall);
6665 Worklist.Add(LHSI); // The malloc's bitcast use.
6666 return ReplaceInstUsesWith(I,
Chris Lattner4de84762010-01-04 07:02:48 +00006667 ConstantInt::get(Type::getInt1Ty(I.getContext()),
Victor Hernandez68afa542009-10-21 19:11:40 +00006668 !I.isTrueWhenEqual()));
6669 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006670 }
6671 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006672 case Instruction::IntToPtr:
6673 // icmp pred inttoptr(X), null -> icmp pred X, 0
6674 if (RHSC->isNullValue() && TD &&
6675 TD->getIntPtrType(RHSC->getContext()) ==
6676 LHSI->getOperand(0)->getType())
6677 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6678 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6679 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006680
6681 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006682 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00006683 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006684 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006685 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6686 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006687 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006688 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6689 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006690 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006691 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006692 }
Chris Lattner6970b662005-04-23 15:31:55 +00006693 }
6694
Reid Spencere4d87aa2006-12-23 06:05:41 +00006695 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006696 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006697 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006698 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006699 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006700 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6701 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006702 return NI;
6703
Reid Spencere4d87aa2006-12-23 06:05:41 +00006704 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006705 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6706 // now.
6707 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6708 if (isa<PointerType>(Op0->getType()) &&
6709 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006710 // We keep moving the cast from the left operand over to the right
6711 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006712 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006713
Chris Lattner57d86372007-01-06 01:45:59 +00006714 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6715 // so eliminate it as well.
6716 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6717 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006718
Chris Lattnerde90b762003-11-03 04:25:02 +00006719 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006720 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006721 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006722 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006723 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006724 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006725 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006726 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006727 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006728 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006729 }
Chris Lattner57d86372007-01-06 01:45:59 +00006730 }
6731
6732 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006733 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006734 // This comes up when you have code like
6735 // int X = A < B;
6736 // if (X) ...
6737 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006738 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006739 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006740 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006741 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006742 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006743
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006744 // See if it's the same type of instruction on the left and right.
6745 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6746 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006747 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006748 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006749 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006750 default: break;
6751 case Instruction::Add:
6752 case Instruction::Sub:
6753 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006754 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006755 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006756 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006757 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6759 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006760 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006761 ? I.getUnsignedPredicate()
6762 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006763 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006764 Op1I->getOperand(0));
6765 }
6766
6767 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006768 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006769 ? I.getUnsignedPredicate()
6770 : I.getSignedPredicate();
6771 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006772 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006773 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006774 }
6775 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006776 break;
6777 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006778 if (!I.isEquality())
6779 break;
6780
Nick Lewycky5d52c452008-08-21 05:56:10 +00006781 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6782 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6783 // Mask = -1 >> count-trailing-zeros(Cst).
6784 if (!CI->isZero() && !CI->isOne()) {
6785 const APInt &AP = CI->getValue();
Chris Lattner4de84762010-01-04 07:02:48 +00006786 ConstantInt *Mask = ConstantInt::get(I.getContext(),
Nick Lewycky5d52c452008-08-21 05:56:10 +00006787 APInt::getLowBitsSet(AP.getBitWidth(),
6788 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006789 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006790 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6791 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006792 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006793 }
6794 }
6795 break;
6796 }
6797 }
6798 }
6799 }
6800
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006801 // ~x < ~y --> y < x
6802 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006803 if (match(Op0, m_Not(m_Value(A))) &&
6804 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006805 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006806 }
6807
Chris Lattner65b72ba2006-09-18 04:22:48 +00006808 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006809 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006810
6811 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006812 if (match(Op0, m_Neg(m_Value(A))) &&
6813 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006814 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006815
Dan Gohman4ae51262009-08-12 16:23:25 +00006816 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006817 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6818 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006819 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006820 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006821 }
6822
Dan Gohman4ae51262009-08-12 16:23:25 +00006823 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006824 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006825 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006826 if (match(B, m_ConstantInt(C1)) &&
6827 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Chris Lattner4de84762010-01-04 07:02:48 +00006828 Constant *NC = ConstantInt::get(I.getContext(),
6829 C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006830 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6831 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006832 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006833
6834 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006835 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6836 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6837 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6838 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006839 }
6840 }
6841
Dan Gohman4ae51262009-08-12 16:23:25 +00006842 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006843 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006844 // A == (A^B) -> B == 0
6845 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006846 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006847 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006848 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006849
6850 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006851 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006852 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006853 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006854
6855 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006856 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006857 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006858 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006859
Chris Lattner9c2328e2006-11-14 06:06:06 +00006860 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6861 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006862 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6863 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006864 Value *X = 0, *Y = 0, *Z = 0;
6865
6866 if (A == C) {
6867 X = B; Y = D; Z = A;
6868 } else if (A == D) {
6869 X = B; Y = C; Z = A;
6870 } else if (B == C) {
6871 X = A; Y = D; Z = B;
6872 } else if (B == D) {
6873 X = A; Y = C; Z = B;
6874 }
6875
6876 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006877 Op1 = Builder->CreateXor(X, Y, "tmp");
6878 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006879 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006880 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006881 return &I;
6882 }
6883 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006884 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006885
6886 {
6887 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006888 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006889 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006890 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6891
Chris Lattner2799baf2009-12-21 03:19:28 +00006892 // icmp X, X+Cst
6893 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006894 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006895 }
Chris Lattner7e708292002-06-25 16:13:24 +00006896 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006897}
6898
Chris Lattner2799baf2009-12-21 03:19:28 +00006899/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6900Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6901 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006902 ICmpInst::Predicate Pred,
6903 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006904 // If we have X+0, exit early (simplifying logic below) and let it get folded
6905 // elsewhere. icmp X+0, X -> icmp X, X
6906 if (CI->isZero()) {
6907 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6908 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6909 }
6910
6911 // (X+4) == X -> false.
6912 if (Pred == ICmpInst::ICMP_EQ)
6913 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6914
6915 // (X+4) != X -> true.
6916 if (Pred == ICmpInst::ICMP_NE)
6917 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006918
6919 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6920 bool isNUW = false, isNSW = false;
6921 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6922 isNUW = Add->hasNoUnsignedWrap();
6923 isNSW = Add->hasNoSignedWrap();
6924 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006925
6926 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6927 // so the values can never be equal. Similiarly for all other "or equals"
6928 // operators.
6929
6930 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6931 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6932 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6933 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006934 // If this is an NUW add, then this is always false.
6935 if (isNUW)
6936 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6937
Chris Lattner2799baf2009-12-21 03:19:28 +00006938 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6939 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6940 }
6941
6942 // (X+1) >u X --> X <u (0-1) --> X != 255
6943 // (X+2) >u X --> X <u (0-2) --> X <u 254
6944 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006945 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6946 // If this is an NUW add, then this is always true.
6947 if (isNUW)
6948 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006949 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006950 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006951
6952 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6953 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6954 APInt::getSignedMaxValue(BitWidth));
6955
6956 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6957 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6958 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6959 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6960 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6961 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006962 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6963 // If this is an NSW add, then we have two cases: if the constant is
6964 // positive, then this is always false, if negative, this is always true.
6965 if (isNSW) {
6966 bool isTrue = CI->getValue().isNegative();
6967 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6968 }
6969
Chris Lattner2799baf2009-12-21 03:19:28 +00006970 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006971 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006972
6973 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6974 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6975 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6976 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6977 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6978 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006979
6980 // If this is an NSW add, then we have two cases: if the constant is
6981 // positive, then this is always true, if negative, this is always false.
6982 if (isNSW) {
6983 bool isTrue = !CI->getValue().isNegative();
6984 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6985 }
6986
Chris Lattner2799baf2009-12-21 03:19:28 +00006987 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6988 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6989 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6990}
Chris Lattner562ef782007-06-20 23:46:26 +00006991
6992/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6993/// and CmpRHS are both known to be integer constants.
6994Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6995 ConstantInt *DivRHS) {
6996 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6997 const APInt &CmpRHSV = CmpRHS->getValue();
6998
6999 // FIXME: If the operand types don't match the type of the divide
7000 // then don't attempt this transform. The code below doesn't have the
7001 // logic to deal with a signed divide and an unsigned compare (and
7002 // vice versa). This is because (x /s C1) <s C2 produces different
7003 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
7004 // (x /u C1) <u C2. Simply casting the operands and result won't
7005 // work. :( The if statement below tests that condition and bails
7006 // if it finds it.
7007 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007008 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00007009 return 0;
7010 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00007011 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00007012 if (DivIsSigned && DivRHS->isAllOnesValue())
7013 return 0; // The overflow computation also screws up here
7014 if (DivRHS->isOne())
7015 return 0; // Not worth bothering, and eliminates some funny cases
7016 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00007017
7018 // Compute Prod = CI * DivRHS. We are essentially solving an equation
7019 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
7020 // C2 (CI). By solving for X we can turn this into a range check
7021 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007022 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00007023
7024 // Determine if the product overflows by seeing if the product is
7025 // not equal to the divide. Make sure we do the same kind of divide
7026 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007027 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
7028 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00007029
7030 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00007031 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00007032
Chris Lattner1dbfd482007-06-21 18:11:19 +00007033 // Figure out the interval that is being checked. For example, a comparison
7034 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7035 // Compute this interval based on the constants involved and the signedness of
7036 // the compare/divide. This computes a half-open interval, keeping track of
7037 // whether either value in the interval overflows. After analysis each
7038 // overflow variable is set to 0 if it's corresponding bound variable is valid
7039 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7040 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00007041 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007042
Chris Lattner562ef782007-06-20 23:46:26 +00007043 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00007044 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00007045 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007046 HiOverflow = LoOverflow = ProdOV;
7047 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007048 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00007049 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007050 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007051 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00007052 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00007053 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00007054 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007055 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7056 HiOverflow = LoOverflow = ProdOV;
7057 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007058 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007059 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00007060 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007061 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00007062 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7063 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007064 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007065 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner4de84762010-01-04 07:02:48 +00007066 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
Chris Lattnera6321b42008-10-11 22:55:00 +00007067 }
Chris Lattner562ef782007-06-20 23:46:26 +00007068 }
Dan Gohman76491272008-02-13 22:09:18 +00007069 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007070 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007071 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00007072 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007073 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007074 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7075 HiOverflow = 1; // [INTMIN+1, overflow)
7076 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7077 }
Dan Gohman76491272008-02-13 22:09:18 +00007078 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007079 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007080 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007081 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007082 if (!LoOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007083 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007084 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00007085 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7086 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00007087 if (!HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007088 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007089 }
7090
Chris Lattner1dbfd482007-06-21 18:11:19 +00007091 // Dividing by a negative swaps the condition. LT <-> GT
7092 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00007093 }
7094
7095 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007096 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007097 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00007098 case ICmpInst::ICMP_EQ:
7099 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007100 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00007101 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007102 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007103 ICmpInst::ICMP_UGE, X, LoBound);
7104 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007105 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007106 ICmpInst::ICMP_ULT, X, HiBound);
7107 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007108 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007109 case ICmpInst::ICMP_NE:
7110 if (LoOverflow && HiOverflow)
Chris Lattner4de84762010-01-04 07:02:48 +00007111 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner562ef782007-06-20 23:46:26 +00007112 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007113 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007114 ICmpInst::ICMP_ULT, X, LoBound);
7115 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007116 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007117 ICmpInst::ICMP_UGE, X, HiBound);
7118 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007119 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007120 case ICmpInst::ICMP_ULT:
7121 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007122 if (LoOverflow == +1) // Low bound is greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00007123 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007124 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00007125 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007126 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007127 case ICmpInst::ICMP_UGT:
7128 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007129 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00007130 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007131 else if (HiOverflow == -1) // High bound less than input range.
Chris Lattner4de84762010-01-04 07:02:48 +00007132 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007133 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007134 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007135 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007136 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007137 }
7138}
7139
7140
Chris Lattner01deb9d2007-04-03 17:43:25 +00007141/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7142///
7143Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7144 Instruction *LHSI,
7145 ConstantInt *RHS) {
7146 const APInt &RHSV = RHS->getValue();
7147
7148 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00007149 case Instruction::Trunc:
7150 if (ICI.isEquality() && LHSI->hasOneUse()) {
7151 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7152 // of the high bits truncated out of x are known.
7153 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7154 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7155 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7156 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7157 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7158
7159 // If all the high bits are known, we can do this xform.
7160 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7161 // Pull in the high bits from known-ones set.
7162 APInt NewRHS(RHS->getValue());
7163 NewRHS.zext(SrcBits);
7164 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007165 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007166 ConstantInt::get(ICI.getContext(), NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00007167 }
7168 }
7169 break;
7170
Duncan Sands0091bf22007-04-04 06:42:45 +00007171 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00007172 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7173 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7174 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007175 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7176 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007177 Value *CompareVal = LHSI->getOperand(0);
7178
7179 // If the sign bit of the XorCST is not set, there is no change to
7180 // the operation, just stop using the Xor.
7181 if (!XorCST->getValue().isNegative()) {
7182 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00007183 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007184 return &ICI;
7185 }
7186
7187 // Was the old condition true if the operand is positive?
7188 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7189
7190 // If so, the new one isn't.
7191 isTrueIfPositive ^= true;
7192
7193 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007194 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007195 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007196 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007197 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007198 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007199 }
Nick Lewycky4333f492009-01-31 21:30:05 +00007200
7201 if (LHSI->hasOneUse()) {
7202 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7203 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7204 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007205 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007206 ? ICI.getUnsignedPredicate()
7207 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007208 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007209 ConstantInt::get(ICI.getContext(),
7210 RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007211 }
7212
7213 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007214 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007215 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007216 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007217 ? ICI.getUnsignedPredicate()
7218 : ICI.getSignedPredicate();
7219 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007220 return new ICmpInst(Pred, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007221 ConstantInt::get(ICI.getContext(),
7222 RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007223 }
7224 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007225 }
7226 break;
7227 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7228 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7229 LHSI->getOperand(0)->hasOneUse()) {
7230 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7231
7232 // If the LHS is an AND of a truncating cast, we can widen the
7233 // and/compare to be the input width without changing the value
7234 // produced, eliminating a cast.
7235 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7236 // We can do this transformation if either the AND constant does not
7237 // have its sign bit set or if it is an equality comparison.
7238 // Extending a relational comparison when we're checking the sign
7239 // bit would not work.
7240 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007241 (ICI.isEquality() ||
7242 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007243 uint32_t BitWidth =
7244 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7245 APInt NewCST = AndCST->getValue();
7246 NewCST.zext(BitWidth);
7247 APInt NewCI = RHSV;
7248 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007249 Value *NewAnd =
7250 Builder->CreateAnd(Cast->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007251 ConstantInt::get(ICI.getContext(), NewCST),
7252 LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007253 return new ICmpInst(ICI.getPredicate(), NewAnd,
Chris Lattner4de84762010-01-04 07:02:48 +00007254 ConstantInt::get(ICI.getContext(), NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007255 }
7256 }
7257
7258 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7259 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7260 // happens a LOT in code produced by the C front-end, for bitfield
7261 // access.
7262 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7263 if (Shift && !Shift->isShift())
7264 Shift = 0;
7265
7266 ConstantInt *ShAmt;
7267 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7268 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7269 const Type *AndTy = AndCST->getType(); // Type of the and.
7270
7271 // We can fold this as long as we can't shift unknown bits
7272 // into the mask. This can only happen with signed shift
7273 // rights, as they sign-extend.
7274 if (ShAmt) {
7275 bool CanFold = Shift->isLogicalShift();
7276 if (!CanFold) {
7277 // To test for the bad case of the signed shr, see if any
7278 // of the bits shifted in could be tested after the mask.
7279 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7280 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7281
7282 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7283 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7284 AndCST->getValue()) == 0)
7285 CanFold = true;
7286 }
7287
7288 if (CanFold) {
7289 Constant *NewCst;
7290 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007291 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007292 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007293 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007294
7295 // Check to see if we are shifting out any of the bits being
7296 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007297 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007298 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007299 // If we shifted bits out, the fold is not going to work out.
7300 // As a special case, check to see if this means that the
7301 // result is always true or false now.
7302 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00007303 return ReplaceInstUsesWith(ICI,
7304 ConstantInt::getFalse(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007305 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00007306 return ReplaceInstUsesWith(ICI,
7307 ConstantInt::getTrue(ICI.getContext()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007308 } else {
7309 ICI.setOperand(1, NewCst);
7310 Constant *NewAndCST;
7311 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007312 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007313 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007314 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007315 LHSI->setOperand(1, NewAndCST);
7316 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007317 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007318 return &ICI;
7319 }
7320 }
7321 }
7322
7323 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7324 // preferable because it allows the C<<Y expression to be hoisted out
7325 // of a loop if Y is invariant and X is not.
7326 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007327 ICI.isEquality() && !Shift->isArithmeticShift() &&
7328 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007329 // Compute C << Y.
7330 Value *NS;
7331 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007332 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007333 } else {
7334 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007335 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007336 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007337
7338 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007339 Value *NewAnd =
7340 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007341
7342 ICI.setOperand(0, NewAnd);
7343 return &ICI;
7344 }
7345 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007346
7347 // Try to optimize things like "A[i]&42 == 0" to index computations.
7348 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7349 if (GetElementPtrInst *GEP =
7350 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7351 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7352 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7353 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7354 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7355 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7356 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007357 }
7358 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007359 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007360
7361 case Instruction::Or: {
7362 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7363 break;
7364 Value *P, *Q;
7365 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7366 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7367 // -> and (icmp eq P, null), (icmp eq Q, null).
7368
7369 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7370 Constant::getNullValue(P->getType()));
7371 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7372 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007373 Instruction *Op;
7374 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky11ed0312010-01-03 00:55:31 +00007375 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007376 else
Nick Lewycky11ed0312010-01-03 00:55:31 +00007377 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007378 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007379 }
7380 break;
7381 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007382
Chris Lattnera0141b92007-07-15 20:42:37 +00007383 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7384 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7385 if (!ShAmt) break;
7386
7387 uint32_t TypeBits = RHSV.getBitWidth();
7388
7389 // Check that the shift amount is in range. If not, don't perform
7390 // undefined shifts. When the shift is visited it will be
7391 // simplified.
7392 if (ShAmt->uge(TypeBits))
7393 break;
7394
7395 if (ICI.isEquality()) {
7396 // If we are comparing against bits always shifted out, the
7397 // comparison cannot succeed.
7398 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007399 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007400 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007401 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7402 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00007403 Constant *Cst =
7404 ConstantInt::get(Type::getInt1Ty(ICI.getContext()), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007405 return ReplaceInstUsesWith(ICI, Cst);
7406 }
7407
7408 if (LHSI->hasOneUse()) {
7409 // Otherwise strength reduce the shift into an and.
7410 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7411 Constant *Mask =
Chris Lattner4de84762010-01-04 07:02:48 +00007412 ConstantInt::get(ICI.getContext(), APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007413 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007414
Chris Lattner74381062009-08-30 07:44:24 +00007415 Value *And =
7416 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007417 return new ICmpInst(ICI.getPredicate(), And,
Chris Lattner4de84762010-01-04 07:02:48 +00007418 ConstantInt::get(ICI.getContext(),
7419 RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007420 }
7421 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007422
7423 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7424 bool TrueIfSigned = false;
7425 if (LHSI->hasOneUse() &&
7426 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7427 // (X << 31) <s 0 --> (X&1) != 0
Chris Lattner4de84762010-01-04 07:02:48 +00007428 Constant *Mask = ConstantInt::get(ICI.getContext(), APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007429 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007430 Value *And =
7431 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007432 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007433 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007434 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007435 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007436 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007437
7438 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007439 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007440 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007441 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007442 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007443
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007444 // Check that the shift amount is in range. If not, don't perform
7445 // undefined shifts. When the shift is visited it will be
7446 // simplified.
7447 uint32_t TypeBits = RHSV.getBitWidth();
7448 if (ShAmt->uge(TypeBits))
7449 break;
7450
7451 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007452
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007453 // If we are comparing against bits always shifted out, the
7454 // comparison cannot succeed.
7455 APInt Comp = RHSV << ShAmtVal;
7456 if (LHSI->getOpcode() == Instruction::LShr)
7457 Comp = Comp.lshr(ShAmtVal);
7458 else
7459 Comp = Comp.ashr(ShAmtVal);
7460
7461 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7462 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner4de84762010-01-04 07:02:48 +00007463 Constant *Cst = ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
7464 IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007465 return ReplaceInstUsesWith(ICI, Cst);
7466 }
7467
7468 // Otherwise, check to see if the bits shifted out are known to be zero.
7469 // If so, we can compare against the unshifted value:
7470 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007471 if (LHSI->hasOneUse() &&
7472 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007473 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007474 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007475 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007476 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007477
Evan Chengf30752c2008-04-23 00:38:06 +00007478 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007479 // Otherwise strength reduce the shift into an and.
7480 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Chris Lattner4de84762010-01-04 07:02:48 +00007481 Constant *Mask = ConstantInt::get(ICI.getContext(), Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007482
Chris Lattner74381062009-08-30 07:44:24 +00007483 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7484 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007485 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007486 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007487 }
7488 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007489 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007490
7491 case Instruction::SDiv:
7492 case Instruction::UDiv:
7493 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7494 // Fold this div into the comparison, producing a range check.
7495 // Determine, based on the divide type, what the range is being
7496 // checked. If there is an overflow on the low or high side, remember
7497 // it, otherwise compute the range [low, hi) bounding the new value.
7498 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007499 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7500 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7501 DivRHS))
7502 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007503 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007504
7505 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007506 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007507 if (!ICI.isEquality()) {
7508 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7509 if (!LHSC) break;
7510 const APInt &LHSV = LHSC->getValue();
7511
7512 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7513 .subtract(LHSV);
7514
Nick Lewycky4a134af2009-10-25 05:20:17 +00007515 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007516 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007517 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007518 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007519 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007520 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007521 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007522 }
7523 } else {
7524 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007525 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007526 ConstantInt::get(ICI.getContext(),CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007527 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007528 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Chris Lattner4de84762010-01-04 07:02:48 +00007529 ConstantInt::get(ICI.getContext(),CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007530 }
7531 }
7532 }
7533 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007534 }
7535
7536 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7537 if (ICI.isEquality()) {
7538 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7539
7540 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7541 // the second operand is a constant, simplify a bit.
7542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7543 switch (BO->getOpcode()) {
7544 case Instruction::SRem:
7545 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7546 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7547 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7548 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007549 Value *NewRem =
7550 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7551 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007552 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007553 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007554 }
7555 }
7556 break;
7557 case Instruction::Add:
7558 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7559 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7560 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007561 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007562 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007563 } else if (RHSV == 0) {
7564 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7565 // efficiently invertible, or if the add has just this one use.
7566 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7567
Dan Gohman186a6362009-08-12 16:04:34 +00007568 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007569 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007570 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007571 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007572 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007573 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007574 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007575 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007576 }
7577 }
7578 break;
7579 case Instruction::Xor:
7580 // For the xor case, we can xor two constants together, eliminating
7581 // the explicit xor.
7582 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007583 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007584 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007585
7586 // FALLTHROUGH
7587 case Instruction::Sub:
7588 // Replace (([sub|xor] A, B) != 0) with (A != B)
7589 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007590 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007591 BO->getOperand(1));
7592 break;
7593
7594 case Instruction::Or:
7595 // If bits are being or'd in that are not present in the constant we
7596 // are comparing against, then the comparison could never succeed!
7597 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007598 Constant *NotCI = ConstantExpr::getNot(RHS);
7599 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007600 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00007601 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00007602 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007603 }
7604 break;
7605
7606 case Instruction::And:
7607 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7608 // If bits are being compared against that are and'd out, then the
7609 // comparison can never succeed!
7610 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007611 return ReplaceInstUsesWith(ICI,
Chris Lattner4de84762010-01-04 07:02:48 +00007612 ConstantInt::get(Type::getInt1Ty(ICI.getContext()),
Owen Andersond672ecb2009-07-03 00:17:18 +00007613 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007614
7615 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7616 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007617 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007618 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007619 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007620
7621 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007622 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007623 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007624 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007625 ICmpInst::Predicate pred = isICMP_NE ?
7626 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007627 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007628 }
7629
7630 // ((X & ~7) == 0) --> X < 8
7631 if (RHSV == 0 && isHighOnes(BOC)) {
7632 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007633 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007634 ICmpInst::Predicate pred = isICMP_NE ?
7635 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007636 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007637 }
7638 }
7639 default: break;
7640 }
7641 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7642 // Handle icmp {eq|ne} <intrinsic>, intcst.
7643 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007644 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007645 ICI.setOperand(0, II->getOperand(1));
Chris Lattner4de84762010-01-04 07:02:48 +00007646 ICI.setOperand(1, ConstantInt::get(II->getContext(), RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007647 return &ICI;
7648 }
7649 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007650 }
7651 return 0;
7652}
7653
7654/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7655/// We only handle extending casts so far.
7656///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007657Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7658 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007659 Value *LHSCIOp = LHSCI->getOperand(0);
7660 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007661 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007662 Value *RHSCIOp;
7663
Chris Lattner8c756c12007-05-05 22:41:33 +00007664 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7665 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007666 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7667 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007668 cast<IntegerType>(DestTy)->getBitWidth()) {
7669 Value *RHSOp = 0;
7670 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007671 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007672 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7673 RHSOp = RHSC->getOperand(0);
7674 // If the pointer types don't match, insert a bitcast.
7675 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007676 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007677 }
7678
7679 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007680 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007681 }
7682
7683 // The code below only handles extension cast instructions, so far.
7684 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007685 if (LHSCI->getOpcode() != Instruction::ZExt &&
7686 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007687 return 0;
7688
Reid Spencere4d87aa2006-12-23 06:05:41 +00007689 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007690 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007691
Reid Spencere4d87aa2006-12-23 06:05:41 +00007692 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007693 // Not an extension from the same type?
7694 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007695 if (RHSCIOp->getType() != LHSCIOp->getType())
7696 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007697
Nick Lewycky4189a532008-01-28 03:48:02 +00007698 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007699 // and the other is a zext), then we can't handle this.
7700 if (CI->getOpcode() != LHSCI->getOpcode())
7701 return 0;
7702
Nick Lewycky4189a532008-01-28 03:48:02 +00007703 // Deal with equality cases early.
7704 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007705 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007706
7707 // A signed comparison of sign extended values simplifies into a
7708 // signed comparison.
7709 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007710 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007711
7712 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007713 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007714 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007715
Reid Spencere4d87aa2006-12-23 06:05:41 +00007716 // If we aren't dealing with a constant on the RHS, exit early
7717 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7718 if (!CI)
7719 return 0;
7720
7721 // Compute the constant that would happen if we truncated to SrcTy then
7722 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007723 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7724 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007725 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007726
7727 // If the re-extended constant didn't change...
7728 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007729 // Deal with equality cases early.
7730 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007731 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007732
7733 // A signed comparison of sign extended values simplifies into a
7734 // signed comparison.
7735 if (isSignedExt && isSignedCmp)
7736 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7737
7738 // The other three cases all fold into an unsigned comparison.
7739 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007740 }
7741
7742 // The re-extended constant changed so the constant cannot be represented
7743 // in the shorter type. Consequently, we cannot emit a simple comparison.
7744
7745 // First, handle some easy cases. We know the result cannot be equal at this
7746 // point so handle the ICI.isEquality() cases
7747 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Chris Lattner4de84762010-01-04 07:02:48 +00007748 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007749 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Chris Lattner4de84762010-01-04 07:02:48 +00007750 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(ICI.getContext()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007751
7752 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7753 // should have been folded away previously and not enter in here.
7754 Value *Result;
7755 if (isSignedCmp) {
7756 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007757 if (cast<ConstantInt>(CI)->getValue().isNegative())
Chris Lattner4de84762010-01-04 07:02:48 +00007758 Result = ConstantInt::getFalse(ICI.getContext()); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007759 else
Chris Lattner4de84762010-01-04 07:02:48 +00007760 Result = ConstantInt::getTrue(ICI.getContext()); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007761 } else {
7762 // We're performing an unsigned comparison.
7763 if (isSignedExt) {
7764 // We're performing an unsigned comp with a sign extended value.
7765 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007766 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007767 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007768 } else {
7769 // Unsigned extend & unsigned compare -> always true.
Chris Lattner4de84762010-01-04 07:02:48 +00007770 Result = ConstantInt::getTrue(ICI.getContext());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007771 }
7772 }
7773
7774 // Finally, return the value computed.
7775 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007776 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007777 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007778
7779 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7780 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7781 "ICmp should be folded!");
7782 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007783 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007784 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007785}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007786
Reid Spencer832254e2007-02-02 02:16:23 +00007787Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7788 return commonShiftTransforms(I);
7789}
7790
7791Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7792 return commonShiftTransforms(I);
7793}
7794
7795Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007796 if (Instruction *R = commonShiftTransforms(I))
7797 return R;
7798
7799 Value *Op0 = I.getOperand(0);
7800
7801 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7802 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7803 if (CSI->isAllOnesValue())
7804 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007805
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007806 // See if we can turn a signed shr into an unsigned shr.
7807 if (MaskedValueIsZero(Op0,
7808 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7809 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7810
7811 // Arithmetic shifting an all-sign-bit value is a no-op.
7812 unsigned NumSignBits = ComputeNumSignBits(Op0);
7813 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7814 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007815
Chris Lattner348f6652007-12-06 01:59:46 +00007816 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007817}
7818
7819Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7820 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007822
7823 // shl X, 0 == X and shr X, 0 == X
7824 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007825 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7826 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007827 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007828
Reid Spencere4d87aa2006-12-23 06:05:41 +00007829 if (isa<UndefValue>(Op0)) {
7830 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007831 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007832 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007834 }
7835 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007836 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7837 return ReplaceInstUsesWith(I, Op0);
7838 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007840 }
7841
Dan Gohman9004c8a2009-05-21 02:28:33 +00007842 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007843 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007844 return &I;
7845
Chris Lattner2eefe512004-04-09 19:05:30 +00007846 // Try to fold constant and into select arguments.
7847 if (isa<Constant>(Op0))
7848 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007850 return R;
7851
Reid Spencerb83eb642006-10-20 07:07:24 +00007852 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007853 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7854 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007855 return 0;
7856}
7857
Reid Spencerb83eb642006-10-20 07:07:24 +00007858Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007859 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007860 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007861
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007862 // See if we can simplify any instructions used by the instruction whose sole
7863 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007864 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007865
Dan Gohmana119de82009-06-14 23:30:43 +00007866 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7867 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007868 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007869 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007870 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007871 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007872 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007873 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007874 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007875 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007876 }
7877
7878 // ((X*C1) << C2) == (X * (C1 << C2))
7879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7880 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7881 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007882 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007883 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007884
7885 // Try to fold constant and into select arguments.
7886 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7887 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7888 return R;
7889 if (isa<PHINode>(Op0))
7890 if (Instruction *NV = FoldOpIntoPhi(I))
7891 return NV;
7892
Chris Lattner8999dd32007-12-22 09:07:47 +00007893 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7894 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7895 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7896 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7897 // place. Don't try to do this transformation in this case. Also, we
7898 // require that the input operand is a shift-by-constant so that we have
7899 // confidence that the shifts will get folded together. We could do this
7900 // xform in more cases, but it is unlikely to be profitable.
7901 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7902 isa<ConstantInt>(TrOp->getOperand(1))) {
7903 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007904 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007905 // (shift2 (shift1 & 0x00FF), c2)
7906 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007907
7908 // For logical shifts, the truncation has the effect of making the high
7909 // part of the register be zeros. Emulate this by inserting an AND to
7910 // clear the top bits as needed. This 'and' will usually be zapped by
7911 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007912 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7913 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007914 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7915
7916 // The mask we constructed says what the trunc would do if occurring
7917 // between the shifts. We want to know the effect *after* the second
7918 // shift. We know that it is a logical shift by a constant, so adjust the
7919 // mask as appropriate.
7920 if (I.getOpcode() == Instruction::Shl)
7921 MaskV <<= Op1->getZExtValue();
7922 else {
7923 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7924 MaskV = MaskV.lshr(Op1->getZExtValue());
7925 }
7926
Chris Lattner74381062009-08-30 07:44:24 +00007927 // shift1 & 0x00FF
Chris Lattner4de84762010-01-04 07:02:48 +00007928 Value *And = Builder->CreateAnd(NSh,
7929 ConstantInt::get(I.getContext(), MaskV),
Chris Lattner74381062009-08-30 07:44:24 +00007930 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007931
7932 // Return the value truncated to the interesting size.
7933 return new TruncInst(And, I.getType());
7934 }
7935 }
7936
Chris Lattner4d5542c2006-01-06 07:12:35 +00007937 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007938 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7939 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7940 Value *V1, *V2;
7941 ConstantInt *CC;
7942 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007943 default: break;
7944 case Instruction::Add:
7945 case Instruction::And:
7946 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007947 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007948 // These operators commute.
7949 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007950 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007951 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007952 m_Specific(Op1)))) {
7953 Value *YS = // (Y << C)
7954 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7955 // (X + (Y << C))
7956 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7957 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007958 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00007959 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00007960 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007961 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007962
Chris Lattner150f12a2005-09-18 06:30:59 +00007963 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007964 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007965 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007966 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007967 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007968 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007969 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007970 Value *YS = // (Y << C)
7971 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7972 Op0BO->getName());
7973 // X & (CC << C)
7974 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7975 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007976 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007977 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007978 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007979
Reid Spencera07cb7d2007-02-02 14:41:37 +00007980 // FALL THROUGH.
7981 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007982 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007983 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007984 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007985 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007986 Value *YS = // (Y << C)
7987 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7988 // (X + (Y << C))
7989 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7990 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007991 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Chris Lattner4de84762010-01-04 07:02:48 +00007992 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
Zhou Sheng90b96812007-03-30 05:45:18 +00007993 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007994 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007995
Chris Lattner13d4ab42006-05-31 21:14:00 +00007996 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007997 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7998 match(Op0BO->getOperand(0),
7999 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008000 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00008001 cast<BinaryOperator>(Op0BO->getOperand(0))
8002 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008003 Value *YS = // (Y << C)
8004 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8005 // X & (CC << C)
8006 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8007 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00008008
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008009 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00008010 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008011
Chris Lattner11021cb2005-09-18 05:12:10 +00008012 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00008013 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008014 }
8015
8016
8017 // If the operand is an bitwise operator with a constant RHS, and the
8018 // shift is the only use, we can pull it out of the shift.
8019 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
8020 bool isValid = true; // Valid only for And, Or, Xor
8021 bool highBitSet = false; // Transform if high bit of constant set?
8022
8023 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00008024 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00008025 case Instruction::Add:
8026 isValid = isLeftShift;
8027 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00008028 case Instruction::Or:
8029 case Instruction::Xor:
8030 highBitSet = false;
8031 break;
8032 case Instruction::And:
8033 highBitSet = true;
8034 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008035 }
8036
8037 // If this is a signed shift right, and the high bit is modified
8038 // by the logical operation, do not perform the transformation.
8039 // The highBitSet boolean indicates the value of the high bit of
8040 // the constant which would cause it to be modified for this
8041 // operation.
8042 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00008043 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00008044 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008045
8046 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008047 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008048
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008049 Value *NewShift =
8050 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00008051 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008052
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008053 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00008054 NewRHS);
8055 }
8056 }
8057 }
8058 }
8059
Chris Lattnerad0124c2006-01-06 07:52:12 +00008060 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00008061 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8062 if (ShiftOp && !ShiftOp->isShift())
8063 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008064
Reid Spencerb83eb642006-10-20 07:07:24 +00008065 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008066 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008067 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8068 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008069 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8070 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8071 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00008072
Zhou Sheng4351c642007-04-02 08:20:41 +00008073 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00008074
8075 const IntegerType *Ty = cast<IntegerType>(I.getType());
8076
8077 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00008078 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008079 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8080 // saturates.
8081 if (AmtSum >= TypeBits) {
8082 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00008083 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008084 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8085 }
8086
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008087 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00008088 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008089 }
8090
8091 if (ShiftOp->getOpcode() == Instruction::LShr &&
8092 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008093 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00008094 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008095
Chris Lattnerb87056f2007-02-05 00:57:54 +00008096 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00008097 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008098 }
8099
8100 if (ShiftOp->getOpcode() == Instruction::AShr &&
8101 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00008102 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00008103 if (AmtSum >= TypeBits)
8104 AmtSum = TypeBits-1;
8105
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008106 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008107
Zhou Shenge9e03f62007-03-28 15:02:20 +00008108 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Chris Lattner4de84762010-01-04 07:02:48 +00008109 return BinaryOperator::CreateAnd(Shift,
8110 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008111 }
8112
Chris Lattnerb87056f2007-02-05 00:57:54 +00008113 // Okay, if we get here, one shift must be left, and the other shift must be
8114 // right. See if the amounts are equal.
8115 if (ShiftAmt1 == ShiftAmt2) {
8116 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8117 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00008118 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00008119 return BinaryOperator::CreateAnd(X,
8120 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008121 }
8122 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8123 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00008124 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Chris Lattner4de84762010-01-04 07:02:48 +00008125 return BinaryOperator::CreateAnd(X,
8126 ConstantInt::get(I.getContext(), Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008127 }
8128 // We can simplify ((X << C) >>s C) into a trunc + sext.
8129 // NOTE: we could do this for any C, but that would make 'unusual' integer
8130 // types. For now, just stick to ones well-supported by the code
8131 // generators.
8132 const Type *SExtType = 0;
8133 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00008134 case 1 :
8135 case 8 :
8136 case 16 :
8137 case 32 :
8138 case 64 :
8139 case 128:
Chris Lattner4de84762010-01-04 07:02:48 +00008140 SExtType = IntegerType::get(I.getContext(),
8141 Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00008142 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008143 default: break;
8144 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008145 if (SExtType)
8146 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008147 // Otherwise, we can't handle it yet.
8148 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00008149 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008150
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008151 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008152 if (I.getOpcode() == Instruction::Shl) {
8153 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8154 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008155 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00008156
Reid Spencer55702aa2007-03-25 21:11:44 +00008157 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008158 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00008159 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008160 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008161
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008162 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008163 if (I.getOpcode() == Instruction::LShr) {
8164 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008165 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008166
Reid Spencerd5e30f02007-03-26 17:18:58 +00008167 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008168 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00008169 ConstantInt::get(I.getContext(),Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00008170 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008171
8172 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8173 } else {
8174 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00008175 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008176
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008177 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008178 if (I.getOpcode() == Instruction::Shl) {
8179 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8180 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008181 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8182 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008183
Reid Spencer55702aa2007-03-25 21:11:44 +00008184 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008185 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00008186 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008187 }
8188
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008189 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008190 if (I.getOpcode() == Instruction::LShr) {
8191 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008192 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008193
Reid Spencer68d27cf2007-03-26 23:45:51 +00008194 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008195 return BinaryOperator::CreateAnd(Shift,
Chris Lattner4de84762010-01-04 07:02:48 +00008196 ConstantInt::get(I.getContext(),Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008197 }
8198
8199 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008200 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00008201 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00008202 return 0;
8203}
8204
Chris Lattnera1be5662002-05-02 17:06:02 +00008205
Chris Lattnercfd65102005-10-29 04:36:15 +00008206/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8207/// expression. If so, decompose it, returning some value X, such that Val is
8208/// X*Scale+Offset.
8209///
8210static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Chris Lattner4de84762010-01-04 07:02:48 +00008211 int &Offset) {
8212 assert(Val->getType() == Type::getInt32Ty(Val->getContext()) &&
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008213 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00008214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008215 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00008216 Scale = 0;
Chris Lattner4de84762010-01-04 07:02:48 +00008217 return ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00008218 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8219 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8220 if (I->getOpcode() == Instruction::Shl) {
8221 // This is a value scaled by '1 << the shift amt'.
8222 Scale = 1U << RHS->getZExtValue();
8223 Offset = 0;
8224 return I->getOperand(0);
8225 } else if (I->getOpcode() == Instruction::Mul) {
8226 // This value is scaled by 'RHS'.
8227 Scale = RHS->getZExtValue();
8228 Offset = 0;
8229 return I->getOperand(0);
8230 } else if (I->getOpcode() == Instruction::Add) {
8231 // We have X+C. Check to see if we really have (X*C2)+C1,
8232 // where C1 is divisible by C2.
8233 unsigned SubScale;
8234 Value *SubVal =
Chris Lattner4de84762010-01-04 07:02:48 +00008235 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
Chris Lattner6a94de22007-10-12 05:30:59 +00008236 Offset += RHS->getZExtValue();
8237 Scale = SubScale;
8238 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00008239 }
8240 }
8241 }
8242
8243 // Otherwise, we can't look past this.
8244 Scale = 1;
8245 Offset = 0;
8246 return Val;
8247}
8248
8249
Chris Lattnerb3f83972005-10-24 06:03:58 +00008250/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8251/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008252Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00008253 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008254 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00008255
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008256 BuilderTy AllocaBuilder(*Builder);
8257 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8258
Chris Lattnerb53c2382005-10-24 06:22:12 +00008259 // Remove any uses of AI that are dead.
8260 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008261
Chris Lattnerb53c2382005-10-24 06:22:12 +00008262 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8263 Instruction *User = cast<Instruction>(*UI++);
8264 if (isInstructionTriviallyDead(User)) {
8265 while (UI != E && *UI == User)
8266 ++UI; // If this instruction uses AI more than once, don't break UI.
8267
Chris Lattnerb53c2382005-10-24 06:22:12 +00008268 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008269 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008270 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008271 }
8272 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008273
8274 // This requires TargetData to get the alloca alignment and size information.
8275 if (!TD) return 0;
8276
Chris Lattnerb3f83972005-10-24 06:03:58 +00008277 // Get the type really allocated and the type casted to.
8278 const Type *AllocElTy = AI.getAllocatedType();
8279 const Type *CastElTy = PTy->getElementType();
8280 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008281
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008282 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8283 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008284 if (CastElTyAlign < AllocElTyAlign) return 0;
8285
Chris Lattner39387a52005-10-24 06:35:18 +00008286 // If the allocation has multiple uses, only promote it if we are strictly
8287 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008288 // same, we open the door to infinite loops of various kinds. (A reference
8289 // from a dbg.declare doesn't count as a use for this purpose.)
8290 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8291 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008292
Duncan Sands777d2302009-05-09 07:06:46 +00008293 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8294 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008295 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008296
Chris Lattner455fcc82005-10-29 03:19:53 +00008297 // See if we can satisfy the modulus by pulling a scale out of the array
8298 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008299 unsigned ArraySizeScale;
8300 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008301 Value *NumElements = // See if the array size is a decomposable linear expr.
Chris Lattner4de84762010-01-04 07:02:48 +00008302 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
Chris Lattnercfd65102005-10-29 04:36:15 +00008303
Chris Lattner455fcc82005-10-29 03:19:53 +00008304 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8305 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008306 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8307 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008308
Chris Lattner455fcc82005-10-29 03:19:53 +00008309 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8310 Value *Amt = 0;
8311 if (Scale == 1) {
8312 Amt = NumElements;
8313 } else {
Chris Lattner4de84762010-01-04 07:02:48 +00008314 Amt = ConstantInt::get(Type::getInt32Ty(CI.getContext()), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008315 // Insert before the alloca, not before the cast.
8316 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008317 }
8318
Jeff Cohen86796be2007-04-04 16:58:57 +00008319 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Chris Lattner4de84762010-01-04 07:02:48 +00008320 Value *Off = ConstantInt::get(Type::getInt32Ty(CI.getContext()),
8321 Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008322 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008323 }
8324
Victor Hernandez7b929da2009-10-23 21:09:37 +00008325 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008326 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008327 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008328
Dale Johannesena0a66372009-03-05 00:39:02 +00008329 // If the allocation has one real use plus a dbg.declare, just remove the
8330 // declare.
8331 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8332 EraseInstFromFunction(*DI);
8333 }
8334 // If the allocation has multiple real uses, insert a cast and change all
8335 // things that used it to use the new cast. This will also hack on CI, but it
8336 // will die soon.
8337 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 // New is the allocation instruction, pointer typed. AI is the original
8339 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008340 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008341 AI.replaceAllUsesWith(NewCast);
8342 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008343 return ReplaceInstUsesWith(CI, New);
8344}
8345
Chris Lattner70074e02006-05-13 02:06:03 +00008346/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008347/// and return it as type Ty without inserting any new casts and without
8348/// changing the computed value. This is used by code that tries to decide
8349/// whether promoting or shrinking integer operations to wider or smaller types
8350/// will allow us to eliminate a truncate or extend.
8351///
8352/// This is a truncation operation if Ty is smaller than V->getType(), or an
8353/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008354///
8355/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8356/// should return true if trunc(V) can be computed by computing V in the smaller
8357/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8358/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8359/// efficiently truncated.
8360///
8361/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8362/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8363/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008364bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008365 unsigned CastOpc,
8366 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008367 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008368 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008369 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008370
8371 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008372 if (!I) return false;
8373
Dan Gohman6de29f82009-06-15 22:12:54 +00008374 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008375
Chris Lattner951626b2007-08-02 06:11:14 +00008376 // If this is an extension or truncate, we can often eliminate it.
8377 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8378 // If this is a cast from the destination type, we can trivially eliminate
8379 // it, and this will remove a cast overall.
8380 if (I->getOperand(0)->getType() == Ty) {
8381 // If the first operand is itself a cast, and is eliminable, do not count
8382 // this as an eliminable cast. We would prefer to eliminate those two
8383 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008384 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008385 ++NumCastsRemoved;
8386 return true;
8387 }
8388 }
8389
8390 // We can't extend or shrink something that has multiple uses: doing so would
8391 // require duplicating the instruction in general, which isn't profitable.
8392 if (!I->hasOneUse()) return false;
8393
Evan Chengf35fd542009-01-15 17:01:23 +00008394 unsigned Opc = I->getOpcode();
8395 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008396 case Instruction::Add:
8397 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008398 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008399 case Instruction::And:
8400 case Instruction::Or:
8401 case Instruction::Xor:
8402 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008403 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008404 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008405 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008406 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008407
Eli Friedman070a9812009-07-13 22:46:01 +00008408 case Instruction::UDiv:
8409 case Instruction::URem: {
8410 // UDiv and URem can be truncated if all the truncated bits are zero.
8411 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8412 uint32_t BitWidth = Ty->getScalarSizeInBits();
8413 if (BitWidth < OrigBitWidth) {
8414 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8415 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8416 MaskedValueIsZero(I->getOperand(1), Mask)) {
8417 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8418 NumCastsRemoved) &&
8419 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8420 NumCastsRemoved);
8421 }
8422 }
8423 break;
8424 }
Chris Lattner46b96052006-11-29 07:18:39 +00008425 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008426 // If we are truncating the result of this SHL, and if it's a shift of a
8427 // constant amount, we can always perform a SHL in a smaller type.
8428 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008429 uint32_t BitWidth = Ty->getScalarSizeInBits();
8430 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008431 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008432 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008433 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008434 }
8435 break;
8436 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008437 // If this is a truncate of a logical shr, we can truncate it to a smaller
8438 // lshr iff we know that the bits we would otherwise be shifting in are
8439 // already zeros.
8440 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008441 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8442 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008443 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008444 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008445 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8446 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008447 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008448 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008449 }
8450 }
Chris Lattner46b96052006-11-29 07:18:39 +00008451 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008452 case Instruction::ZExt:
8453 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008454 case Instruction::Trunc:
8455 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008456 // can safely replace it. Note that replacing it does not reduce the number
8457 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008458 if (Opc == CastOpc)
8459 return true;
8460
8461 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008462 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008463 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008464 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008465 case Instruction::Select: {
8466 SelectInst *SI = cast<SelectInst>(I);
8467 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008468 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008469 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008470 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008471 }
Chris Lattner8114b712008-06-18 04:00:49 +00008472 case Instruction::PHI: {
8473 // We can change a phi if we can change all operands.
8474 PHINode *PN = cast<PHINode>(I);
8475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8476 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008477 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008478 return false;
8479 return true;
8480 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008481 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008482 // TODO: Can handle more cases here.
8483 break;
8484 }
8485
8486 return false;
8487}
8488
8489/// EvaluateInDifferentType - Given an expression that
8490/// CanEvaluateInDifferentType returns true for, actually insert the code to
8491/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008492Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008493 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008494 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008495 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008496
8497 // Otherwise, it must be an instruction.
8498 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008499 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008500 unsigned Opc = I->getOpcode();
8501 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008502 case Instruction::Add:
8503 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008504 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008505 case Instruction::And:
8506 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008507 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008508 case Instruction::AShr:
8509 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008510 case Instruction::Shl:
8511 case Instruction::UDiv:
8512 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008513 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008514 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008515 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008516 break;
8517 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008518 case Instruction::Trunc:
8519 case Instruction::ZExt:
8520 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008521 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008522 // just return the source. There's no need to insert it because it is not
8523 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008524 if (I->getOperand(0)->getType() == Ty)
8525 return I->getOperand(0);
8526
Chris Lattner8114b712008-06-18 04:00:49 +00008527 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008528 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008529 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008530 case Instruction::Select: {
8531 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8532 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8533 Res = SelectInst::Create(I->getOperand(0), True, False);
8534 break;
8535 }
Chris Lattner8114b712008-06-18 04:00:49 +00008536 case Instruction::PHI: {
8537 PHINode *OPN = cast<PHINode>(I);
8538 PHINode *NPN = PHINode::Create(Ty);
8539 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8540 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8541 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8542 }
8543 Res = NPN;
8544 break;
8545 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008546 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008547 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008548 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008549 break;
8550 }
8551
Chris Lattner8114b712008-06-18 04:00:49 +00008552 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008553 return InsertNewInstBefore(Res, *I);
8554}
8555
Reid Spencer3da59db2006-11-27 01:05:10 +00008556/// @brief Implement the transforms common to all CastInst visitors.
8557Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008558 Value *Src = CI.getOperand(0);
8559
Dan Gohman23d9d272007-05-11 21:10:54 +00008560 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008561 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008562 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008563 if (Instruction::CastOps opc =
8564 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8565 // The first cast (CSrc) is eliminable so we need to fix up or replace
8566 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008567 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008568 }
8569 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008570
Reid Spencer3da59db2006-11-27 01:05:10 +00008571 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008572 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8573 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8574 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008575
8576 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008577 if (isa<PHINode>(Src)) {
8578 // We don't do this if this would create a PHI node with an illegal type if
8579 // it is currently legal.
8580 if (!isa<IntegerType>(Src->getType()) ||
8581 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008582 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008583 if (Instruction *NV = FoldOpIntoPhi(CI))
8584 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008585 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008586
Reid Spencer3da59db2006-11-27 01:05:10 +00008587 return 0;
8588}
8589
Chris Lattner46cd5a12009-01-09 05:44:56 +00008590/// FindElementAtOffset - Given a type and a constant offset, determine whether
8591/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008592/// the specified offset. If so, fill them into NewIndices and return the
8593/// resultant element type, otherwise return null.
8594static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8595 SmallVectorImpl<Value*> &NewIndices,
Chris Lattner4de84762010-01-04 07:02:48 +00008596 const TargetData *TD) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008597 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008598 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008599
8600 // Start with the index over the outer type. Note that the type size
8601 // might be zero (even if the offset isn't zero) if the indexed type
8602 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +00008603 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008604 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008605 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008606 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008607 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008608
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008609 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008610 if (Offset < 0) {
8611 --FirstIdx;
8612 Offset += TySize;
8613 assert(Offset >= 0);
8614 }
8615 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8616 }
8617
Owen Andersoneed707b2009-07-24 23:12:02 +00008618 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008619
8620 // Index into the types. If we fail, set OrigBase to null.
8621 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008622 // Indexing into tail padding between struct/array elements.
8623 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008624 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008625
Chris Lattner46cd5a12009-01-09 05:44:56 +00008626 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8627 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008628 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8629 "Offset must stay within the indexed type");
8630
Chris Lattner46cd5a12009-01-09 05:44:56 +00008631 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +00008632 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
8633 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008634
8635 Offset -= SL->getElementOffset(Elt);
8636 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008637 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008638 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008639 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008640 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008641 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008642 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008643 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008644 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008645 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008646 }
8647 }
8648
Chris Lattner3914f722009-01-24 01:00:13 +00008649 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008650}
8651
Chris Lattnerd3e28342007-04-27 17:44:50 +00008652/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8653Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8654 Value *Src = CI.getOperand(0);
8655
Chris Lattnerd3e28342007-04-27 17:44:50 +00008656 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008657 // If casting the result of a getelementptr instruction with no offset, turn
8658 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008659 if (GEP->hasAllZeroIndices()) {
8660 // Changing the cast operand is usually not a good idea but it is safe
8661 // here because the pointer operand is being replaced with another
8662 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008663 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008664 CI.setOperand(0, GEP->getOperand(0));
8665 return &CI;
8666 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008667
8668 // If the GEP has a single use, and the base pointer is a bitcast, and the
8669 // GEP computes a constant offset, see if we can convert these three
8670 // instructions into fewer. This typically happens with unions and other
8671 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008672 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008673 if (GEP->hasAllConstantIndices()) {
8674 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008675 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008676 int64_t Offset = OffsetV->getSExtValue();
8677
8678 // Get the base pointer input of the bitcast, and the type it points to.
8679 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8680 const Type *GEPIdxTy =
8681 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008682 SmallVector<Value*, 8> NewIndices;
Chris Lattner4de84762010-01-04 07:02:48 +00008683 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008684 // If we were able to index down into an element, create the GEP
8685 // and bitcast the result. This eliminates one bitcast, potentially
8686 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008687 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8688 Builder->CreateInBoundsGEP(OrigBase,
8689 NewIndices.begin(), NewIndices.end()) :
8690 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008691 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008692
Chris Lattner46cd5a12009-01-09 05:44:56 +00008693 if (isa<BitCastInst>(CI))
8694 return new BitCastInst(NGEP, CI.getType());
8695 assert(isa<PtrToIntInst>(CI));
8696 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008697 }
8698 }
8699 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008700 }
8701
8702 return commonCastTransforms(CI);
8703}
8704
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008705/// commonIntCastTransforms - This function implements the common transforms
8706/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008707Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8708 if (Instruction *Result = commonCastTransforms(CI))
8709 return Result;
8710
8711 Value *Src = CI.getOperand(0);
8712 const Type *SrcTy = Src->getType();
8713 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008714 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8715 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008716
Reid Spencer3da59db2006-11-27 01:05:10 +00008717 // See if we can simplify any instructions used by the LHS whose sole
8718 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008719 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008720 return &CI;
8721
8722 // If the source isn't an instruction or has more than one use then we
8723 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008724 Instruction *SrcI = dyn_cast<Instruction>(Src);
8725 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008726 return 0;
8727
Chris Lattnerc739cd62007-03-03 05:27:34 +00008728 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008729 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008730 // Only do this if the dest type is a simple type, don't convert the
8731 // expression tree to something weird like i93 unless the source is also
8732 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008733 if ((isa<VectorType>(DestTy) ||
8734 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8735 CanEvaluateInDifferentType(SrcI, DestTy,
8736 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008737 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008738 // eliminates the cast, so it is always a win. If this is a zero-extension,
8739 // we need to do an AND to maintain the clear top-part of the computation,
8740 // so we require that the input have eliminated at least one cast. If this
8741 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008742 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008743 bool DoXForm = false;
8744 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008745 switch (CI.getOpcode()) {
8746 default:
8747 // All the others use floating point so we shouldn't actually
8748 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008749 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008750 case Instruction::Trunc:
8751 DoXForm = true;
8752 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008753 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008754 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008755
Chris Lattner39c27ed2009-01-31 19:05:27 +00008756 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008757 // If it's unnecessary to issue an AND to clear the high bits, it's
8758 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008759 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008760 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8761 if (MaskedValueIsZero(TryRes, Mask))
8762 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008763
8764 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008765 if (TryI->use_empty())
8766 EraseInstFromFunction(*TryI);
8767 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008768 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008769 }
Evan Chengf35fd542009-01-15 17:01:23 +00008770 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008771 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008772 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008773 // If we do not have to emit the truncate + sext pair, then it's always
8774 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008775 //
8776 // It's not safe to eliminate the trunc + sext pair if one of the
8777 // eliminated cast is a truncate. e.g.
8778 // t2 = trunc i32 t1 to i16
8779 // t3 = sext i16 t2 to i32
8780 // !=
8781 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008782 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008783 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8784 if (NumSignBits > (DestBitSize - SrcBitSize))
8785 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008786
8787 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008788 if (TryI->use_empty())
8789 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008790 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008791 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008792 }
Evan Chengf35fd542009-01-15 17:01:23 +00008793 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008794
8795 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008796 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8797 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008798 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8799 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008800 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008801 // Just replace this cast with the result.
8802 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008803
Reid Spencer3da59db2006-11-27 01:05:10 +00008804 assert(Res->getType() == DestTy);
8805 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008806 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008807 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008808 // Just replace this cast with the result.
8809 return ReplaceInstUsesWith(CI, Res);
8810 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008811 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008812
8813 // If the high bits are already zero, just replace this cast with the
8814 // result.
8815 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8816 if (MaskedValueIsZero(Res, Mask))
8817 return ReplaceInstUsesWith(CI, Res);
8818
8819 // We need to emit an AND to clear the high bits.
Chris Lattner4de84762010-01-04 07:02:48 +00008820 Constant *C = ConstantInt::get(CI.getContext(),
Owen Andersoneed707b2009-07-24 23:12:02 +00008821 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008822 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008823 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008824 case Instruction::SExt: {
8825 // If the high bits are already filled with sign bit, just replace this
8826 // cast with the result.
8827 unsigned NumSignBits = ComputeNumSignBits(Res);
8828 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008829 return ReplaceInstUsesWith(CI, Res);
8830
Reid Spencer3da59db2006-11-27 01:05:10 +00008831 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008832 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008833 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008834 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008835 }
8836 }
8837
8838 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8839 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8840
8841 switch (SrcI->getOpcode()) {
8842 case Instruction::Add:
8843 case Instruction::Mul:
8844 case Instruction::And:
8845 case Instruction::Or:
8846 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008847 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008848 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8849 // Don't insert two casts unless at least one can be eliminated.
8850 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008851 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008852 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8853 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008854 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008855 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008856 }
8857 }
8858
8859 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8860 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8861 SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner4de84762010-01-04 07:02:48 +00008862 Op1 == ConstantInt::getTrue(CI.getContext()) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008863 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008864 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008865 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008866 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008867 }
8868 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008869
Eli Friedman65445c52009-07-13 21:45:57 +00008870 case Instruction::Shl: {
8871 // Canonicalize trunc inside shl, if we can.
8872 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8873 if (CI && DestBitSize < SrcBitSize &&
8874 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008875 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8876 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008877 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008878 }
8879 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008880 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008881 }
8882 return 0;
8883}
8884
Chris Lattner8a9f5712007-04-11 06:57:46 +00008885Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008886 if (Instruction *Result = commonIntCastTransforms(CI))
8887 return Result;
8888
8889 Value *Src = CI.getOperand(0);
8890 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008891 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8892 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008893
8894 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008895 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008896 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008897 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008898 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008899 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008900 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008901
Chris Lattner4f9797d2009-03-24 18:15:30 +00008902 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8903 ConstantInt *ShAmtV = 0;
8904 Value *ShiftOp = 0;
8905 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008906 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008907 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8908
8909 // Get a mask for the bits shifting in.
8910 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8911 if (MaskedValueIsZero(ShiftOp, Mask)) {
8912 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008913 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008914
8915 // Okay, we can shrink this. Truncate the input, then return a new
8916 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008917 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008918 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008919 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008920 }
8921 }
Chris Lattner9956c052009-11-08 19:23:30 +00008922
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008923 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008924}
8925
Evan Chengb98a10e2008-03-24 00:21:34 +00008926/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8927/// in order to eliminate the icmp.
8928Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8929 bool DoXform) {
8930 // If we are just checking for a icmp eq of a single bit and zext'ing it
8931 // to an integer, then shift the bit to the appropriate place and then
8932 // cast to integer to avoid the comparison.
8933 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8934 const APInt &Op1CV = Op1C->getValue();
8935
8936 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8937 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8938 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8939 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8940 if (!DoXform) return ICI;
8941
8942 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008943 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008944 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008945 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008946 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008947 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008948
8949 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008950 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008951 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008952 }
8953
8954 return ReplaceInstUsesWith(CI, In);
8955 }
8956
8957
8958
8959 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8960 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8961 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8962 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8963 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8964 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8965 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8966 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8967 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8968 // This only works for EQ and NE
8969 ICI->isEquality()) {
8970 // If Op1C some other power of two, convert:
8971 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8972 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8973 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8974 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8975
8976 APInt KnownZeroMask(~KnownZero);
8977 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8978 if (!DoXform) return ICI;
8979
8980 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8981 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8982 // (X&4) == 2 --> false
8983 // (X&4) != 2 --> true
Chris Lattner4de84762010-01-04 07:02:48 +00008984 Constant *Res = ConstantInt::get(Type::getInt1Ty(CI.getContext()),
8985 isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008986 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008987 return ReplaceInstUsesWith(CI, Res);
8988 }
8989
8990 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8991 Value *In = ICI->getOperand(0);
8992 if (ShiftAmt) {
8993 // Perform a logical shr by shiftamt.
8994 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008995 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8996 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008997 }
8998
8999 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00009000 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009001 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00009002 }
9003
9004 if (CI.getType() == In->getType())
9005 return ReplaceInstUsesWith(CI, In);
9006 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009007 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00009008 }
9009 }
9010 }
9011
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009012 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
9013 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
9014 // may lead to additional simplifications.
9015 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
9016 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
9017 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009018 Value *LHS = ICI->getOperand(0);
9019 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009020
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009021 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
9022 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
9023 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9024 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
9025 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009026
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009027 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
9028 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
9029 APInt UnknownBit = ~KnownBits;
9030 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009031 if (!DoXform) return ICI;
9032
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009033 Value *Result = Builder->CreateXor(LHS, RHS);
9034
9035 // Mask off any bits that are set and won't be shifted away.
9036 if (KnownOneLHS.uge(UnknownBit))
9037 Result = Builder->CreateAnd(Result,
9038 ConstantInt::get(ITy, UnknownBit));
9039
9040 // Shift the bit we're testing down to the lsb.
9041 Result = Builder->CreateLShr(
9042 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
9043
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009044 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009045 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
9046 Result->takeName(ICI);
9047 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009048 }
9049 }
9050 }
9051 }
9052
Evan Chengb98a10e2008-03-24 00:21:34 +00009053 return 0;
9054}
9055
Chris Lattner8a9f5712007-04-11 06:57:46 +00009056Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00009057 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00009058 if (Instruction *Result = commonIntCastTransforms(CI))
9059 return Result;
9060
9061 Value *Src = CI.getOperand(0);
9062
Chris Lattnera84f47c2009-02-17 20:47:23 +00009063 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9064 // types and if the sizes are just right we can convert this into a logical
9065 // 'and' which will be much cheaper than the pair of casts.
9066 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9067 // Get the sizes of the types involved. We know that the intermediate type
9068 // will be smaller than A or C, but don't know the relation between A and C.
9069 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009070 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9071 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9072 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00009073 // If we're actually extending zero bits, then if
9074 // SrcSize < DstSize: zext(a & mask)
9075 // SrcSize == DstSize: a & mask
9076 // SrcSize > DstSize: trunc(a) & mask
9077 if (SrcSize < DstSize) {
9078 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009079 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009080 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009081 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009082 }
9083
9084 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00009085 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009086 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009087 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009088 }
9089 if (SrcSize > DstSize) {
9090 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009091 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00009092 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00009093 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009094 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00009095 }
9096 }
9097
Evan Chengb98a10e2008-03-24 00:21:34 +00009098 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9099 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00009100
Evan Chengb98a10e2008-03-24 00:21:34 +00009101 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9102 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9103 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9104 // of the (zext icmp) will be transformed.
9105 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9106 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9107 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9108 (transformZExtICmp(LHS, CI, false) ||
9109 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009110 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9111 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009112 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00009113 }
Evan Chengb98a10e2008-03-24 00:21:34 +00009114 }
9115
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009116 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00009117 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9118 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9119 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9120 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009121 if (TI0->getType() == CI.getType())
9122 return
9123 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009124 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00009125 }
9126
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009127 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9128 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9129 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9130 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9131 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9132 And->getOperand(1) == C)
9133 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9134 Value *TI0 = TI->getOperand(0);
9135 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009136 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009137 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009138 return BinaryOperator::CreateXor(NewAnd, ZC);
9139 }
9140 }
9141
Reid Spencer3da59db2006-11-27 01:05:10 +00009142 return 0;
9143}
9144
Chris Lattner8a9f5712007-04-11 06:57:46 +00009145Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00009146 if (Instruction *I = commonIntCastTransforms(CI))
9147 return I;
9148
Chris Lattner8a9f5712007-04-11 06:57:46 +00009149 Value *Src = CI.getOperand(0);
9150
Dan Gohman1975d032008-10-30 20:40:10 +00009151 // Canonicalize sign-extend from i1 to a select.
Chris Lattner4de84762010-01-04 07:02:48 +00009152 if (Src->getType() == Type::getInt1Ty(CI.getContext()))
Dan Gohman1975d032008-10-30 20:40:10 +00009153 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00009154 Constant::getAllOnesValue(CI.getType()),
9155 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00009156
9157 // See if the value being truncated is already sign extended. If so, just
9158 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00009159 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00009160 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009161 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9162 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9163 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00009164 unsigned NumSignBits = ComputeNumSignBits(Op);
9165
9166 if (OpBits == DestBits) {
9167 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9168 // bits, it is already ready.
9169 if (NumSignBits > DestBits-MidBits)
9170 return ReplaceInstUsesWith(CI, Op);
9171 } else if (OpBits < DestBits) {
9172 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9173 // bits, just sext from i32.
9174 if (NumSignBits > OpBits-MidBits)
9175 return new SExtInst(Op, CI.getType(), "tmp");
9176 } else {
9177 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9178 // bits, just truncate to i32.
9179 if (NumSignBits > OpBits-MidBits)
9180 return new TruncInst(Op, CI.getType(), "tmp");
9181 }
9182 }
Chris Lattner46bbad22008-08-06 07:35:52 +00009183
9184 // If the input is a shl/ashr pair of a same constant, then this is a sign
9185 // extension from a smaller value. If we could trust arbitrary bitwidth
9186 // integers, we could turn this into a truncate to the smaller bit and then
9187 // use a sext for the whole extension. Since we don't, look deeper and check
9188 // for a truncate. If the source and dest are the same type, eliminate the
9189 // trunc and extend and just do shifts. For example, turn:
9190 // %a = trunc i32 %i to i8
9191 // %b = shl i8 %a, 6
9192 // %c = ashr i8 %b, 6
9193 // %d = sext i8 %c to i32
9194 // into:
9195 // %a = shl i32 %i, 30
9196 // %d = ashr i32 %a, 30
9197 Value *A = 0;
9198 ConstantInt *BA = 0, *CA = 0;
9199 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00009200 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00009201 BA == CA && isa<TruncInst>(A)) {
9202 Value *I = cast<TruncInst>(A)->getOperand(0);
9203 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009204 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9205 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00009206 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00009207 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009208 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00009209 return BinaryOperator::CreateAShr(I, ShAmtV);
9210 }
9211 }
9212
Chris Lattnerba417832007-04-11 06:12:58 +00009213 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009214}
9215
Chris Lattnerb7530652008-01-27 05:29:54 +00009216/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9217/// in the specified FP type without changing its value.
Chris Lattner4de84762010-01-04 07:02:48 +00009218static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00009219 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00009220 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00009221 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9222 if (!losesInfo)
Chris Lattner4de84762010-01-04 07:02:48 +00009223 return ConstantFP::get(CFP->getContext(), F);
Chris Lattnerb7530652008-01-27 05:29:54 +00009224 return 0;
9225}
9226
9227/// LookThroughFPExtensions - If this is an fp extension instruction, look
9228/// through it until we get the source value.
Chris Lattner4de84762010-01-04 07:02:48 +00009229static Value *LookThroughFPExtensions(Value *V) {
Chris Lattnerb7530652008-01-27 05:29:54 +00009230 if (Instruction *I = dyn_cast<Instruction>(V))
9231 if (I->getOpcode() == Instruction::FPExt)
Chris Lattner4de84762010-01-04 07:02:48 +00009232 return LookThroughFPExtensions(I->getOperand(0));
Chris Lattnerb7530652008-01-27 05:29:54 +00009233
9234 // If this value is a constant, return the constant in the smallest FP type
9235 // that can accurately represent it. This allows us to turn
9236 // (float)((double)X+2.0) into x+2.0f.
9237 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +00009238 if (CFP->getType() == Type::getPPC_FP128Ty(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00009239 return V; // No constant folding of this.
9240 // See if the value can be truncated to float and then reextended.
Chris Lattner4de84762010-01-04 07:02:48 +00009241 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00009242 return V;
Chris Lattner4de84762010-01-04 07:02:48 +00009243 if (CFP->getType() == Type::getDoubleTy(V->getContext()))
Chris Lattnerb7530652008-01-27 05:29:54 +00009244 return V; // Won't shrink.
Chris Lattner4de84762010-01-04 07:02:48 +00009245 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00009246 return V;
9247 // Don't try to shrink to various long double types.
9248 }
9249
9250 return V;
9251}
9252
9253Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9254 if (Instruction *I = commonCastTransforms(CI))
9255 return I;
9256
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009257 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00009258 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009259 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009260 // many builtins (sqrt, etc).
9261 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9262 if (OpI && OpI->hasOneUse()) {
9263 switch (OpI->getOpcode()) {
9264 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009265 case Instruction::FAdd:
9266 case Instruction::FSub:
9267 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009268 case Instruction::FDiv:
9269 case Instruction::FRem:
9270 const Type *SrcTy = OpI->getType();
Chris Lattner4de84762010-01-04 07:02:48 +00009271 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
9272 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
Chris Lattnerb7530652008-01-27 05:29:54 +00009273 if (LHSTrunc->getType() != SrcTy &&
9274 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009275 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009276 // If the source types were both smaller than the destination type of
9277 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009278 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9279 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009280 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9281 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009282 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009283 }
9284 }
9285 break;
9286 }
9287 }
9288 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009289}
9290
9291Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9292 return commonCastTransforms(CI);
9293}
9294
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009295Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009296 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9297 if (OpI == 0)
9298 return commonCastTransforms(FI);
9299
9300 // fptoui(uitofp(X)) --> X
9301 // fptoui(sitofp(X)) --> X
9302 // This is safe if the intermediate type has enough bits in its mantissa to
9303 // accurately represent all values of X. For example, do not do this with
9304 // i64->float->i64. This is also safe for sitofp case, because any negative
9305 // 'X' value would cause an undefined result for the fptoui.
9306 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9307 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009308 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009309 OpI->getType()->getFPMantissaWidth())
9310 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009311
9312 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009313}
9314
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009315Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009316 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9317 if (OpI == 0)
9318 return commonCastTransforms(FI);
9319
9320 // fptosi(sitofp(X)) --> X
9321 // fptosi(uitofp(X)) --> X
9322 // This is safe if the intermediate type has enough bits in its mantissa to
9323 // accurately represent all values of X. For example, do not do this with
9324 // i64->float->i64. This is also safe for sitofp case, because any negative
9325 // 'X' value would cause an undefined result for the fptoui.
9326 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9327 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009328 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009329 OpI->getType()->getFPMantissaWidth())
9330 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009331
9332 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009333}
9334
9335Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9336 return commonCastTransforms(CI);
9337}
9338
9339Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9340 return commonCastTransforms(CI);
9341}
9342
Chris Lattnera0e69692009-03-24 18:35:40 +00009343Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9344 // If the destination integer type is smaller than the intptr_t type for
9345 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9346 // trunc to be exposed to other transforms. Don't do this for extending
9347 // ptrtoint's, because we don't know if the target sign or zero extends its
9348 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009349 if (TD &&
9350 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009351 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9352 TD->getIntPtrType(CI.getContext()),
9353 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009354 return new TruncInst(P, CI.getType());
9355 }
9356
Chris Lattnerd3e28342007-04-27 17:44:50 +00009357 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009358}
9359
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009360Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009361 // If the source integer type is larger than the intptr_t type for
9362 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9363 // allows the trunc to be exposed to other transforms. Don't do this for
9364 // extending inttoptr's, because we don't know if the target sign or zero
9365 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009366 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009367 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009368 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9369 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009370 return new IntToPtrInst(P, CI.getType());
9371 }
9372
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009373 if (Instruction *I = commonCastTransforms(CI))
9374 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009375
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009376 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009377}
9378
Chris Lattnerd3e28342007-04-27 17:44:50 +00009379Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009380 // If the operands are integer typed then apply the integer transforms,
9381 // otherwise just apply the common ones.
9382 Value *Src = CI.getOperand(0);
9383 const Type *SrcTy = Src->getType();
9384 const Type *DestTy = CI.getType();
9385
Eli Friedman7e25d452009-07-13 20:53:00 +00009386 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009387 if (Instruction *I = commonPointerCastTransforms(CI))
9388 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009389 } else {
9390 if (Instruction *Result = commonCastTransforms(CI))
9391 return Result;
9392 }
9393
9394
9395 // Get rid of casts from one type to the same type. These are useless and can
9396 // be replaced by the operand.
9397 if (DestTy == Src->getType())
9398 return ReplaceInstUsesWith(CI, Src);
9399
Reid Spencer3da59db2006-11-27 01:05:10 +00009400 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009401 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9402 const Type *DstElTy = DstPTy->getElementType();
9403 const Type *SrcElTy = SrcPTy->getElementType();
9404
Nate Begeman83ad90a2008-03-31 00:22:16 +00009405 // If the address spaces don't match, don't eliminate the bitcast, which is
9406 // required for changing types.
9407 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9408 return 0;
9409
Victor Hernandez83d63912009-09-18 22:35:49 +00009410 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009411 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009412 // There is no need to modify malloc calls because it is their bitcast that
9413 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009414 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009415 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9416 return V;
9417
Chris Lattnerd717c182007-05-05 22:32:24 +00009418 // If the source and destination are pointers, and this cast is equivalent
9419 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009420 // This can enhance SROA and other transforms that want type-safe pointers.
Chris Lattner4de84762010-01-04 07:02:48 +00009421 Constant *ZeroUInt =
9422 Constant::getNullValue(Type::getInt32Ty(CI.getContext()));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009423 unsigned NumZeros = 0;
9424 while (SrcElTy != DstElTy &&
9425 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9426 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9427 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9428 ++NumZeros;
9429 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009430
Chris Lattnerd3e28342007-04-27 17:44:50 +00009431 // If we found a path from the src to dest, create the getelementptr now.
9432 if (SrcElTy == DstElTy) {
9433 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chris Lattner4de84762010-01-04 07:02:48 +00009434 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(),"",
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009435 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009436 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009437 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009438
Eli Friedman2451a642009-07-18 23:06:53 +00009439 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9440 if (DestVTy->getNumElements() == 1) {
9441 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009442 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009443 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner4de84762010-01-04 07:02:48 +00009444 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00009445 }
9446 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9447 }
9448 }
9449
9450 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9451 if (SrcVTy->getNumElements() == 1) {
9452 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009453 Value *Elem =
9454 Builder->CreateExtractElement(Src,
Chris Lattner4de84762010-01-04 07:02:48 +00009455 Constant::getNullValue(Type::getInt32Ty(CI.getContext())));
Eli Friedman2451a642009-07-18 23:06:53 +00009456 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9457 }
9458 }
9459 }
9460
Reid Spencer3da59db2006-11-27 01:05:10 +00009461 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9462 if (SVI->hasOneUse()) {
9463 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9464 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009465 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009466 cast<VectorType>(DestTy)->getNumElements() ==
9467 SVI->getType()->getNumElements() &&
9468 SVI->getType()->getNumElements() ==
9469 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009470 CastInst *Tmp;
9471 // If either of the operands is a cast from CI.getType(), then
9472 // evaluating the shuffle in the casted destination's type will allow
9473 // us to eliminate at least one cast.
9474 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9475 Tmp->getOperand(0)->getType() == DestTy) ||
9476 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9477 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009478 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9479 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009480 // Return a new shuffle vector. Use the same element ID's, as we
9481 // know the vector types match #elts.
9482 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009483 }
9484 }
9485 }
9486 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009487 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009488}
9489
Chris Lattnere576b912004-04-09 23:46:01 +00009490/// GetSelectFoldableOperands - We want to turn code that looks like this:
9491/// %C = or %A, %B
9492/// %D = select %cond, %C, %A
9493/// into:
9494/// %C = select %cond, %B, 0
9495/// %D = or %A, %C
9496///
9497/// Assuming that the specified instruction is an operand to the select, return
9498/// a bitmask indicating which operands of this instruction are foldable if they
9499/// equal the other incoming value of the select.
9500///
9501static unsigned GetSelectFoldableOperands(Instruction *I) {
9502 switch (I->getOpcode()) {
9503 case Instruction::Add:
9504 case Instruction::Mul:
9505 case Instruction::And:
9506 case Instruction::Or:
9507 case Instruction::Xor:
9508 return 3; // Can fold through either operand.
9509 case Instruction::Sub: // Can only fold on the amount subtracted.
9510 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009511 case Instruction::LShr:
9512 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009513 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009514 default:
9515 return 0; // Cannot fold
9516 }
9517}
9518
9519/// GetSelectFoldableConstant - For the same transformation as the previous
9520/// function, return the identity constant that goes into the select.
Chris Lattner4de84762010-01-04 07:02:48 +00009521static Constant *GetSelectFoldableConstant(Instruction *I) {
Chris Lattnere576b912004-04-09 23:46:01 +00009522 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009523 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009524 case Instruction::Add:
9525 case Instruction::Sub:
9526 case Instruction::Or:
9527 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009528 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009529 case Instruction::LShr:
9530 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009531 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009532 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009533 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009534 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009535 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009536 }
9537}
9538
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009539/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9540/// have the same opcode and only one use each. Try to simplify this.
9541Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9542 Instruction *FI) {
9543 if (TI->getNumOperands() == 1) {
9544 // If this is a non-volatile load or a cast from the same type,
9545 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009546 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009547 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9548 return 0;
9549 } else {
9550 return 0; // unknown unary op.
9551 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009552
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009553 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009554 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009555 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009556 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009557 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009558 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009559 }
9560
Reid Spencer832254e2007-02-02 02:16:23 +00009561 // Only handle binary operators here.
9562 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009563 return 0;
9564
9565 // Figure out if the operations have any operands in common.
9566 Value *MatchOp, *OtherOpT, *OtherOpF;
9567 bool MatchIsOpZero;
9568 if (TI->getOperand(0) == FI->getOperand(0)) {
9569 MatchOp = TI->getOperand(0);
9570 OtherOpT = TI->getOperand(1);
9571 OtherOpF = FI->getOperand(1);
9572 MatchIsOpZero = true;
9573 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9574 MatchOp = TI->getOperand(1);
9575 OtherOpT = TI->getOperand(0);
9576 OtherOpF = FI->getOperand(0);
9577 MatchIsOpZero = false;
9578 } else if (!TI->isCommutative()) {
9579 return 0;
9580 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9581 MatchOp = TI->getOperand(0);
9582 OtherOpT = TI->getOperand(1);
9583 OtherOpF = FI->getOperand(0);
9584 MatchIsOpZero = true;
9585 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9586 MatchOp = TI->getOperand(1);
9587 OtherOpT = TI->getOperand(0);
9588 OtherOpF = FI->getOperand(1);
9589 MatchIsOpZero = true;
9590 } else {
9591 return 0;
9592 }
9593
9594 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009595 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9596 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009597 InsertNewInstBefore(NewSI, SI);
9598
9599 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9600 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009601 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009602 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009603 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009604 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009605 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009606 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009607}
9608
Evan Chengde621922009-03-31 20:42:45 +00009609static bool isSelect01(Constant *C1, Constant *C2) {
9610 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9611 if (!C1I)
9612 return false;
9613 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9614 if (!C2I)
9615 return false;
9616 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9617}
9618
9619/// FoldSelectIntoOp - Try fold the select into one of the operands to
9620/// facilitate further optimization.
9621Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9622 Value *FalseVal) {
9623 // See the comment above GetSelectFoldableOperands for a description of the
9624 // transformation we are doing here.
9625 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9626 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9627 !isa<Constant>(FalseVal)) {
9628 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9629 unsigned OpToFold = 0;
9630 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9631 OpToFold = 1;
9632 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9633 OpToFold = 2;
9634 }
9635
9636 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00009637 Constant *C = GetSelectFoldableConstant(TVI);
Evan Chengde621922009-03-31 20:42:45 +00009638 Value *OOp = TVI->getOperand(2-OpToFold);
9639 // Avoid creating select between 2 constants unless it's selecting
9640 // between 0 and 1.
9641 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9642 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9643 InsertNewInstBefore(NewSel, SI);
9644 NewSel->takeName(TVI);
9645 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9646 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009647 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009648 }
9649 }
9650 }
9651 }
9652 }
9653
9654 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9655 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9656 !isa<Constant>(TrueVal)) {
9657 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9658 unsigned OpToFold = 0;
9659 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9660 OpToFold = 1;
9661 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9662 OpToFold = 2;
9663 }
9664
9665 if (OpToFold) {
Chris Lattner4de84762010-01-04 07:02:48 +00009666 Constant *C = GetSelectFoldableConstant(FVI);
Evan Chengde621922009-03-31 20:42:45 +00009667 Value *OOp = FVI->getOperand(2-OpToFold);
9668 // Avoid creating select between 2 constants unless it's selecting
9669 // between 0 and 1.
9670 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9671 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9672 InsertNewInstBefore(NewSel, SI);
9673 NewSel->takeName(FVI);
9674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9675 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009676 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009677 }
9678 }
9679 }
9680 }
9681 }
9682
9683 return 0;
9684}
9685
Dan Gohman81b28ce2008-09-16 18:46:06 +00009686/// visitSelectInstWithICmp - Visit a SelectInst that has an
9687/// ICmpInst as its first operand.
9688///
9689Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9690 ICmpInst *ICI) {
9691 bool Changed = false;
9692 ICmpInst::Predicate Pred = ICI->getPredicate();
9693 Value *CmpLHS = ICI->getOperand(0);
9694 Value *CmpRHS = ICI->getOperand(1);
9695 Value *TrueVal = SI.getTrueValue();
9696 Value *FalseVal = SI.getFalseValue();
9697
9698 // Check cases where the comparison is with a constant that
9699 // can be adjusted to fit the min/max idiom. We may edit ICI in
9700 // place here, so make sure the select is the only user.
9701 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009702 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009703 switch (Pred) {
9704 default: break;
9705 case ICmpInst::ICMP_ULT:
9706 case ICmpInst::ICMP_SLT: {
9707 // X < MIN ? T : F --> F
9708 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9709 return ReplaceInstUsesWith(SI, FalseVal);
9710 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009711 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009712 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9713 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9714 Pred = ICmpInst::getSwappedPredicate(Pred);
9715 CmpRHS = AdjustedRHS;
9716 std::swap(FalseVal, TrueVal);
9717 ICI->setPredicate(Pred);
9718 ICI->setOperand(1, CmpRHS);
9719 SI.setOperand(1, TrueVal);
9720 SI.setOperand(2, FalseVal);
9721 Changed = true;
9722 }
9723 break;
9724 }
9725 case ICmpInst::ICMP_UGT:
9726 case ICmpInst::ICMP_SGT: {
9727 // X > MAX ? T : F --> F
9728 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9729 return ReplaceInstUsesWith(SI, FalseVal);
9730 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009731 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009732 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9733 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9734 Pred = ICmpInst::getSwappedPredicate(Pred);
9735 CmpRHS = AdjustedRHS;
9736 std::swap(FalseVal, TrueVal);
9737 ICI->setPredicate(Pred);
9738 ICI->setOperand(1, CmpRHS);
9739 SI.setOperand(1, TrueVal);
9740 SI.setOperand(2, FalseVal);
9741 Changed = true;
9742 }
9743 break;
9744 }
9745 }
9746
Dan Gohman1975d032008-10-30 20:40:10 +00009747 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9748 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009749 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009750 if (match(TrueVal, m_ConstantInt<-1>()) &&
9751 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009752 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009753 else if (match(TrueVal, m_ConstantInt<0>()) &&
9754 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009755 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9756
Dan Gohman1975d032008-10-30 20:40:10 +00009757 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9758 // If we are just checking for a icmp eq of a single bit and zext'ing it
9759 // to an integer, then shift the bit to the appropriate place and then
9760 // cast to integer to avoid the comparison.
9761 const APInt &Op1CV = CI->getValue();
9762
9763 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9764 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9765 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009766 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009767 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009768 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009769 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009770 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009771 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009772 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009773 if (In->getType() != SI.getType())
9774 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009775 true/*SExt*/, "tmp", ICI);
9776
9777 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009778 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009779 In->getName()+".not"), *ICI);
9780
9781 return ReplaceInstUsesWith(SI, In);
9782 }
9783 }
9784 }
9785
Dan Gohman81b28ce2008-09-16 18:46:06 +00009786 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9787 // Transform (X == Y) ? X : Y -> Y
9788 if (Pred == ICmpInst::ICMP_EQ)
9789 return ReplaceInstUsesWith(SI, FalseVal);
9790 // Transform (X != Y) ? X : Y -> X
9791 if (Pred == ICmpInst::ICMP_NE)
9792 return ReplaceInstUsesWith(SI, TrueVal);
9793 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9794
9795 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9796 // Transform (X == Y) ? Y : X -> X
9797 if (Pred == ICmpInst::ICMP_EQ)
9798 return ReplaceInstUsesWith(SI, FalseVal);
9799 // Transform (X != Y) ? Y : X -> Y
9800 if (Pred == ICmpInst::ICMP_NE)
9801 return ReplaceInstUsesWith(SI, TrueVal);
9802 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9803 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009804 return Changed ? &SI : 0;
9805}
9806
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009807
Chris Lattner7f239582009-10-22 00:17:26 +00009808/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9809/// PHI node (but the two may be in different blocks). See if the true/false
9810/// values (V) are live in all of the predecessor blocks of the PHI. For
9811/// example, cases like this cannot be mapped:
9812///
9813/// X = phi [ C1, BB1], [C2, BB2]
9814/// Y = add
9815/// Z = select X, Y, 0
9816///
9817/// because Y is not live in BB1/BB2.
9818///
9819static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9820 const SelectInst &SI) {
9821 // If the value is a non-instruction value like a constant or argument, it
9822 // can always be mapped.
9823 const Instruction *I = dyn_cast<Instruction>(V);
9824 if (I == 0) return true;
9825
9826 // If V is a PHI node defined in the same block as the condition PHI, we can
9827 // map the arguments.
9828 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9829
9830 if (const PHINode *VP = dyn_cast<PHINode>(I))
9831 if (VP->getParent() == CondPHI->getParent())
9832 return true;
9833
9834 // Otherwise, if the PHI and select are defined in the same block and if V is
9835 // defined in a different block, then we can transform it.
9836 if (SI.getParent() == CondPHI->getParent() &&
9837 I->getParent() != CondPHI->getParent())
9838 return true;
9839
9840 // Otherwise we have a 'hard' case and we can't tell without doing more
9841 // detailed dominator based analysis, punt.
9842 return false;
9843}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009844
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009845/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9846/// SPF2(SPF1(A, B), C)
9847Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9848 SelectPatternFlavor SPF1,
9849 Value *A, Value *B,
9850 Instruction &Outer,
9851 SelectPatternFlavor SPF2, Value *C) {
9852 if (C == A || C == B) {
9853 // MAX(MAX(A, B), B) -> MAX(A, B)
9854 // MIN(MIN(a, b), a) -> MIN(a, b)
9855 if (SPF1 == SPF2)
9856 return ReplaceInstUsesWith(Outer, Inner);
9857
9858 // MAX(MIN(a, b), a) -> a
9859 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009860 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9861 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9862 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9863 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009864 return ReplaceInstUsesWith(Outer, C);
9865 }
9866
9867 // TODO: MIN(MIN(A, 23), 97)
9868 return 0;
9869}
9870
9871
9872
9873
Chris Lattner3d69f462004-03-12 05:52:32 +00009874Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009875 Value *CondVal = SI.getCondition();
9876 Value *TrueVal = SI.getTrueValue();
9877 Value *FalseVal = SI.getFalseValue();
9878
9879 // select true, X, Y -> X
9880 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009881 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009882 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009883
9884 // select C, X, X -> X
9885 if (TrueVal == FalseVal)
9886 return ReplaceInstUsesWith(SI, TrueVal);
9887
Chris Lattnere87597f2004-10-16 18:11:37 +00009888 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9889 return ReplaceInstUsesWith(SI, FalseVal);
9890 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9891 return ReplaceInstUsesWith(SI, TrueVal);
9892 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9893 if (isa<Constant>(TrueVal))
9894 return ReplaceInstUsesWith(SI, TrueVal);
9895 else
9896 return ReplaceInstUsesWith(SI, FalseVal);
9897 }
9898
Chris Lattner4de84762010-01-04 07:02:48 +00009899 if (SI.getType() == Type::getInt1Ty(SI.getContext())) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009900 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009901 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009902 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009903 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009904 } else {
9905 // Change: A = select B, false, C --> A = and !B, C
9906 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009907 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009908 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009909 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009910 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009911 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009912 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009913 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009914 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009915 } else {
9916 // Change: A = select B, C, true --> A = or !B, C
9917 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009918 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009919 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009920 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009921 }
9922 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009923
9924 // select a, b, a -> a&b
9925 // select a, a, b -> a|b
9926 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009927 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009928 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009929 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009930 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009931
Chris Lattner2eefe512004-04-09 19:05:30 +00009932 // Selecting between two integer constants?
9933 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9934 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009935 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009936 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009937 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009938 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009939 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009940 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009941 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009942 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009943 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009944 }
Chris Lattner457dd822004-06-09 07:59:58 +00009945
Reid Spencere4d87aa2006-12-23 06:05:41 +00009946 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009947 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009948 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009949 // non-constant value, eliminate this whole mess. This corresponds to
9950 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009951 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009952 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009953 cast<Constant>(IC->getOperand(1))->isNullValue())
9954 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9955 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009956 isa<ConstantInt>(ICA->getOperand(1)) &&
9957 (ICA->getOperand(1) == TrueValC ||
9958 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009959 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9960 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009961 // know whether we have a icmp_ne or icmp_eq and whether the
9962 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009963 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009964 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009965 Value *V = ICA;
9966 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009967 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009968 Instruction::Xor, V, ICA->getOperand(1)), SI);
9969 return ReplaceInstUsesWith(SI, V);
9970 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009971 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009972 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009973
9974 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009975 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9976 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009977 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009978 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9979 // This is not safe in general for floating point:
9980 // consider X== -0, Y== +0.
9981 // It becomes safe if either operand is a nonzero constant.
9982 ConstantFP *CFPt, *CFPf;
9983 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9984 !CFPt->getValueAPF().isZero()) ||
9985 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9986 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009987 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009988 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009989 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009990 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009991 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009992 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009993
Reid Spencere4d87aa2006-12-23 06:05:41 +00009994 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009995 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009996 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9997 // This is not safe in general for floating point:
9998 // consider X== -0, Y== +0.
9999 // It becomes safe if either operand is a nonzero constant.
10000 ConstantFP *CFPt, *CFPf;
10001 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10002 !CFPt->getValueAPF().isZero()) ||
10003 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10004 !CFPf->getValueAPF().isZero()))
10005 return ReplaceInstUsesWith(SI, FalseVal);
10006 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010007 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +000010008 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10009 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010010 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +000010011 }
Dan Gohman81b28ce2008-09-16 18:46:06 +000010012 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +000010013 }
10014
10015 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +000010016 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
10017 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
10018 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +000010019
Chris Lattner87875da2005-01-13 22:52:24 +000010020 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
10021 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
10022 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +000010023 Instruction *AddOp = 0, *SubOp = 0;
10024
Chris Lattner6fb5a4a2005-01-19 21:50:18 +000010025 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
10026 if (TI->getOpcode() == FI->getOpcode())
10027 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
10028 return IV;
10029
10030 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
10031 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010032 if ((TI->getOpcode() == Instruction::Sub &&
10033 FI->getOpcode() == Instruction::Add) ||
10034 (TI->getOpcode() == Instruction::FSub &&
10035 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010036 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010037 } else if ((FI->getOpcode() == Instruction::Sub &&
10038 TI->getOpcode() == Instruction::Add) ||
10039 (FI->getOpcode() == Instruction::FSub &&
10040 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010041 AddOp = TI; SubOp = FI;
10042 }
10043
10044 if (AddOp) {
10045 Value *OtherAddOp = 0;
10046 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
10047 OtherAddOp = AddOp->getOperand(1);
10048 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
10049 OtherAddOp = AddOp->getOperand(0);
10050 }
10051
10052 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +000010053 // So at this point we know we have (Y -> OtherAddOp):
10054 // select C, (add X, Y), (sub X, Z)
10055 Value *NegVal; // Compute -Z
10056 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000010057 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +000010058 } else {
10059 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +000010060 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +000010061 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +000010062 }
Chris Lattner97f37a42006-02-24 18:05:58 +000010063
10064 Value *NewTrueOp = OtherAddOp;
10065 Value *NewFalseOp = NegVal;
10066 if (AddOp != TI)
10067 std::swap(NewTrueOp, NewFalseOp);
10068 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010069 SelectInst::Create(CondVal, NewTrueOp,
10070 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +000010071
10072 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010073 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +000010074 }
10075 }
10076 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010077
Chris Lattnere576b912004-04-09 23:46:01 +000010078 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +000010079 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010080 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +000010081 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010082
10083 // MAX(MAX(a, b), a) -> MAX(a, b)
10084 // MIN(MIN(a, b), a) -> MIN(a, b)
10085 // MAX(MIN(a, b), a) -> a
10086 // MIN(MAX(a, b), a) -> a
10087 Value *LHS, *RHS, *LHS2, *RHS2;
10088 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10089 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10090 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10091 SI, SPF, RHS))
10092 return R;
10093 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10094 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10095 SI, SPF, LHS))
10096 return R;
10097 }
10098
10099 // TODO.
10100 // ABS(-X) -> ABS(X)
10101 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +000010102 }
Chris Lattnera1df33c2005-04-24 07:30:14 +000010103
Chris Lattner7f239582009-10-22 00:17:26 +000010104 // See if we can fold the select into a phi node if the condition is a select.
10105 if (isa<PHINode>(SI.getCondition()))
10106 // The true/false values have to be live in the PHI predecessor's blocks.
10107 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10108 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10109 if (Instruction *NV = FoldOpIntoPhi(SI))
10110 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +000010111
Chris Lattnera1df33c2005-04-24 07:30:14 +000010112 if (BinaryOperator::isNot(CondVal)) {
10113 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10114 SI.setOperand(1, FalseVal);
10115 SI.setOperand(2, TrueVal);
10116 return &SI;
10117 }
10118
Chris Lattner3d69f462004-03-12 05:52:32 +000010119 return 0;
10120}
10121
Dan Gohmaneee962e2008-04-10 18:43:06 +000010122/// EnforceKnownAlignment - If the specified pointer points to an object that
10123/// we control, modify the object's alignment to PrefAlign. This isn't
10124/// often possible though. If alignment is important, a more reliable approach
10125/// is to simply align all global variables and allocation instructions to
10126/// their preferred alignment from the beginning.
10127///
10128static unsigned EnforceKnownAlignment(Value *V,
10129 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +000010130
Dan Gohmaneee962e2008-04-10 18:43:06 +000010131 User *U = dyn_cast<User>(V);
10132 if (!U) return Align;
10133
Dan Gohmanca178902009-07-17 20:47:02 +000010134 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010135 default: break;
10136 case Instruction::BitCast:
10137 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10138 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +000010139 // If all indexes are zero, it is just the alignment of the base pointer.
10140 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +000010141 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +000010142 if (!isa<Constant>(*i) ||
10143 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +000010144 AllZeroOperands = false;
10145 break;
10146 }
Chris Lattnerf2369f22007-08-09 19:05:49 +000010147
10148 if (AllZeroOperands) {
10149 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010150 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +000010151 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010152 break;
Chris Lattner95a959d2006-03-06 20:18:44 +000010153 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010154 }
10155
10156 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10157 // If there is a large requested alignment and we can, bump up the alignment
10158 // of the global.
10159 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +000010160 if (GV->getAlignment() >= PrefAlign)
10161 Align = GV->getAlignment();
10162 else {
10163 GV->setAlignment(PrefAlign);
10164 Align = PrefAlign;
10165 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010166 }
Chris Lattner42ebefa2009-09-27 21:42:46 +000010167 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10168 // If there is a requested alignment and if this is an alloca, round up.
10169 if (AI->getAlignment() >= PrefAlign)
10170 Align = AI->getAlignment();
10171 else {
10172 AI->setAlignment(PrefAlign);
10173 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +000010174 }
10175 }
10176
10177 return Align;
10178}
10179
10180/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10181/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10182/// and it is more than the alignment of the ultimate object, see if we can
10183/// increase the alignment of the ultimate object, making this check succeed.
10184unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10185 unsigned PrefAlign) {
10186 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10187 sizeof(PrefAlign) * CHAR_BIT;
10188 APInt Mask = APInt::getAllOnesValue(BitWidth);
10189 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10190 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10191 unsigned TrailZ = KnownZero.countTrailingOnes();
10192 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10193
10194 if (PrefAlign > Align)
10195 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10196
10197 // We don't need to make any adjustment.
10198 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +000010199}
10200
Chris Lattnerf497b022008-01-13 23:50:23 +000010201Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010202 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +000010203 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +000010204 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010205 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +000010206
10207 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010208 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010209 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +000010210 return MI;
10211 }
10212
10213 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10214 // load/store.
10215 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10216 if (MemOpLength == 0) return 0;
10217
Chris Lattner37ac6082008-01-14 00:28:35 +000010218 // Source and destination pointer types are always "i8*" for intrinsic. See
10219 // if the size is something we can handle with a single primitive load/store.
10220 // A single load+store correctly handles overlapping memory in the memmove
10221 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +000010222 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010223 if (Size == 0) return MI; // Delete this mem transfer.
10224
10225 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +000010226 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +000010227
Chris Lattner37ac6082008-01-14 00:28:35 +000010228 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +000010229 Type *NewPtrTy =
Chris Lattner4de84762010-01-04 07:02:48 +000010230 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +000010231
10232 // Memcpy forces the use of i8* for the source and destination. That means
10233 // that if you're using memcpy to move one double around, you'll get a cast
10234 // from double* to i8*. We'd much rather use a double load+store rather than
10235 // an i64 load+store, here because this improves the odds that the source or
10236 // dest address will be promotable. See if we can find a better type than the
10237 // integer datatype.
10238 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10239 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010240 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010241 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10242 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +000010243 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010244 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10245 if (STy->getNumElements() == 1)
10246 SrcETy = STy->getElementType(0);
10247 else
10248 break;
10249 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10250 if (ATy->getNumElements() == 1)
10251 SrcETy = ATy->getElementType();
10252 else
10253 break;
10254 } else
10255 break;
10256 }
10257
Dan Gohman8f8e2692008-05-23 01:52:21 +000010258 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010259 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010260 }
10261 }
10262
10263
Chris Lattnerf497b022008-01-13 23:50:23 +000010264 // If the memcpy/memmove provides better alignment info than we can
10265 // infer, use it.
10266 SrcAlign = std::max(SrcAlign, CopyAlign);
10267 DstAlign = std::max(DstAlign, CopyAlign);
10268
Chris Lattner08142f22009-08-30 19:47:22 +000010269 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10270 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010271 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10272 InsertNewInstBefore(L, *MI);
10273 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10274
10275 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010276 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010277 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010278}
Chris Lattner3d69f462004-03-12 05:52:32 +000010279
Chris Lattner69ea9d22008-04-30 06:39:11 +000010280Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10281 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010282 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010283 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010284 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010285 return MI;
10286 }
10287
10288 // Extract the length and alignment and fill if they are constant.
10289 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10290 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Chris Lattner4de84762010-01-04 07:02:48 +000010291 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(MI->getContext()))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010292 return 0;
10293 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010294 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010295
10296 // If the length is zero, this is a no-op
10297 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10298
10299 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10300 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner4de84762010-01-04 07:02:48 +000010301 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010302
10303 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010304 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010305
10306 // Alignment 0 is identity for alignment 1 for memset, but not store.
10307 if (Alignment == 0) Alignment = 1;
10308
10309 // Extract the fill value and store.
10310 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010311 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010312 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010313
10314 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010315 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010316 return MI;
10317 }
10318
10319 return 0;
10320}
10321
10322
Chris Lattner8b0ea312006-01-13 20:11:04 +000010323/// visitCallInst - CallInst simplification. This mostly only handles folding
10324/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10325/// the heavy lifting.
10326///
Chris Lattner9fe38862003-06-19 17:00:31 +000010327Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010328 if (isFreeCall(&CI))
10329 return visitFree(CI);
10330
Chris Lattneraab6ec42009-05-13 17:39:14 +000010331 // If the caller function is nounwind, mark the call as nounwind, even if the
10332 // callee isn't.
10333 if (CI.getParent()->getParent()->doesNotThrow() &&
10334 !CI.doesNotThrow()) {
10335 CI.setDoesNotThrow();
10336 return &CI;
10337 }
10338
Chris Lattner8b0ea312006-01-13 20:11:04 +000010339 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10340 if (!II) return visitCallSite(&CI);
10341
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010342 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10343 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010344 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010345 bool Changed = false;
10346
10347 // memmove/cpy/set of zero bytes is a noop.
10348 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10349 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10350
Chris Lattner35b9e482004-10-12 04:52:52 +000010351 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010352 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010353 // Replace the instruction with just byte operations. We would
10354 // transform other cases to loads/stores, but we don't know if
10355 // alignment is sufficient.
10356 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010357 }
10358
Chris Lattner35b9e482004-10-12 04:52:52 +000010359 // If we have a memmove and the source operation is a constant global,
10360 // then the source and dest pointers can't alias, so we can change this
10361 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010362 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010363 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10364 if (GVSrc->isConstant()) {
10365 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010366 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10367 const Type *Tys[1];
10368 Tys[0] = CI.getOperand(3)->getType();
10369 CI.setOperand(0,
10370 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010371 Changed = true;
10372 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010373 }
Chris Lattnera935db82008-05-28 05:30:41 +000010374
Eli Friedman0c826d92009-12-17 21:07:31 +000010375 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010376 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010377 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010378 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010379 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010380
Chris Lattner95a959d2006-03-06 20:18:44 +000010381 // If we can determine a pointer alignment that is bigger than currently
10382 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010383 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010384 if (Instruction *I = SimplifyMemTransfer(MI))
10385 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010386 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10387 if (Instruction *I = SimplifyMemSet(MSI))
10388 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010389 }
10390
Chris Lattner8b0ea312006-01-13 20:11:04 +000010391 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010392 }
10393
10394 switch (II->getIntrinsicID()) {
10395 default: break;
10396 case Intrinsic::bswap:
10397 // bswap(bswap(x)) -> x
10398 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10399 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10400 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010401
10402 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10403 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10404 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10405 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10406 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10407 TI->getType()->getPrimitiveSizeInBits();
10408 Value *CV = ConstantInt::get(Operand->getType(), C);
10409 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10410 return new TruncInst(V, TI->getType());
10411 }
10412 }
10413
Chris Lattner0521e3c2008-06-18 04:33:20 +000010414 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010415 case Intrinsic::powi:
10416 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10417 // powi(x, 0) -> 1.0
10418 if (Power->isZero())
10419 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10420 // powi(x, 1) -> x
10421 if (Power->isOne())
10422 return ReplaceInstUsesWith(CI, II->getOperand(1));
10423 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010424 if (Power->isAllOnesValue())
10425 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10426 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010427 }
10428 break;
10429
Chris Lattner2bbac752009-11-26 21:42:47 +000010430 case Intrinsic::uadd_with_overflow: {
10431 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10432 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10433 uint32_t BitWidth = IT->getBitWidth();
10434 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010435 APInt LHSKnownZero(BitWidth, 0);
10436 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010437 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10438 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10439 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10440
10441 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010442 APInt RHSKnownZero(BitWidth, 0);
10443 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010444 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10445 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10446 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10447 if (LHSKnownNegative && RHSKnownNegative) {
10448 // The sign bit is set in both cases: this MUST overflow.
10449 // Create a simple add instruction, and insert it into the struct.
10450 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10451 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010452 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +000010453 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010454 };
Chris Lattner4de84762010-01-04 07:02:48 +000010455 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010456 return InsertValueInst::Create(Struct, Add, 0);
10457 }
10458
10459 if (LHSKnownPositive && RHSKnownPositive) {
10460 // The sign bit is clear in both cases: this CANNOT overflow.
10461 // Create a simple add instruction, and insert it into the struct.
10462 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10463 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010464 Constant *V[] = {
Chris Lattner4de84762010-01-04 07:02:48 +000010465 UndefValue::get(LHS->getType()),
10466 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010467 };
Chris Lattner4de84762010-01-04 07:02:48 +000010468 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010469 return InsertValueInst::Create(Struct, Add, 0);
10470 }
10471 }
10472 }
10473 // FALL THROUGH uadd into sadd
10474 case Intrinsic::sadd_with_overflow:
10475 // Canonicalize constants into the RHS.
10476 if (isa<Constant>(II->getOperand(1)) &&
10477 !isa<Constant>(II->getOperand(2))) {
10478 Value *LHS = II->getOperand(1);
10479 II->setOperand(1, II->getOperand(2));
10480 II->setOperand(2, LHS);
10481 return II;
10482 }
10483
10484 // X + undef -> undef
10485 if (isa<UndefValue>(II->getOperand(2)))
10486 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10487
10488 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10489 // X + 0 -> {X, false}
10490 if (RHS->isZero()) {
10491 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010492 UndefValue::get(II->getOperand(0)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010493 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +000010494 };
Chris Lattner4de84762010-01-04 07:02:48 +000010495 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010496 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10497 }
10498 }
10499 break;
10500 case Intrinsic::usub_with_overflow:
10501 case Intrinsic::ssub_with_overflow:
10502 // undef - X -> undef
10503 // X - undef -> undef
10504 if (isa<UndefValue>(II->getOperand(1)) ||
10505 isa<UndefValue>(II->getOperand(2)))
10506 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10507
10508 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10509 // X - 0 -> {X, false}
10510 if (RHS->isZero()) {
10511 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010512 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010513 ConstantInt::getFalse(II->getContext())
Chris Lattner2bbac752009-11-26 21:42:47 +000010514 };
Chris Lattner4de84762010-01-04 07:02:48 +000010515 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattner2bbac752009-11-26 21:42:47 +000010516 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10517 }
10518 }
10519 break;
10520 case Intrinsic::umul_with_overflow:
10521 case Intrinsic::smul_with_overflow:
10522 // Canonicalize constants into the RHS.
10523 if (isa<Constant>(II->getOperand(1)) &&
10524 !isa<Constant>(II->getOperand(2))) {
10525 Value *LHS = II->getOperand(1);
10526 II->setOperand(1, II->getOperand(2));
10527 II->setOperand(2, LHS);
10528 return II;
10529 }
10530
10531 // X * undef -> undef
10532 if (isa<UndefValue>(II->getOperand(2)))
10533 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10534
10535 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10536 // X*0 -> {0, false}
10537 if (RHSI->isZero())
10538 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10539
10540 // X * 1 -> {X, false}
10541 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010542 Constant *V[] = {
10543 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner4de84762010-01-04 07:02:48 +000010544 ConstantInt::getFalse(II->getContext())
Chris Lattnercd188e92009-11-29 02:57:29 +000010545 };
Chris Lattner4de84762010-01-04 07:02:48 +000010546 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010547 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010548 }
10549 }
10550 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010551 case Intrinsic::ppc_altivec_lvx:
10552 case Intrinsic::ppc_altivec_lvxl:
10553 case Intrinsic::x86_sse_loadu_ps:
10554 case Intrinsic::x86_sse2_loadu_pd:
10555 case Intrinsic::x86_sse2_loadu_dq:
10556 // Turn PPC lvx -> load if the pointer is known aligned.
10557 // Turn X86 loadups -> load if the pointer is known aligned.
10558 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010559 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10560 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010561 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010562 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010563 break;
10564 case Intrinsic::ppc_altivec_stvx:
10565 case Intrinsic::ppc_altivec_stvxl:
10566 // Turn stvx -> store if the pointer is known aligned.
10567 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10568 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010569 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010570 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010571 return new StoreInst(II->getOperand(1), Ptr);
10572 }
10573 break;
10574 case Intrinsic::x86_sse_storeu_ps:
10575 case Intrinsic::x86_sse2_storeu_pd:
10576 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010577 // Turn X86 storeu -> store if the pointer is known aligned.
10578 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10579 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010580 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010581 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010582 return new StoreInst(II->getOperand(2), Ptr);
10583 }
10584 break;
10585
10586 case Intrinsic::x86_sse_cvttss2si: {
10587 // These intrinsics only demands the 0th element of its input vector. If
10588 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010589 unsigned VWidth =
10590 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10591 APInt DemandedElts(VWidth, 1);
10592 APInt UndefElts(VWidth, 0);
10593 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010594 UndefElts)) {
10595 II->setOperand(1, V);
10596 return II;
10597 }
10598 break;
10599 }
10600
10601 case Intrinsic::ppc_altivec_vperm:
10602 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10603 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10604 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010605
Chris Lattner0521e3c2008-06-18 04:33:20 +000010606 // Check that all of the elements are integer constants or undefs.
10607 bool AllEltsOk = true;
10608 for (unsigned i = 0; i != 16; ++i) {
10609 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10610 !isa<UndefValue>(Mask->getOperand(i))) {
10611 AllEltsOk = false;
10612 break;
10613 }
10614 }
10615
10616 if (AllEltsOk) {
10617 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010618 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10619 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010620 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010621
Chris Lattner0521e3c2008-06-18 04:33:20 +000010622 // Only extract each element once.
10623 Value *ExtractedElts[32];
10624 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10625
Chris Lattnere2ed0572006-04-06 19:19:17 +000010626 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010627 if (isa<UndefValue>(Mask->getOperand(i)))
10628 continue;
10629 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10630 Idx &= 31; // Match the hardware behavior.
10631
10632 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010633 ExtractedElts[Idx] =
10634 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner4de84762010-01-04 07:02:48 +000010635 ConstantInt::get(Type::getInt32Ty(II->getContext()),
10636 Idx&15, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010637 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010638
Chris Lattner0521e3c2008-06-18 04:33:20 +000010639 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010640 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Chris Lattner4de84762010-01-04 07:02:48 +000010641 ConstantInt::get(Type::getInt32Ty(II->getContext()),
10642 i, false), "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010643 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010644 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010645 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010646 }
10647 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010648
Chris Lattner0521e3c2008-06-18 04:33:20 +000010649 case Intrinsic::stackrestore: {
10650 // If the save is right next to the restore, remove the restore. This can
10651 // happen when variable allocas are DCE'd.
10652 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10653 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10654 BasicBlock::iterator BI = SS;
10655 if (&*++BI == II)
10656 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010657 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010658 }
10659
10660 // Scan down this block to see if there is another stack restore in the
10661 // same block without an intervening call/alloca.
10662 BasicBlock::iterator BI = II;
10663 TerminatorInst *TI = II->getParent()->getTerminator();
10664 bool CannotRemove = false;
10665 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010666 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010667 CannotRemove = true;
10668 break;
10669 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010670 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10671 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10672 // If there is a stackrestore below this one, remove this one.
10673 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10674 return EraseInstFromFunction(CI);
10675 // Otherwise, ignore the intrinsic.
10676 } else {
10677 // If we found a non-intrinsic call, we can't remove the stack
10678 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010679 CannotRemove = true;
10680 break;
10681 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010682 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010683 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010684
10685 // If the stack restore is in a return/unwind block and if there are no
10686 // allocas or calls between the restore and the return, nuke the restore.
10687 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10688 return EraseInstFromFunction(CI);
10689 break;
10690 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010691 }
10692
Chris Lattner8b0ea312006-01-13 20:11:04 +000010693 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010694}
10695
10696// InvokeInst simplification
10697//
10698Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010699 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010700}
10701
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010702/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10703/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010704static bool isSafeToEliminateVarargsCast(const CallSite CS,
10705 const CastInst * const CI,
10706 const TargetData * const TD,
10707 const int ix) {
10708 if (!CI->isLosslessCast())
10709 return false;
10710
10711 // The size of ByVal arguments is derived from the type, so we
10712 // can't change to a type with a different size. If the size were
10713 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010714 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010715 return true;
10716
10717 const Type* SrcTy =
10718 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10719 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10720 if (!SrcTy->isSized() || !DstTy->isSized())
10721 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010722 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010723 return false;
10724 return true;
10725}
10726
Chris Lattnera44d8a22003-10-07 22:32:43 +000010727// visitCallSite - Improvements for call and invoke instructions.
10728//
10729Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010730 bool Changed = false;
10731
10732 // If the callee is a constexpr cast of a function, attempt to move the cast
10733 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010734 if (transformConstExprCastCall(CS)) return 0;
10735
Chris Lattner6c266db2003-10-07 22:54:13 +000010736 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010737
Chris Lattner08b22ec2005-05-13 07:09:09 +000010738 if (Function *CalleeF = dyn_cast<Function>(Callee))
10739 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10740 Instruction *OldCall = CS.getInstruction();
10741 // If the call and callee calling conventions don't match, this call must
10742 // be unreachable, as the call is undefined.
Chris Lattner4de84762010-01-04 07:02:48 +000010743 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
10744 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Owen Andersond672ecb2009-07-03 00:17:18 +000010745 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010746 // If OldCall dues not return void then replaceAllUsesWith undef.
10747 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010748 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010749 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010750 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10751 return EraseInstFromFunction(*OldCall);
10752 return 0;
10753 }
10754
Chris Lattner17be6352004-10-18 02:59:09 +000010755 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10756 // This instruction is not reachable, just remove it. We insert a store to
10757 // undef so that we know that this code is not reachable, despite the fact
10758 // that we can't modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +000010759 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
10760 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner17be6352004-10-18 02:59:09 +000010761 CS.getInstruction());
10762
Devang Patel228ebd02009-10-13 22:56:32 +000010763 // If CS dues not return void then replaceAllUsesWith undef.
10764 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010765 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010766 CS.getInstruction()->
10767 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010768
10769 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10770 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010771 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner4de84762010-01-04 07:02:48 +000010772 ConstantInt::getTrue(Callee->getContext()), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010773 }
Chris Lattner17be6352004-10-18 02:59:09 +000010774 return EraseInstFromFunction(*CS.getInstruction());
10775 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010776
Duncan Sandscdb6d922007-09-17 10:26:40 +000010777 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10778 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10779 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10780 return transformCallThroughTrampoline(CS);
10781
Chris Lattner6c266db2003-10-07 22:54:13 +000010782 const PointerType *PTy = cast<PointerType>(Callee->getType());
10783 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10784 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010785 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010786 // See if we can optimize any arguments passed through the varargs area of
10787 // the call.
10788 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010789 E = CS.arg_end(); I != E; ++I, ++ix) {
10790 CastInst *CI = dyn_cast<CastInst>(*I);
10791 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10792 *I = CI->getOperand(0);
10793 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010794 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010795 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010796 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010797
Duncan Sandsf0c33542007-12-19 21:13:37 +000010798 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010799 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010800 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010801 Changed = true;
10802 }
10803
Chris Lattner6c266db2003-10-07 22:54:13 +000010804 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010805}
10806
Chris Lattner9fe38862003-06-19 17:00:31 +000010807// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10808// attempt to move the cast to the arguments of the call/invoke.
10809//
10810bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10811 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10812 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010813 if (CE->getOpcode() != Instruction::BitCast ||
10814 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010815 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010816 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010817 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010818 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010819
10820 // Okay, this is a cast from a function to a different type. Unless doing so
10821 // would cause a type conversion of one of our arguments, change this call to
10822 // be a direct call with arguments casted to the appropriate types.
10823 //
10824 const FunctionType *FT = Callee->getFunctionType();
10825 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010826 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010827
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010828 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010829 return false; // TODO: Handle multiple return values.
10830
Chris Lattnerf78616b2004-01-14 06:06:08 +000010831 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010832 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010833 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010834 // Conversion is ok if changing from one pointer type to another or from
10835 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010836 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010837 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010838 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010839 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010840 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010841
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010842 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010843 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010844 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010845 return false; // Cannot transform this return value.
10846
Chris Lattner58d74912008-03-12 17:45:29 +000010847 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010848 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010849 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010850 return false; // Attribute not compatible with transformed value.
10851 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010852
Chris Lattnerf78616b2004-01-14 06:06:08 +000010853 // If the callsite is an invoke instruction, and the return value is used by
10854 // a PHI node in a successor, we cannot change the return type of the call
10855 // because there is no place to put the cast instruction (without breaking
10856 // the critical edge). Bail out in this case.
10857 if (!Caller->use_empty())
10858 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10859 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10860 UI != E; ++UI)
10861 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10862 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010863 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010864 return false;
10865 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010866
10867 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10868 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010869
Chris Lattner9fe38862003-06-19 17:00:31 +000010870 CallSite::arg_iterator AI = CS.arg_begin();
10871 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10872 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010873 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010874
10875 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010876 return false; // Cannot transform this parameter value.
10877
Devang Patel19c87462008-09-26 22:53:05 +000010878 if (CallerPAL.getParamAttributes(i + 1)
10879 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010880 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010881
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010882 // Converting from one pointer type to another or between a pointer and an
10883 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010884 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010885 (TD && ((isa<PointerType>(ParamTy) ||
10886 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10887 (isa<PointerType>(ActTy) ||
10888 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010889 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010890 }
10891
10892 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010893 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010894 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010895
Chris Lattner58d74912008-03-12 17:45:29 +000010896 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10897 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010898 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010899 // won't be dropping them. Check that these extra arguments have attributes
10900 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010901 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10902 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010903 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010904 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010905 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010906 return false;
10907 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010908
Chris Lattner9fe38862003-06-19 17:00:31 +000010909 // Okay, we decided that this is a safe thing to do: go ahead and start
10910 // inserting cast instructions as necessary...
10911 std::vector<Value*> Args;
10912 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010913 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010914 attrVec.reserve(NumCommonArgs);
10915
10916 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010917 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010918
10919 // If the return value is not being used, the type may not be compatible
10920 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010921 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010922
10923 // Add the new return attributes.
10924 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010925 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010926
10927 AI = CS.arg_begin();
10928 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10929 const Type *ParamTy = FT->getParamType(i);
10930 if ((*AI)->getType() == ParamTy) {
10931 Args.push_back(*AI);
10932 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010933 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010934 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010935 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010936 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010937
10938 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010939 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010940 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010941 }
10942
10943 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010944 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010945 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010946 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010947
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010948 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010949 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010950 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010951 errs() << "WARNING: While resolving call to function '"
10952 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010953 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010954 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010955 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10956 const Type *PTy = getPromotedType((*AI)->getType());
10957 if (PTy != (*AI)->getType()) {
10958 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010959 Instruction::CastOps opcode =
10960 CastInst::getCastOpcode(*AI, false, PTy, false);
10961 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010962 } else {
10963 Args.push_back(*AI);
10964 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010965
Duncan Sandse1e520f2008-01-13 08:02:44 +000010966 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010967 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010968 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010969 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010970 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010971 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010972
Devang Patel19c87462008-09-26 22:53:05 +000010973 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10974 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10975
Devang Patel9674d152009-10-14 17:29:00 +000010976 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010977 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010978
Eric Christophera66297a2009-07-25 02:45:27 +000010979 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10980 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010981
Chris Lattner9fe38862003-06-19 17:00:31 +000010982 Instruction *NC;
10983 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010984 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010985 Args.begin(), Args.end(),
10986 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010987 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010988 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010989 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010990 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10991 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010992 CallInst *CI = cast<CallInst>(Caller);
10993 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010994 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010995 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010996 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010997 }
10998
Chris Lattner6934a042007-02-11 01:23:03 +000010999 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000011000 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011001 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000011002 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011003 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011004 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011005 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000011006
11007 // If this is an invoke instruction, we should insert it after the first
11008 // non-phi, instruction in the normal successor block.
11009 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000011010 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000011011 InsertNewInstBefore(NC, *I);
11012 } else {
11013 // Otherwise, it's a call, just insert cast right after the call instr
11014 InsertNewInstBefore(NC, *Caller);
11015 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000011016 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011017 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011018 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000011019 }
11020 }
11021
Devang Patel1bf5ebc2009-10-13 21:41:20 +000011022
Chris Lattner931f8f32009-08-31 05:17:58 +000011023 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000011024 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000011025
11026 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011027 return true;
11028}
11029
Duncan Sandscdb6d922007-09-17 10:26:40 +000011030// transformCallThroughTrampoline - Turn a call to a function created by the
11031// init_trampoline intrinsic into a direct call to the underlying function.
11032//
11033Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
11034 Value *Callee = CS.getCalledValue();
11035 const PointerType *PTy = cast<PointerType>(Callee->getType());
11036 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000011037 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011038
11039 // If the call already has the 'nest' attribute somewhere then give up -
11040 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000011041 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011042 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011043
11044 IntrinsicInst *Tramp =
11045 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
11046
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000011047 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011048 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
11049 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
11050
Devang Patel05988662008-09-25 21:00:45 +000011051 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000011052 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011053 unsigned NestIdx = 1;
11054 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000011055 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011056
11057 // Look for a parameter marked with the 'nest' attribute.
11058 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11059 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000011060 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011061 // Record the parameter type and any other attributes.
11062 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000011063 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011064 break;
11065 }
11066
11067 if (NestTy) {
11068 Instruction *Caller = CS.getInstruction();
11069 std::vector<Value*> NewArgs;
11070 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11071
Devang Patel05988662008-09-25 21:00:45 +000011072 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000011073 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011074
Duncan Sandscdb6d922007-09-17 10:26:40 +000011075 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011076 // mean appending it. Likewise for attributes.
11077
Devang Patel19c87462008-09-26 22:53:05 +000011078 // Add any result attributes.
11079 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000011080 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011081
Duncan Sandscdb6d922007-09-17 10:26:40 +000011082 {
11083 unsigned Idx = 1;
11084 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11085 do {
11086 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011087 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011088 Value *NestVal = Tramp->getOperand(3);
11089 if (NestVal->getType() != NestTy)
11090 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11091 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000011092 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011093 }
11094
11095 if (I == E)
11096 break;
11097
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011098 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011099 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000011100 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011101 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000011102 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011103
11104 ++Idx, ++I;
11105 } while (1);
11106 }
11107
Devang Patel19c87462008-09-26 22:53:05 +000011108 // Add any function attributes.
11109 if (Attributes Attr = Attrs.getFnAttributes())
11110 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11111
Duncan Sandscdb6d922007-09-17 10:26:40 +000011112 // The trampoline may have been bitcast to a bogus type (FTy).
11113 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011114 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011115
Duncan Sandscdb6d922007-09-17 10:26:40 +000011116 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011117 NewTypes.reserve(FTy->getNumParams()+1);
11118
Duncan Sandscdb6d922007-09-17 10:26:40 +000011119 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011120 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011121 {
11122 unsigned Idx = 1;
11123 FunctionType::param_iterator I = FTy->param_begin(),
11124 E = FTy->param_end();
11125
11126 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011127 if (Idx == NestIdx)
11128 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011129 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011130
11131 if (I == E)
11132 break;
11133
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011134 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011135 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011136
11137 ++Idx, ++I;
11138 } while (1);
11139 }
11140
11141 // Replace the trampoline call with a direct call. Let the generic
11142 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000011143 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000011144 FTy->isVarArg());
11145 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000011146 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000011147 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000011148 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000011149 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11150 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011151
11152 Instruction *NewCaller;
11153 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011154 NewCaller = InvokeInst::Create(NewCallee,
11155 II->getNormalDest(), II->getUnwindDest(),
11156 NewArgs.begin(), NewArgs.end(),
11157 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011158 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011159 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011160 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011161 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11162 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011163 if (cast<CallInst>(Caller)->isTailCall())
11164 cast<CallInst>(NewCaller)->setTailCall();
11165 cast<CallInst>(NewCaller)->
11166 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011167 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011168 }
Devang Patel9674d152009-10-14 17:29:00 +000011169 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000011170 Caller->replaceAllUsesWith(NewCaller);
11171 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000011172 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011173 return 0;
11174 }
11175 }
11176
11177 // Replace the trampoline call with a direct call. Since there is no 'nest'
11178 // parameter, there is no need to adjust the argument list. Let the generic
11179 // code sort out any function type mismatches.
11180 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000011181 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000011182 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011183 CS.setCalledFunction(NewCallee);
11184 return CS.getInstruction();
11185}
11186
Dan Gohman9ad29202009-09-16 16:50:24 +000011187/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11188/// 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 +000011189/// and a single binop.
11190Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11191 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011192 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000011193 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011194 Value *LHSVal = FirstInst->getOperand(0);
11195 Value *RHSVal = FirstInst->getOperand(1);
11196
11197 const Type *LHSType = LHSVal->getType();
11198 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000011199
Dan Gohman9ad29202009-09-16 16:50:24 +000011200 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011201 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000011202 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000011203 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000011204 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000011205 // types or GEP's with different index types.
11206 I->getOperand(0)->getType() != LHSType ||
11207 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000011208 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011209
11210 // If they are CmpInst instructions, check their predicates
11211 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11212 if (cast<CmpInst>(I)->getPredicate() !=
11213 cast<CmpInst>(FirstInst)->getPredicate())
11214 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011215
11216 // Keep track of which operand needs a phi node.
11217 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11218 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011219 }
Dan Gohman9ad29202009-09-16 16:50:24 +000011220
11221 // If both LHS and RHS would need a PHI, don't do this transformation,
11222 // because it would increase the number of PHIs entering the block,
11223 // which leads to higher register pressure. This is especially
11224 // bad when the PHIs are in the header of a loop.
11225 if (!LHSVal && !RHSVal)
11226 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011227
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011228 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000011229
Chris Lattner7da52b22006-11-01 04:51:18 +000011230 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000011231 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000011232 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011233 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011234 NewLHS = PHINode::Create(LHSType,
11235 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011236 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11237 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011238 InsertNewInstBefore(NewLHS, PN);
11239 LHSVal = NewLHS;
11240 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011241
11242 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011243 NewRHS = PHINode::Create(RHSType,
11244 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011245 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11246 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011247 InsertNewInstBefore(NewRHS, PN);
11248 RHSVal = NewRHS;
11249 }
11250
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011251 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000011252 if (NewLHS || NewRHS) {
11253 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11254 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11255 if (NewLHS) {
11256 Value *NewInLHS = InInst->getOperand(0);
11257 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11258 }
11259 if (NewRHS) {
11260 Value *NewInRHS = InInst->getOperand(1);
11261 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11262 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011263 }
11264 }
11265
Chris Lattner7da52b22006-11-01 04:51:18 +000011266 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011267 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011268 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011269 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011270 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011271}
11272
Chris Lattner05f18922008-12-01 02:34:36 +000011273Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11274 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11275
11276 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11277 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011278 // This is true if all GEP bases are allocas and if all indices into them are
11279 // constants.
11280 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011281
11282 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011283 // more than one phi, which leads to higher register pressure. This is
11284 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011285 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011286
Dan Gohman9ad29202009-09-16 16:50:24 +000011287 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011288 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11289 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11290 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11291 GEP->getNumOperands() != FirstInst->getNumOperands())
11292 return 0;
11293
Chris Lattner36d3e322009-02-21 00:46:50 +000011294 // Keep track of whether or not all GEPs are of alloca pointers.
11295 if (AllBasePointersAreAllocas &&
11296 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11297 !GEP->hasAllConstantIndices()))
11298 AllBasePointersAreAllocas = false;
11299
Chris Lattner05f18922008-12-01 02:34:36 +000011300 // Compare the operand lists.
11301 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11302 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11303 continue;
11304
11305 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11306 // if one of the PHIs has a constant for the index. The index may be
11307 // substantially cheaper to compute for the constants, so making it a
11308 // variable index could pessimize the path. This also handles the case
11309 // for struct indices, which must always be constant.
11310 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11311 isa<ConstantInt>(GEP->getOperand(op)))
11312 return 0;
11313
11314 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11315 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011316
11317 // If we already needed a PHI for an earlier operand, and another operand
11318 // also requires a PHI, we'd be introducing more PHIs than we're
11319 // eliminating, which increases register pressure on entry to the PHI's
11320 // block.
11321 if (NeededPhi)
11322 return 0;
11323
Chris Lattner05f18922008-12-01 02:34:36 +000011324 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011325 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011326 }
11327 }
11328
Chris Lattner36d3e322009-02-21 00:46:50 +000011329 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011330 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011331 // offset calculation, but all the predecessors will have to materialize the
11332 // stack address into a register anyway. We'd actually rather *clone* the
11333 // load up into the predecessors so that we have a load of a gep of an alloca,
11334 // which can usually all be folded into the load.
11335 if (AllBasePointersAreAllocas)
11336 return 0;
11337
Chris Lattner05f18922008-12-01 02:34:36 +000011338 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11339 // that is variable.
11340 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11341
11342 bool HasAnyPHIs = false;
11343 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11344 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11345 Value *FirstOp = FirstInst->getOperand(i);
11346 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11347 FirstOp->getName()+".pn");
11348 InsertNewInstBefore(NewPN, PN);
11349
11350 NewPN->reserveOperandSpace(e);
11351 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11352 OperandPhis[i] = NewPN;
11353 FixedOperands[i] = NewPN;
11354 HasAnyPHIs = true;
11355 }
11356
11357
11358 // Add all operands to the new PHIs.
11359 if (HasAnyPHIs) {
11360 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11361 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11362 BasicBlock *InBB = PN.getIncomingBlock(i);
11363
11364 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11365 if (PHINode *OpPhi = OperandPhis[op])
11366 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11367 }
11368 }
11369
11370 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011371 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11372 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11373 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011374 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11375 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011376}
11377
11378
Chris Lattner21550882009-02-23 05:56:17 +000011379/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11380/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011381/// obvious the value of the load is not changed from the point of the load to
11382/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011383///
11384/// Finally, it is safe, but not profitable, to sink a load targetting a
11385/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11386/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011387static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011388 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11389
11390 for (++BBI; BBI != E; ++BBI)
11391 if (BBI->mayWriteToMemory())
11392 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011393
11394 // Check for non-address taken alloca. If not address-taken already, it isn't
11395 // profitable to do this xform.
11396 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11397 bool isAddressTaken = false;
11398 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11399 UI != E; ++UI) {
11400 if (isa<LoadInst>(UI)) continue;
11401 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11402 // If storing TO the alloca, then the address isn't taken.
11403 if (SI->getOperand(1) == AI) continue;
11404 }
11405 isAddressTaken = true;
11406 break;
11407 }
11408
Chris Lattner36d3e322009-02-21 00:46:50 +000011409 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011410 return false;
11411 }
11412
Chris Lattner36d3e322009-02-21 00:46:50 +000011413 // If this load is a load from a GEP with a constant offset from an alloca,
11414 // then we don't want to sink it. In its present form, it will be
11415 // load [constant stack offset]. Sinking it will cause us to have to
11416 // materialize the stack addresses in each predecessor in a register only to
11417 // do a shared load from register in the successor.
11418 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11419 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11420 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11421 return false;
11422
Chris Lattner76c73142006-11-01 07:13:54 +000011423 return true;
11424}
11425
Chris Lattner751a3622009-11-01 20:04:24 +000011426Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11427 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11428
11429 // When processing loads, we need to propagate two bits of information to the
11430 // sunk load: whether it is volatile, and what its alignment is. We currently
11431 // don't sink loads when some have their alignment specified and some don't.
11432 // visitLoadInst will propagate an alignment onto the load when TD is around,
11433 // and if TD isn't around, we can't handle the mixed case.
11434 bool isVolatile = FirstLI->isVolatile();
11435 unsigned LoadAlignment = FirstLI->getAlignment();
11436
11437 // We can't sink the load if the loaded value could be modified between the
11438 // load and the PHI.
11439 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11440 !isSafeAndProfitableToSinkLoad(FirstLI))
11441 return 0;
11442
11443 // If the PHI is of volatile loads and the load block has multiple
11444 // successors, sinking it would remove a load of the volatile value from
11445 // the path through the other successor.
11446 if (isVolatile &&
11447 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11448 return 0;
11449
11450 // Check to see if all arguments are the same operation.
11451 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11452 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11453 if (!LI || !LI->hasOneUse())
11454 return 0;
11455
11456 // We can't sink the load if the loaded value could be modified between
11457 // the load and the PHI.
11458 if (LI->isVolatile() != isVolatile ||
11459 LI->getParent() != PN.getIncomingBlock(i) ||
11460 !isSafeAndProfitableToSinkLoad(LI))
11461 return 0;
11462
11463 // If some of the loads have an alignment specified but not all of them,
11464 // we can't do the transformation.
11465 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11466 return 0;
11467
Chris Lattnera664bb72009-11-01 20:07:07 +000011468 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011469
11470 // If the PHI is of volatile loads and the load block has multiple
11471 // successors, sinking it would remove a load of the volatile value from
11472 // the path through the other successor.
11473 if (isVolatile &&
11474 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11475 return 0;
11476 }
11477
11478 // Okay, they are all the same operation. Create a new PHI node of the
11479 // correct type, and PHI together all of the LHS's of the instructions.
11480 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11481 PN.getName()+".in");
11482 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11483
11484 Value *InVal = FirstLI->getOperand(0);
11485 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11486
11487 // Add all operands to the new PHI.
11488 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11489 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11490 if (NewInVal != InVal)
11491 InVal = 0;
11492 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11493 }
11494
11495 Value *PhiVal;
11496 if (InVal) {
11497 // The new PHI unions all of the same values together. This is really
11498 // common, so we handle it intelligently here for compile-time speed.
11499 PhiVal = InVal;
11500 delete NewPN;
11501 } else {
11502 InsertNewInstBefore(NewPN, PN);
11503 PhiVal = NewPN;
11504 }
11505
11506 // If this was a volatile load that we are merging, make sure to loop through
11507 // and mark all the input loads as non-volatile. If we don't do this, we will
11508 // insert a new volatile load and the old ones will not be deletable.
11509 if (isVolatile)
11510 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11511 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11512
11513 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11514}
11515
Chris Lattner9fe38862003-06-19 17:00:31 +000011516
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011517
11518/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11519/// operator and they all are only used by the PHI, PHI together their
11520/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011521Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11522 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11523
Chris Lattner751a3622009-11-01 20:04:24 +000011524 if (isa<GetElementPtrInst>(FirstInst))
11525 return FoldPHIArgGEPIntoPHI(PN);
11526 if (isa<LoadInst>(FirstInst))
11527 return FoldPHIArgLoadIntoPHI(PN);
11528
Chris Lattnerbac32862004-11-14 19:13:23 +000011529 // Scan the instruction, looking for input operations that can be folded away.
11530 // If all input operands to the phi are the same instruction (e.g. a cast from
11531 // the same type or "+42") we can pull the operation through the PHI, reducing
11532 // code size and simplifying code.
11533 Constant *ConstantOp = 0;
11534 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011535
Chris Lattnerbac32862004-11-14 19:13:23 +000011536 if (isa<CastInst>(FirstInst)) {
11537 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011538
11539 // Be careful about transforming integer PHIs. We don't want to pessimize
11540 // the code by turning an i32 into an i1293.
11541 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011542 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011543 return 0;
11544 }
Reid Spencer832254e2007-02-02 02:16:23 +000011545 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011546 // Can fold binop, compare or shift here if the RHS is a constant,
11547 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011548 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011549 if (ConstantOp == 0)
11550 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011551 } else {
11552 return 0; // Cannot fold this operation.
11553 }
11554
11555 // Check to see if all arguments are the same operation.
11556 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011557 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11558 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011559 return 0;
11560 if (CastSrcTy) {
11561 if (I->getOperand(0)->getType() != CastSrcTy)
11562 return 0; // Cast operation must match.
11563 } else if (I->getOperand(1) != ConstantOp) {
11564 return 0;
11565 }
11566 }
11567
11568 // Okay, they are all the same operation. Create a new PHI node of the
11569 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011570 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11571 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011572 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011573
11574 Value *InVal = FirstInst->getOperand(0);
11575 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011576
11577 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011578 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11579 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11580 if (NewInVal != InVal)
11581 InVal = 0;
11582 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11583 }
11584
11585 Value *PhiVal;
11586 if (InVal) {
11587 // The new PHI unions all of the same values together. This is really
11588 // common, so we handle it intelligently here for compile-time speed.
11589 PhiVal = InVal;
11590 delete NewPN;
11591 } else {
11592 InsertNewInstBefore(NewPN, PN);
11593 PhiVal = NewPN;
11594 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011595
Chris Lattnerbac32862004-11-14 19:13:23 +000011596 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011597 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011598 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011599
Chris Lattner54545ac2008-04-29 17:13:43 +000011600 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011601 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011602
Chris Lattner751a3622009-11-01 20:04:24 +000011603 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11604 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11605 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011606}
Chris Lattnera1be5662002-05-02 17:06:02 +000011607
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011608/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11609/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011610static bool DeadPHICycle(PHINode *PN,
11611 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011612 if (PN->use_empty()) return true;
11613 if (!PN->hasOneUse()) return false;
11614
11615 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011616 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011617 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011618
11619 // Don't scan crazily complex things.
11620 if (PotentiallyDeadPHIs.size() == 16)
11621 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011622
11623 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11624 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011625
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011626 return false;
11627}
11628
Chris Lattnercf5008a2007-11-06 21:52:06 +000011629/// PHIsEqualValue - Return true if this phi node is always equal to
11630/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11631/// z = some value; x = phi (y, z); y = phi (x, z)
11632static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11633 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11634 // See if we already saw this PHI node.
11635 if (!ValueEqualPHIs.insert(PN))
11636 return true;
11637
11638 // Don't scan crazily complex things.
11639 if (ValueEqualPHIs.size() == 16)
11640 return false;
11641
11642 // Scan the operands to see if they are either phi nodes or are equal to
11643 // the value.
11644 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11645 Value *Op = PN->getIncomingValue(i);
11646 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11647 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11648 return false;
11649 } else if (Op != NonPhiInVal)
11650 return false;
11651 }
11652
11653 return true;
11654}
11655
11656
Chris Lattner9956c052009-11-08 19:23:30 +000011657namespace {
11658struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011659 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011660 unsigned Shift; // The amount shifted.
11661 Instruction *Inst; // The trunc instruction.
11662
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011663 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11664 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011665
11666 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011667 if (PHIId < RHS.PHIId) return true;
11668 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011669 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011670 if (Shift > RHS.Shift) return false;
11671 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011672 RHS.Inst->getType()->getPrimitiveSizeInBits();
11673 }
11674};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011675
11676struct LoweredPHIRecord {
11677 PHINode *PN; // The PHI that was lowered.
11678 unsigned Shift; // The amount shifted.
11679 unsigned Width; // The width extracted.
11680
11681 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11682 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11683
11684 // Ctor form used by DenseMap.
11685 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11686 : PN(pn), Shift(Sh), Width(0) {}
11687};
11688}
11689
11690namespace llvm {
11691 template<>
11692 struct DenseMapInfo<LoweredPHIRecord> {
11693 static inline LoweredPHIRecord getEmptyKey() {
11694 return LoweredPHIRecord(0, 0);
11695 }
11696 static inline LoweredPHIRecord getTombstoneKey() {
11697 return LoweredPHIRecord(0, 1);
11698 }
11699 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11700 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11701 (Val.Width>>3);
11702 }
11703 static bool isEqual(const LoweredPHIRecord &LHS,
11704 const LoweredPHIRecord &RHS) {
11705 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11706 LHS.Width == RHS.Width;
11707 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011708 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011709 template <>
11710 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011711}
11712
11713
11714/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11715/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11716/// so, we split the PHI into the various pieces being extracted. This sort of
11717/// thing is introduced when SROA promotes an aggregate to large integer values.
11718///
11719/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11720/// inttoptr. We should produce new PHIs in the right type.
11721///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011722Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11723 // PHIUsers - Keep track of all of the truncated values extracted from a set
11724 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011725 SmallVector<PHIUsageRecord, 16> PHIUsers;
11726
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011727 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11728 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11729 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11730 // check the uses of (to ensure they are all extracts).
11731 SmallVector<PHINode*, 8> PHIsToSlice;
11732 SmallPtrSet<PHINode*, 8> PHIsInspected;
11733
11734 PHIsToSlice.push_back(&FirstPhi);
11735 PHIsInspected.insert(&FirstPhi);
11736
11737 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11738 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011739
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011740 // Scan the input list of the PHI. If any input is an invoke, and if the
11741 // input is defined in the predecessor, then we won't be split the critical
11742 // edge which is required to insert a truncate. Because of this, we have to
11743 // bail out.
11744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11745 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11746 if (II == 0) continue;
11747 if (II->getParent() != PN->getIncomingBlock(i))
11748 continue;
11749
11750 // If we have a phi, and if it's directly in the predecessor, then we have
11751 // a critical edge where we need to put the truncate. Since we can't
11752 // split the edge in instcombine, we have to bail out.
11753 return 0;
11754 }
11755
11756
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011757 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11758 UI != E; ++UI) {
11759 Instruction *User = cast<Instruction>(*UI);
11760
11761 // If the user is a PHI, inspect its uses recursively.
11762 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11763 if (PHIsInspected.insert(UserPN))
11764 PHIsToSlice.push_back(UserPN);
11765 continue;
11766 }
11767
11768 // Truncates are always ok.
11769 if (isa<TruncInst>(User)) {
11770 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11771 continue;
11772 }
11773
11774 // Otherwise it must be a lshr which can only be used by one trunc.
11775 if (User->getOpcode() != Instruction::LShr ||
11776 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11777 !isa<ConstantInt>(User->getOperand(1)))
11778 return 0;
11779
11780 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11781 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011782 }
Chris Lattner9956c052009-11-08 19:23:30 +000011783 }
11784
11785 // If we have no users, they must be all self uses, just nuke the PHI.
11786 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011787 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011788
11789 // If this phi node is transformable, create new PHIs for all the pieces
11790 // extracted out of it. First, sort the users by their offset and size.
11791 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11792
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011793 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11794 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11795 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11796 );
Chris Lattner9956c052009-11-08 19:23:30 +000011797
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011798 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11799 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011800 DenseMap<BasicBlock*, Value*> PredValues;
11801
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011802 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11803 // introduce redundant PHIs.
11804 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11805
11806 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11807 unsigned PHIId = PHIUsers[UserI].PHIId;
11808 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011809 unsigned Offset = PHIUsers[UserI].Shift;
11810 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011811
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011812 PHINode *EltPHI;
11813
11814 // If we've already lowered a user like this, reuse the previously lowered
11815 // value.
11816 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011817
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011818 // Otherwise, Create the new PHI node for this user.
11819 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11820 assert(EltPHI->getType() != PN->getType() &&
11821 "Truncate didn't shrink phi?");
11822
11823 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11824 BasicBlock *Pred = PN->getIncomingBlock(i);
11825 Value *&PredVal = PredValues[Pred];
11826
11827 // If we already have a value for this predecessor, reuse it.
11828 if (PredVal) {
11829 EltPHI->addIncoming(PredVal, Pred);
11830 continue;
11831 }
Chris Lattner9956c052009-11-08 19:23:30 +000011832
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011833 // Handle the PHI self-reuse case.
11834 Value *InVal = PN->getIncomingValue(i);
11835 if (InVal == PN) {
11836 PredVal = EltPHI;
11837 EltPHI->addIncoming(PredVal, Pred);
11838 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011839 }
11840
11841 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011842 // If the incoming value was a PHI, and if it was one of the PHIs we
11843 // already rewrote it, just use the lowered value.
11844 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11845 PredVal = Res;
11846 EltPHI->addIncoming(PredVal, Pred);
11847 continue;
11848 }
11849 }
11850
11851 // Otherwise, do an extract in the predecessor.
11852 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11853 Value *Res = InVal;
11854 if (Offset)
11855 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11856 Offset), "extract");
11857 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11858 PredVal = Res;
11859 EltPHI->addIncoming(Res, Pred);
11860
11861 // If the incoming value was a PHI, and if it was one of the PHIs we are
11862 // rewriting, we will ultimately delete the code we inserted. This
11863 // means we need to revisit that PHI to make sure we extract out the
11864 // needed piece.
11865 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11866 if (PHIsInspected.count(OldInVal)) {
11867 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11868 OldInVal)-PHIsToSlice.begin();
11869 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11870 cast<Instruction>(Res)));
11871 ++UserE;
11872 }
Chris Lattner9956c052009-11-08 19:23:30 +000011873 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011874 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011875
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011876 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11877 << *EltPHI << '\n');
11878 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011879 }
Chris Lattner9956c052009-11-08 19:23:30 +000011880
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011881 // Replace the use of this piece with the PHI node.
11882 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011883 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011884
11885 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11886 // with undefs.
11887 Value *Undef = UndefValue::get(FirstPhi.getType());
11888 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11889 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11890 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011891}
11892
Chris Lattner473945d2002-05-06 18:06:38 +000011893// PHINode simplification
11894//
Chris Lattner7e708292002-06-25 16:13:24 +000011895Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011896 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011897 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011898
Owen Anderson7e057142006-07-10 22:03:18 +000011899 if (Value *V = PN.hasConstantValue())
11900 return ReplaceInstUsesWith(PN, V);
11901
Owen Anderson7e057142006-07-10 22:03:18 +000011902 // If all PHI operands are the same operation, pull them through the PHI,
11903 // reducing code size.
11904 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011905 isa<Instruction>(PN.getIncomingValue(1)) &&
11906 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11907 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11908 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11909 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011910 PN.getIncomingValue(0)->hasOneUse())
11911 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11912 return Result;
11913
11914 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11915 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11916 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011917 if (PN.hasOneUse()) {
11918 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11919 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011920 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011921 PotentiallyDeadPHIs.insert(&PN);
11922 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011923 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011924 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011925
11926 // If this phi has a single use, and if that use just computes a value for
11927 // the next iteration of a loop, delete the phi. This occurs with unused
11928 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11929 // common case here is good because the only other things that catch this
11930 // are induction variable analysis (sometimes) and ADCE, which is only run
11931 // late.
11932 if (PHIUser->hasOneUse() &&
11933 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11934 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011935 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011936 }
11937 }
Owen Anderson7e057142006-07-10 22:03:18 +000011938
Chris Lattnercf5008a2007-11-06 21:52:06 +000011939 // We sometimes end up with phi cycles that non-obviously end up being the
11940 // same value, for example:
11941 // z = some value; x = phi (y, z); y = phi (x, z)
11942 // where the phi nodes don't necessarily need to be in the same block. Do a
11943 // quick check to see if the PHI node only contains a single non-phi value, if
11944 // so, scan to see if the phi cycle is actually equal to that value.
11945 {
11946 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11947 // Scan for the first non-phi operand.
11948 while (InValNo != NumOperandVals &&
11949 isa<PHINode>(PN.getIncomingValue(InValNo)))
11950 ++InValNo;
11951
11952 if (InValNo != NumOperandVals) {
11953 Value *NonPhiInVal = PN.getOperand(InValNo);
11954
11955 // Scan the rest of the operands to see if there are any conflicts, if so
11956 // there is no need to recursively scan other phis.
11957 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11958 Value *OpVal = PN.getIncomingValue(InValNo);
11959 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11960 break;
11961 }
11962
11963 // If we scanned over all operands, then we have one unique value plus
11964 // phi values. Scan PHI nodes to see if they all merge in each other or
11965 // the value.
11966 if (InValNo == NumOperandVals) {
11967 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11968 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11969 return ReplaceInstUsesWith(PN, NonPhiInVal);
11970 }
11971 }
11972 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011973
Dan Gohman5b097012009-10-31 14:22:52 +000011974 // If there are multiple PHIs, sort their operands so that they all list
11975 // the blocks in the same order. This will help identical PHIs be eliminated
11976 // by other passes. Other passes shouldn't depend on this for correctness
11977 // however.
11978 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11979 if (&PN != FirstPN)
11980 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011981 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011982 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11983 if (BBA != BBB) {
11984 Value *VA = PN.getIncomingValue(i);
11985 unsigned j = PN.getBasicBlockIndex(BBB);
11986 Value *VB = PN.getIncomingValue(j);
11987 PN.setIncomingBlock(i, BBB);
11988 PN.setIncomingValue(i, VB);
11989 PN.setIncomingBlock(j, BBA);
11990 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011991 // NOTE: Instcombine normally would want us to "return &PN" if we
11992 // modified any of the operands of an instruction. However, since we
11993 // aren't adding or removing uses (just rearranging them) we don't do
11994 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011995 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011996 }
11997
Chris Lattner9956c052009-11-08 19:23:30 +000011998 // If this is an integer PHI and we know that it has an illegal type, see if
11999 // it is only used by trunc or trunc(lshr) operations. If so, we split the
12000 // PHI into the various pieces being extracted. This sort of thing is
12001 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000012002 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000012003 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
12004 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
12005 return Res;
12006
Chris Lattner60921c92003-12-19 05:58:40 +000012007 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000012008}
12009
Chris Lattner7e708292002-06-25 16:13:24 +000012010Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012011 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
12012
12013 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
12014 return ReplaceInstUsesWith(GEP, V);
12015
Chris Lattner620ce142004-05-07 22:09:22 +000012016 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012017
Chris Lattnere87597f2004-10-16 18:11:37 +000012018 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012019 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012020
Chris Lattner28977af2004-04-05 01:30:19 +000012021 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000012022 if (TD) {
12023 bool MadeChange = false;
12024 unsigned PtrSize = TD->getPointerSizeInBits();
12025
12026 gep_type_iterator GTI = gep_type_begin(GEP);
12027 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
12028 I != E; ++I, ++GTI) {
12029 if (!isa<SequentialType>(*GTI)) continue;
12030
Chris Lattnercb69a4e2004-04-07 18:38:20 +000012031 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000012032 // to what we need. If narrower, sign-extend it to what we need. This
12033 // explicit cast can make subsequent optimizations more obvious.
12034 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000012035 if (OpBits == PtrSize)
12036 continue;
12037
Chris Lattner2345d1d2009-08-30 20:01:10 +000012038 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012039 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000012040 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000012041 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000012042 }
Chris Lattner28977af2004-04-05 01:30:19 +000012043
Chris Lattner90ac28c2002-08-02 19:29:35 +000012044 // Combine Indices - If the source pointer to this getelementptr instruction
12045 // is a getelementptr instruction, combine the indices of the two
12046 // getelementptr instructions into a single instruction.
12047 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012048 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000012049 // Note that if our source is a gep chain itself that we wait for that
12050 // chain to be resolved before we perform this transformation. This
12051 // avoids us creating a TON of code in some cases.
12052 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012053 if (GetElementPtrInst *SrcGEP =
12054 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12055 if (SrcGEP->getNumOperands() == 2)
12056 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000012057
Chris Lattner72588fc2007-02-15 22:48:32 +000012058 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000012059
12060 // Find out whether the last index in the source GEP is a sequential idx.
12061 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000012062 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12063 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000012064 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012065
Chris Lattner90ac28c2002-08-02 19:29:35 +000012066 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000012067 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000012068 // Replace: gep (gep %P, long B), long A, ...
12069 // With: T = long A+B; gep %P, T, ...
12070 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012071 Value *Sum;
12072 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12073 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000012074 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012075 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000012076 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012077 Sum = SO1;
12078 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000012079 // If they aren't the same type, then the input hasn't been processed
12080 // by the loop above yet (which canonicalizes sequential index types to
12081 // intptr_t). Just avoid transforming this until the input has been
12082 // normalized.
12083 if (SO1->getType() != GO1->getType())
12084 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012085 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000012086 }
Chris Lattner620ce142004-05-07 22:09:22 +000012087
Chris Lattnerab984842009-08-30 05:30:55 +000012088 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012089 if (Src->getNumOperands() == 2) {
12090 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000012091 GEP.setOperand(1, Sum);
12092 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000012093 }
Chris Lattnerab984842009-08-30 05:30:55 +000012094 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012095 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000012096 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000012097 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000012098 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012099 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000012100 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000012101 Indices.append(Src->op_begin()+1, Src->op_end());
12102 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000012103 }
12104
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012105 if (!Indices.empty())
12106 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12107 Src->isInBounds()) ?
12108 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12109 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012110 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000012111 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000012112 }
12113
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012114 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12115 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000012116 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000012117
Chris Lattner2de23192009-08-30 20:38:21 +000012118 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12119 // want to change the gep until the bitcasts are eliminated.
12120 if (getBitCastOperand(X)) {
12121 Worklist.AddValue(PtrOp);
12122 return 0;
12123 }
12124
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012125 bool HasZeroPointerIndex = false;
12126 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12127 HasZeroPointerIndex = C->isZero();
12128
Chris Lattner963f4ba2009-08-30 20:36:46 +000012129 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12130 // into : GEP [10 x i8]* X, i32 0, ...
12131 //
12132 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12133 // into : GEP i8* X, ...
12134 //
12135 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000012136 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000012137 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12138 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012139 if (const ArrayType *CATy =
12140 dyn_cast<ArrayType>(CPTy->getElementType())) {
12141 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12142 if (CATy->getElementType() == XTy->getElementType()) {
12143 // -> GEP i8* X, ...
12144 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012145 return cast<GEPOperator>(&GEP)->isInBounds() ?
12146 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12147 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012148 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12149 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000012150 }
12151
12152 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012153 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000012154 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012155 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000012156 // At this point, we know that the cast source type is a pointer
12157 // to an array of the same type as the destination pointer
12158 // array. Because the array type is never stepped over (there
12159 // is a leading zero) we can fold the cast into this GEP.
12160 GEP.setOperand(0, X);
12161 return &GEP;
12162 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012163 }
12164 }
Chris Lattnereed48272005-09-13 00:40:14 +000012165 } else if (GEP.getNumOperands() == 2) {
12166 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012167 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12168 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000012169 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12170 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012171 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000012172 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12173 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000012174 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000012175 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000012176 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012177 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12178 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012179 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012180 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012181 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012182 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000012183
12184 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012185 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000012186 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012187 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000012188
Chris Lattner4de84762010-01-04 07:02:48 +000012189 if (TD && isa<ArrayType>(SrcElTy) &&
12190 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000012191 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000012192 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012193
12194 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12195 // allow either a mul, shift, or constant here.
12196 Value *NewIdx = 0;
12197 ConstantInt *Scale = 0;
12198 if (ArrayEltSize == 1) {
12199 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000012200 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012201 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012202 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012203 Scale = CI;
12204 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12205 if (Inst->getOpcode() == Instruction::Shl &&
12206 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000012207 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12208 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000012209 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000012210 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012211 NewIdx = Inst->getOperand(0);
12212 } else if (Inst->getOpcode() == Instruction::Mul &&
12213 isa<ConstantInt>(Inst->getOperand(1))) {
12214 Scale = cast<ConstantInt>(Inst->getOperand(1));
12215 NewIdx = Inst->getOperand(0);
12216 }
12217 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012218
Chris Lattner7835cdd2005-09-13 18:36:04 +000012219 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012220 // out, perform the transformation. Note, we don't know whether Scale is
12221 // signed or not. We'll use unsigned version of division/modulo
12222 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000012223 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012224 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012225 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012226 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000012227 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000012228 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12229 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012230 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000012231 }
12232
12233 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000012234 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +000012235 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000012236 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012237 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12238 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12239 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012240 // The NewGEP must be pointer typed, so must the old one -> BitCast
12241 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012242 }
12243 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012244 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012245 }
Chris Lattner58407792009-01-09 04:53:57 +000012246
Chris Lattner46cd5a12009-01-09 05:44:56 +000012247 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000012248 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000012249 /// Y = gep X, <...constant indices...>
12250 /// into a gep of the original struct. This is important for SROA and alias
12251 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000012252 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012253 if (TD &&
12254 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012255 // Determine how much the GEP moves the pointer. We are guaranteed to get
12256 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000012257 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000012258 int64_t Offset = OffsetV->getSExtValue();
12259
12260 // If this GEP instruction doesn't move the pointer, just replace the GEP
12261 // with a bitcast of the real input to the dest type.
12262 if (Offset == 0) {
12263 // If the bitcast is of an allocation, and the allocation will be
12264 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012265 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012266 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012267 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12268 if (Instruction *I = visitBitCast(*BCI)) {
12269 if (I != BCI) {
12270 I->takeName(BCI);
12271 BCI->getParent()->getInstList().insert(BCI, I);
12272 ReplaceInstUsesWith(*BCI, I);
12273 }
12274 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012275 }
Chris Lattner58407792009-01-09 04:53:57 +000012276 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012277 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012278 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012279
12280 // Otherwise, if the offset is non-zero, we need to find out if there is a
12281 // field at Offset in 'A's type. If so, we can pull the cast through the
12282 // GEP.
12283 SmallVector<Value*, 8> NewIndices;
12284 const Type *InTy =
12285 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner4de84762010-01-04 07:02:48 +000012286 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012287 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12288 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12289 NewIndices.end()) :
12290 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12291 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012292
12293 if (NGEP->getType() == GEP.getType())
12294 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012295 NGEP->takeName(&GEP);
12296 return new BitCastInst(NGEP, GEP.getType());
12297 }
Chris Lattner58407792009-01-09 04:53:57 +000012298 }
12299 }
12300
Chris Lattner8a2a3112001-12-14 16:52:21 +000012301 return 0;
12302}
12303
Victor Hernandez7b929da2009-10-23 21:09:37 +000012304Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012305 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012306 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012307 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12308 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012309 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012310 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012311 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012312 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012313
Chris Lattner0864acf2002-11-04 16:18:53 +000012314 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012315 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012316 //
12317 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012318 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012319
12320 // Now that I is pointing to the first non-allocation-inst in the block,
12321 // insert our getelementptr instruction...
12322 //
Chris Lattner4de84762010-01-04 07:02:48 +000012323 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +000012324 Value *Idx[2];
12325 Idx[0] = NullIdx;
12326 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012327 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12328 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012329
12330 // Now make everything use the getelementptr instead of the original
12331 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012332 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012333 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012334 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012335 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012336 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012337
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012338 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012339 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012340 // Note that we only do this for alloca's, because malloc should allocate
12341 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012342 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012343 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012344
12345 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12346 if (AI.getAlignment() == 0)
12347 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12348 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012349
Chris Lattner0864acf2002-11-04 16:18:53 +000012350 return 0;
12351}
12352
Victor Hernandez66284e02009-10-24 04:23:03 +000012353Instruction *InstCombiner::visitFree(Instruction &FI) {
12354 Value *Op = FI.getOperand(1);
12355
12356 // free undef -> unreachable.
12357 if (isa<UndefValue>(Op)) {
12358 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +000012359 new StoreInst(ConstantInt::getTrue(FI.getContext()),
12360 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +000012361 return EraseInstFromFunction(FI);
12362 }
12363
12364 // If we have 'free null' delete the instruction. This can happen in stl code
12365 // when lots of inlining happens.
12366 if (isa<ConstantPointerNull>(Op))
12367 return EraseInstFromFunction(FI);
12368
Victor Hernandez046e78c2009-10-26 23:43:48 +000012369 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012370 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012371 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12372 if (Op->hasOneUse() && CI->hasOneUse()) {
12373 EraseInstFromFunction(FI);
12374 EraseInstFromFunction(*CI);
12375 return EraseInstFromFunction(*cast<Instruction>(Op));
12376 }
12377 } else {
12378 // Op is a call to malloc
12379 if (Op->hasOneUse()) {
12380 EraseInstFromFunction(FI);
12381 return EraseInstFromFunction(*cast<Instruction>(Op));
12382 }
12383 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012384 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012385
12386 return 0;
12387}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012388
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012389/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012390static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012391 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012392 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012393 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000012394
Mon P Wang6753f952009-02-07 22:19:29 +000012395 const PointerType *DestTy = cast<PointerType>(CI->getType());
12396 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012397 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012398
12399 // If the address spaces don't match, don't eliminate the cast.
12400 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12401 return 0;
12402
Chris Lattnerb89e0712004-07-13 01:49:43 +000012403 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012404
Reid Spencer42230162007-01-22 05:51:25 +000012405 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012406 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012407 // If the source is an array, the code below will not succeed. Check to
12408 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12409 // constants.
12410 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12411 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12412 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012413 Value *Idxs[2];
Chris Lattner4de84762010-01-04 07:02:48 +000012414 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
Chris Lattnere00c43f2009-10-22 06:44:07 +000012415 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012416 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012417 SrcTy = cast<PointerType>(CastOp->getType());
12418 SrcPTy = SrcTy->getElementType();
12419 }
12420
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012421 if (IC.getTargetData() &&
12422 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012423 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012424 // Do not allow turning this into a load of an integer, which is then
12425 // casted to a pointer, this pessimizes pointer analysis a lot.
12426 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012427 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12428 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012429
Chris Lattnerf9527852005-01-31 04:50:46 +000012430 // Okay, we are casting from one integer or pointer type to another of
12431 // the same size. Instead of casting the pointer before the load, cast
12432 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012433 Value *NewLoad =
12434 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012435 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012436 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012437 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012438 }
12439 }
12440 return 0;
12441}
12442
Chris Lattner833b8a42003-06-26 05:06:25 +000012443Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12444 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012445
Dan Gohman9941f742007-07-20 16:34:21 +000012446 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012447 if (TD) {
12448 unsigned KnownAlign =
12449 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12450 if (KnownAlign >
12451 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12452 LI.getAlignment()))
12453 LI.setAlignment(KnownAlign);
12454 }
Dan Gohman9941f742007-07-20 16:34:21 +000012455
Chris Lattner963f4ba2009-08-30 20:36:46 +000012456 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012457 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012458 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012459 return Res;
12460
12461 // None of the following transforms are legal for volatile loads.
12462 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012463
Dan Gohman2276a7b2008-10-15 23:19:35 +000012464 // Do really simple store-to-load forwarding and load CSE, to catch cases
12465 // where there are several consequtive memory accesses to the same location,
12466 // separated by a few arithmetic operations.
12467 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012468 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12469 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012470
Chris Lattner878e4942009-10-22 06:25:11 +000012471 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012472 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12473 const Value *GEPI0 = GEPI->getOperand(0);
12474 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012475 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012476 // Insert a new store to null instruction before the load to indicate
12477 // that this code is not reachable. We do this instead of inserting
12478 // an unreachable instruction directly because we cannot modify the
12479 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012480 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012481 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012482 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012483 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012484 }
Chris Lattner37366c12005-05-01 04:24:53 +000012485
Chris Lattner878e4942009-10-22 06:25:11 +000012486 // load null/undef -> unreachable
12487 // TODO: Consider a target hook for valid address spaces for this xform.
12488 if (isa<UndefValue>(Op) ||
12489 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12490 // Insert a new store to null instruction before the load to indicate that
12491 // this code is not reachable. We do this instead of inserting an
12492 // unreachable instruction directly because we cannot modify the CFG.
12493 new StoreInst(UndefValue::get(LI.getType()),
12494 Constant::getNullValue(Op->getType()), &LI);
12495 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012496 }
Chris Lattner878e4942009-10-22 06:25:11 +000012497
12498 // Instcombine load (constantexpr_cast global) -> cast (load global)
12499 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12500 if (CE->isCast())
12501 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12502 return Res;
12503
Chris Lattner37366c12005-05-01 04:24:53 +000012504 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012505 // Change select and PHI nodes to select values instead of addresses: this
12506 // helps alias analysis out a lot, allows many others simplifications, and
12507 // exposes redundancy in the code.
12508 //
12509 // Note that we cannot do the transformation unless we know that the
12510 // introduced loads cannot trap! Something like this is valid as long as
12511 // the condition is always false: load (select bool %C, int* null, int* %G),
12512 // but it would not be valid if we transformed it to load from null
12513 // unconditionally.
12514 //
12515 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12516 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012517 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12518 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012519 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12520 SI->getOperand(1)->getName()+".val");
12521 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12522 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012523 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012524 }
12525
Chris Lattner684fe212004-09-23 15:46:00 +000012526 // load (select (cond, null, P)) -> load P
12527 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12528 if (C->isNullValue()) {
12529 LI.setOperand(0, SI->getOperand(2));
12530 return &LI;
12531 }
12532
12533 // load (select (cond, P, null)) -> load P
12534 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12535 if (C->isNullValue()) {
12536 LI.setOperand(0, SI->getOperand(1));
12537 return &LI;
12538 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012539 }
12540 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012541 return 0;
12542}
12543
Reid Spencer55af2b52007-01-19 21:20:31 +000012544/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012545/// when possible. This makes it generally easy to do alias analysis and/or
12546/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012547static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12548 User *CI = cast<User>(SI.getOperand(1));
12549 Value *CastOp = CI->getOperand(0);
12550
12551 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012552 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12553 if (SrcTy == 0) return 0;
12554
12555 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012556
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012557 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12558 return 0;
12559
Chris Lattner3914f722009-01-24 01:00:13 +000012560 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12561 /// to its first element. This allows us to handle things like:
12562 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12563 /// on 32-bit hosts.
12564 SmallVector<Value*, 4> NewGEPIndices;
12565
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012566 // If the source is an array, the code below will not succeed. Check to
12567 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12568 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012569 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12570 // Index through pointer.
Chris Lattner4de84762010-01-04 07:02:48 +000012571 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012572 NewGEPIndices.push_back(Zero);
12573
12574 while (1) {
12575 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012576 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012577 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012578 NewGEPIndices.push_back(Zero);
12579 SrcPTy = STy->getElementType(0);
12580 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12581 NewGEPIndices.push_back(Zero);
12582 SrcPTy = ATy->getElementType();
12583 } else {
12584 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012585 }
Chris Lattner3914f722009-01-24 01:00:13 +000012586 }
12587
Owen Andersondebcb012009-07-29 22:17:13 +000012588 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012589 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012590
12591 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12592 return 0;
12593
Chris Lattner71759c42009-01-16 20:12:52 +000012594 // If the pointers point into different address spaces or if they point to
12595 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012596 if (!IC.getTargetData() ||
12597 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012598 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012599 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12600 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012601 return 0;
12602
12603 // Okay, we are casting from one integer or pointer type to another of
12604 // the same size. Instead of casting the pointer before
12605 // the store, cast the value to be stored.
12606 Value *NewCast;
12607 Value *SIOp0 = SI.getOperand(0);
12608 Instruction::CastOps opcode = Instruction::BitCast;
12609 const Type* CastSrcTy = SIOp0->getType();
12610 const Type* CastDstTy = SrcPTy;
12611 if (isa<PointerType>(CastDstTy)) {
12612 if (CastSrcTy->isInteger())
12613 opcode = Instruction::IntToPtr;
12614 } else if (isa<IntegerType>(CastDstTy)) {
12615 if (isa<PointerType>(SIOp0->getType()))
12616 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012617 }
Chris Lattner3914f722009-01-24 01:00:13 +000012618
12619 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12620 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012621 if (!NewGEPIndices.empty())
12622 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12623 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012624
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012625 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12626 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012627 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012628}
12629
Chris Lattner4aebaee2008-11-27 08:56:30 +000012630/// equivalentAddressValues - Test if A and B will obviously have the same
12631/// value. This includes recognizing that %t0 and %t1 will have the same
12632/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012633/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012634/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012635/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012636/// %t2 = load i32* %t1
12637///
12638static bool equivalentAddressValues(Value *A, Value *B) {
12639 // Test if the values are trivially equivalent.
12640 if (A == B) return true;
12641
12642 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012643 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12644 // its only used to compare two uses within the same basic block, which
12645 // means that they'll always either have the same value or one of them
12646 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012647 if (isa<BinaryOperator>(A) ||
12648 isa<CastInst>(A) ||
12649 isa<PHINode>(A) ||
12650 isa<GetElementPtrInst>(A))
12651 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012652 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012653 return true;
12654
12655 // Otherwise they may not be equivalent.
12656 return false;
12657}
12658
Dale Johannesen4945c652009-03-03 21:26:39 +000012659// If this instruction has two uses, one of which is a llvm.dbg.declare,
12660// return the llvm.dbg.declare.
12661DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12662 if (!V->hasNUses(2))
12663 return 0;
12664 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12665 UI != E; ++UI) {
12666 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12667 return DI;
12668 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12669 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12670 return DI;
12671 }
12672 }
12673 return 0;
12674}
12675
Chris Lattner2f503e62005-01-31 05:36:43 +000012676Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12677 Value *Val = SI.getOperand(0);
12678 Value *Ptr = SI.getOperand(1);
12679
Chris Lattner836692d2007-01-15 06:51:56 +000012680 // If the RHS is an alloca with a single use, zapify the store, making the
12681 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012682 // If the RHS is an alloca with a two uses, the other one being a
12683 // llvm.dbg.declare, zapify the store and the declare, making the
12684 // alloca dead. We must do this to prevent declare's from affecting
12685 // codegen.
12686 if (!SI.isVolatile()) {
12687 if (Ptr->hasOneUse()) {
12688 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012689 EraseInstFromFunction(SI);
12690 ++NumCombined;
12691 return 0;
12692 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012693 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12694 if (isa<AllocaInst>(GEP->getOperand(0))) {
12695 if (GEP->getOperand(0)->hasOneUse()) {
12696 EraseInstFromFunction(SI);
12697 ++NumCombined;
12698 return 0;
12699 }
12700 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12701 EraseInstFromFunction(*DI);
12702 EraseInstFromFunction(SI);
12703 ++NumCombined;
12704 return 0;
12705 }
12706 }
12707 }
12708 }
12709 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12710 EraseInstFromFunction(*DI);
12711 EraseInstFromFunction(SI);
12712 ++NumCombined;
12713 return 0;
12714 }
Chris Lattner836692d2007-01-15 06:51:56 +000012715 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012716
Dan Gohman9941f742007-07-20 16:34:21 +000012717 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012718 if (TD) {
12719 unsigned KnownAlign =
12720 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12721 if (KnownAlign >
12722 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12723 SI.getAlignment()))
12724 SI.setAlignment(KnownAlign);
12725 }
Dan Gohman9941f742007-07-20 16:34:21 +000012726
Dale Johannesenacb51a32009-03-03 01:43:03 +000012727 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012728 // stores to the same location, separated by a few arithmetic operations. This
12729 // situation often occurs with bitfield accesses.
12730 BasicBlock::iterator BBI = &SI;
12731 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12732 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012733 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012734 // Don't count debug info directives, lest they affect codegen,
12735 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12736 // It is necessary for correctness to skip those that feed into a
12737 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012738 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012739 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012740 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012741 continue;
12742 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012743
12744 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12745 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012746 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12747 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012748 ++NumDeadStore;
12749 ++BBI;
12750 EraseInstFromFunction(*PrevSI);
12751 continue;
12752 }
12753 break;
12754 }
12755
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012756 // If this is a load, we have to stop. However, if the loaded value is from
12757 // the pointer we're loading and is producing the pointer we're storing,
12758 // then *this* store is dead (X = load P; store X -> P).
12759 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012760 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12761 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012762 EraseInstFromFunction(SI);
12763 ++NumCombined;
12764 return 0;
12765 }
12766 // Otherwise, this is a load from some other location. Stores before it
12767 // may not be dead.
12768 break;
12769 }
12770
Chris Lattner9ca96412006-02-08 03:25:32 +000012771 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012772 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012773 break;
12774 }
12775
12776
12777 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012778
12779 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012780 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012781 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012782 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012783 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012784 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012785 ++NumCombined;
12786 }
12787 return 0; // Do not modify these!
12788 }
12789
12790 // store undef, Ptr -> noop
12791 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012792 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012793 ++NumCombined;
12794 return 0;
12795 }
12796
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012797 // If the pointer destination is a cast, see if we can fold the cast into the
12798 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012799 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012800 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12801 return Res;
12802 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012803 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012804 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12805 return Res;
12806
Chris Lattner408902b2005-09-12 23:23:25 +000012807
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012808 // If this store is the last instruction in the basic block (possibly
12809 // excepting debug info instructions and the pointer bitcasts that feed
12810 // into them), and if the block ends with an unconditional branch, try
12811 // to move it to the successor block.
12812 BBI = &SI;
12813 do {
12814 ++BBI;
12815 } while (isa<DbgInfoIntrinsic>(BBI) ||
12816 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012817 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012818 if (BI->isUnconditional())
12819 if (SimplifyStoreAtEndOfBlock(SI))
12820 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012821
Chris Lattner2f503e62005-01-31 05:36:43 +000012822 return 0;
12823}
12824
Chris Lattner3284d1f2007-04-15 00:07:55 +000012825/// SimplifyStoreAtEndOfBlock - Turn things like:
12826/// if () { *P = v1; } else { *P = v2 }
12827/// into a phi node with a store in the successor.
12828///
Chris Lattner31755a02007-04-15 01:02:18 +000012829/// Simplify things like:
12830/// *P = v1; if () { *P = v2; }
12831/// into a phi node with a store in the successor.
12832///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012833bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12834 BasicBlock *StoreBB = SI.getParent();
12835
12836 // Check to see if the successor block has exactly two incoming edges. If
12837 // so, see if the other predecessor contains a store to the same location.
12838 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012839 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012840
12841 // Determine whether Dest has exactly two predecessors and, if so, compute
12842 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012843 pred_iterator PI = pred_begin(DestBB);
12844 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012845 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012846 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012847 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012848 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012849 return false;
12850
12851 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012852 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012853 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012854 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012855 }
Chris Lattner31755a02007-04-15 01:02:18 +000012856 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012857 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012858
12859 // Bail out if all the relevant blocks aren't distinct (this can happen,
12860 // for example, if SI is in an infinite loop)
12861 if (StoreBB == DestBB || OtherBB == DestBB)
12862 return false;
12863
Chris Lattner31755a02007-04-15 01:02:18 +000012864 // Verify that the other block ends in a branch and is not otherwise empty.
12865 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012866 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012867 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012868 return false;
12869
Chris Lattner31755a02007-04-15 01:02:18 +000012870 // If the other block ends in an unconditional branch, check for the 'if then
12871 // else' case. there is an instruction before the branch.
12872 StoreInst *OtherStore = 0;
12873 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012874 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012875 // Skip over debugging info.
12876 while (isa<DbgInfoIntrinsic>(BBI) ||
12877 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12878 if (BBI==OtherBB->begin())
12879 return false;
12880 --BBI;
12881 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012882 // If this isn't a store, isn't a store to the same location, or if the
12883 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012884 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012885 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12886 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012887 return false;
12888 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012889 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012890 // destinations is StoreBB, then we have the if/then case.
12891 if (OtherBr->getSuccessor(0) != StoreBB &&
12892 OtherBr->getSuccessor(1) != StoreBB)
12893 return false;
12894
12895 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012896 // if/then triangle. See if there is a store to the same ptr as SI that
12897 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012898 for (;; --BBI) {
12899 // Check to see if we find the matching store.
12900 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012901 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12902 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012903 return false;
12904 break;
12905 }
Eli Friedman6903a242008-06-13 22:02:12 +000012906 // If we find something that may be using or overwriting the stored
12907 // value, or if we run out of instructions, we can't do the xform.
12908 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012909 BBI == OtherBB->begin())
12910 return false;
12911 }
12912
12913 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012914 // make sure nothing reads or overwrites the stored value in
12915 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012916 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12917 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012918 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012919 return false;
12920 }
12921 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012922
Chris Lattner31755a02007-04-15 01:02:18 +000012923 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012924 Value *MergedVal = OtherStore->getOperand(0);
12925 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012926 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012927 PN->reserveOperandSpace(2);
12928 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012929 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12930 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012931 }
12932
12933 // Advance to a place where it is safe to insert the new store and
12934 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012935 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012936 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012937 OtherStore->isVolatile(),
12938 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012939
12940 // Nuke the old stores.
12941 EraseInstFromFunction(SI);
12942 EraseInstFromFunction(*OtherStore);
12943 ++NumCombined;
12944 return true;
12945}
12946
Chris Lattner2f503e62005-01-31 05:36:43 +000012947
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012948Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12949 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012950 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012951 BasicBlock *TrueDest;
12952 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012953 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012954 !isa<Constant>(X)) {
12955 // Swap Destinations and condition...
12956 BI.setCondition(X);
12957 BI.setSuccessor(0, FalseDest);
12958 BI.setSuccessor(1, TrueDest);
12959 return &BI;
12960 }
12961
Reid Spencere4d87aa2006-12-23 06:05:41 +000012962 // Cannonicalize fcmp_one -> fcmp_oeq
12963 FCmpInst::Predicate FPred; Value *Y;
12964 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012965 TrueDest, FalseDest)) &&
12966 BI.getCondition()->hasOneUse())
12967 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12968 FPred == FCmpInst::FCMP_OGE) {
12969 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12970 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12971
12972 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012973 BI.setSuccessor(0, FalseDest);
12974 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012975 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012976 return &BI;
12977 }
12978
12979 // Cannonicalize icmp_ne -> icmp_eq
12980 ICmpInst::Predicate IPred;
12981 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012982 TrueDest, FalseDest)) &&
12983 BI.getCondition()->hasOneUse())
12984 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12985 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12986 IPred == ICmpInst::ICMP_SGE) {
12987 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12988 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12989 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012990 BI.setSuccessor(0, FalseDest);
12991 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012992 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012993 return &BI;
12994 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012995
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012996 return 0;
12997}
Chris Lattner0864acf2002-11-04 16:18:53 +000012998
Chris Lattner46238a62004-07-03 00:26:11 +000012999Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
13000 Value *Cond = SI.getCondition();
13001 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
13002 if (I->getOpcode() == Instruction::Add)
13003 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
13004 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
13005 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013006 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000013007 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000013008 AddRHS));
13009 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000013010 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000013011 return &SI;
13012 }
13013 }
13014 return 0;
13015}
13016
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013017Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013018 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013019
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013020 if (!EV.hasIndices())
13021 return ReplaceInstUsesWith(EV, Agg);
13022
13023 if (Constant *C = dyn_cast<Constant>(Agg)) {
13024 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013025 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013026
13027 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000013028 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013029
13030 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
13031 // Extract the element indexed by the first index out of the constant
13032 Value *V = C->getOperand(*EV.idx_begin());
13033 if (EV.getNumIndices() > 1)
13034 // Extract the remaining indices out of the constant indexed by the
13035 // first index
13036 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
13037 else
13038 return ReplaceInstUsesWith(EV, V);
13039 }
13040 return 0; // Can't handle other constants
13041 }
13042 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
13043 // We're extracting from an insertvalue instruction, compare the indices
13044 const unsigned *exti, *exte, *insi, *inse;
13045 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
13046 exte = EV.idx_end(), inse = IV->idx_end();
13047 exti != exte && insi != inse;
13048 ++exti, ++insi) {
13049 if (*insi != *exti)
13050 // The insert and extract both reference distinctly different elements.
13051 // This means the extract is not influenced by the insert, and we can
13052 // replace the aggregate operand of the extract with the aggregate
13053 // operand of the insert. i.e., replace
13054 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13055 // %E = extractvalue { i32, { i32 } } %I, 0
13056 // with
13057 // %E = extractvalue { i32, { i32 } } %A, 0
13058 return ExtractValueInst::Create(IV->getAggregateOperand(),
13059 EV.idx_begin(), EV.idx_end());
13060 }
13061 if (exti == exte && insi == inse)
13062 // Both iterators are at the end: Index lists are identical. Replace
13063 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13064 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13065 // with "i32 42"
13066 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13067 if (exti == exte) {
13068 // The extract list is a prefix of the insert list. i.e. replace
13069 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13070 // %E = extractvalue { i32, { i32 } } %I, 1
13071 // with
13072 // %X = extractvalue { i32, { i32 } } %A, 1
13073 // %E = insertvalue { i32 } %X, i32 42, 0
13074 // by switching the order of the insert and extract (though the
13075 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000013076 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13077 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013078 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13079 insi, inse);
13080 }
13081 if (insi == inse)
13082 // The insert list is a prefix of the extract list
13083 // We can simply remove the common indices from the extract and make it
13084 // operate on the inserted value instead of the insertvalue result.
13085 // i.e., replace
13086 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13087 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13088 // with
13089 // %E extractvalue { i32 } { i32 42 }, 0
13090 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13091 exti, exte);
13092 }
Chris Lattner7e606e22009-11-09 07:07:56 +000013093 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13094 // We're extracting from an intrinsic, see if we're the only user, which
13095 // allows us to simplify multiple result intrinsics to simpler things that
13096 // just get one value..
13097 if (II->hasOneUse()) {
13098 // Check if we're grabbing the overflow bit or the result of a 'with
13099 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13100 // and replace it with a traditional binary instruction.
13101 switch (II->getIntrinsicID()) {
13102 case Intrinsic::uadd_with_overflow:
13103 case Intrinsic::sadd_with_overflow:
13104 if (*EV.idx_begin() == 0) { // Normal result.
13105 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13106 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13107 EraseInstFromFunction(*II);
13108 return BinaryOperator::CreateAdd(LHS, RHS);
13109 }
13110 break;
13111 case Intrinsic::usub_with_overflow:
13112 case Intrinsic::ssub_with_overflow:
13113 if (*EV.idx_begin() == 0) { // Normal result.
13114 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13115 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13116 EraseInstFromFunction(*II);
13117 return BinaryOperator::CreateSub(LHS, RHS);
13118 }
13119 break;
13120 case Intrinsic::umul_with_overflow:
13121 case Intrinsic::smul_with_overflow:
13122 if (*EV.idx_begin() == 0) { // Normal result.
13123 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13124 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13125 EraseInstFromFunction(*II);
13126 return BinaryOperator::CreateMul(LHS, RHS);
13127 }
13128 break;
13129 default:
13130 break;
13131 }
13132 }
13133 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013134 // Can't simplify extracts from other values. Note that nested extracts are
13135 // already simplified implicitely by the above (extract ( extract (insert) )
13136 // will be translated into extract ( insert ( extract ) ) first and then just
13137 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013138 return 0;
13139}
13140
Chris Lattner220b0cf2006-03-05 00:22:33 +000013141/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13142/// is to leave as a vector operation.
13143static bool CheapToScalarize(Value *V, bool isConstant) {
13144 if (isa<ConstantAggregateZero>(V))
13145 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013146 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000013147 if (isConstant) return true;
13148 // If all elts are the same, we can extract.
13149 Constant *Op0 = C->getOperand(0);
13150 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13151 if (C->getOperand(i) != Op0)
13152 return false;
13153 return true;
13154 }
13155 Instruction *I = dyn_cast<Instruction>(V);
13156 if (!I) return false;
13157
13158 // Insert element gets simplified to the inserted element or is deleted if
13159 // this is constant idx extract element and its a constant idx insertelt.
13160 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13161 isa<ConstantInt>(I->getOperand(2)))
13162 return true;
13163 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13164 return true;
13165 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13166 if (BO->hasOneUse() &&
13167 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13168 CheapToScalarize(BO->getOperand(1), isConstant)))
13169 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000013170 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13171 if (CI->hasOneUse() &&
13172 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13173 CheapToScalarize(CI->getOperand(1), isConstant)))
13174 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000013175
13176 return false;
13177}
13178
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000013179/// Read and decode a shufflevector mask.
13180///
13181/// It turns undef elements into values that are larger than the number of
13182/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000013183static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13184 unsigned NElts = SVI->getType()->getNumElements();
13185 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13186 return std::vector<unsigned>(NElts, 0);
13187 if (isa<UndefValue>(SVI->getOperand(2)))
13188 return std::vector<unsigned>(NElts, 2*NElts);
13189
13190 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013191 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000013192 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13193 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000013194 Result.push_back(NElts*2); // undef -> 8
13195 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000013196 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000013197 return Result;
13198}
13199
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013200/// FindScalarElement - Given a vector and an element number, see if the scalar
13201/// value is already around as a register, for example if it were inserted then
13202/// extracted from the vector.
Chris Lattner4de84762010-01-04 07:02:48 +000013203static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013204 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13205 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000013206 unsigned Width = PTy->getNumElements();
13207 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013208 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013209
13210 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013211 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013212 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000013213 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000013214 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013215 return CP->getOperand(EltNo);
13216 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13217 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000013218 if (!isa<ConstantInt>(III->getOperand(2)))
13219 return 0;
13220 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013221
13222 // If this is an insert to the element we are looking for, return the
13223 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000013224 if (EltNo == IIElt)
13225 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013226
13227 // Otherwise, the insertelement doesn't modify the value, recurse on its
13228 // vector input.
Chris Lattner4de84762010-01-04 07:02:48 +000013229 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000013230 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000013231 unsigned LHSWidth =
13232 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000013233 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000013234 if (InEl < LHSWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000013235 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013236 else if (InEl < LHSWidth*2)
Chris Lattner4de84762010-01-04 07:02:48 +000013237 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000013238 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013239 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013240 }
13241
13242 // Otherwise, we don't know.
13243 return 0;
13244}
13245
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013246Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000013247 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000013248 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013249 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013250
Dan Gohman07a96762007-07-16 14:29:03 +000013251 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000013252 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000013253 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013254
Reid Spencer9d6565a2007-02-15 02:26:10 +000013255 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000013256 // If vector val is constant with all elements the same, replace EI with
13257 // that element. When the elements are not identical, we cannot replace yet
13258 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000013259 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013260 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013261 if (C->getOperand(i) != op0) {
13262 op0 = 0;
13263 break;
13264 }
13265 if (op0)
13266 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013267 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013268
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013269 // If extracting a specified index from the vector, see if we can recursively
13270 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013271 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013272 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013273 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013274
13275 // If this is extracting an invalid index, turn this into undef, to avoid
13276 // crashing the code below.
13277 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013278 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013279
Chris Lattner867b99f2006-10-05 06:55:50 +000013280 // This instruction only demands the single element from the input vector.
13281 // If the input vector has a single use, simplify it based on this use
13282 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013283 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013284 APInt UndefElts(VectorWidth, 0);
13285 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013286 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013287 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013288 EI.setOperand(0, V);
13289 return &EI;
13290 }
13291 }
13292
Chris Lattner4de84762010-01-04 07:02:48 +000013293 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013294 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013295
13296 // If the this extractelement is directly using a bitcast from a vector of
13297 // the same number of elements, see if we can find the source element from
13298 // it. In this case, we will end up needing to bitcast the scalars.
13299 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13300 if (const VectorType *VT =
13301 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13302 if (VT->getNumElements() == VectorWidth)
Chris Lattner4de84762010-01-04 07:02:48 +000013303 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013304 return new BitCastInst(Elt, EI.getType());
13305 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013306 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013307
Chris Lattner73fa49d2006-05-25 22:53:38 +000013308 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013309 // Push extractelement into predecessor operation if legal and
13310 // profitable to do so
13311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13312 if (I->hasOneUse() &&
13313 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13314 Value *newEI0 =
13315 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13316 EI.getName()+".lhs");
13317 Value *newEI1 =
13318 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13319 EI.getName()+".rhs");
13320 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013321 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013322 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013323 // Extracting the inserted element?
13324 if (IE->getOperand(2) == EI.getOperand(1))
13325 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13326 // If the inserted and extracted elements are constants, they must not
13327 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013328 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013329 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013330 EI.setOperand(0, IE->getOperand(0));
13331 return &EI;
13332 }
13333 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13334 // If this is extracting an element from a shufflevector, figure out where
13335 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013336 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13337 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013338 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013339 unsigned LHSWidth =
13340 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13341
13342 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013343 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013344 else if (SrcIdx < LHSWidth*2) {
13345 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013346 Src = SVI->getOperand(1);
13347 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013348 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013349 }
Eric Christophera3500da2009-07-25 02:28:41 +000013350 return ExtractElementInst::Create(Src,
Chris Lattner4de84762010-01-04 07:02:48 +000013351 ConstantInt::get(Type::getInt32Ty(EI.getContext()),
13352 SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013353 }
13354 }
Eli Friedman2451a642009-07-18 23:06:53 +000013355 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013356 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013357 return 0;
13358}
13359
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013360/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13361/// elements from either LHS or RHS, return the shuffle mask and true.
13362/// Otherwise, return false.
13363static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner4de84762010-01-04 07:02:48 +000013364 std::vector<Constant*> &Mask) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013365 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13366 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013367 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013368
13369 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013370 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013371 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013372 }
13373
13374 if (V == LHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013375 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013376 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013377 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013378 }
13379
13380 if (V == RHS) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013381 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013382 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
13383 i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013384 return true;
Chris Lattner4de84762010-01-04 07:02:48 +000013385 }
13386
13387 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013388 // If this is an insert of an extract from some other vector, include it.
13389 Value *VecOp = IEI->getOperand(0);
13390 Value *ScalarOp = IEI->getOperand(1);
13391 Value *IdxOp = IEI->getOperand(2);
13392
Chris Lattnerd929f062006-04-27 21:14:21 +000013393 if (!isa<ConstantInt>(IdxOp))
13394 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013395 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013396
13397 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13398 // Okay, we can handle this if the vector we are insertinting into is
13399 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000013400 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013401 // If so, update the mask to reflect the inserted undef.
Chris Lattner4de84762010-01-04 07:02:48 +000013402 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
Chris Lattnerd929f062006-04-27 21:14:21 +000013403 return true;
13404 }
13405 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13406 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013407 EI->getOperand(0)->getType() == V->getType()) {
13408 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013409 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013410
13411 // This must be extracting from either LHS or RHS.
13412 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13413 // Okay, we can handle this if the vector we are insertinting into is
13414 // transitively ok.
Chris Lattner4de84762010-01-04 07:02:48 +000013415 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013416 // If so, update the mask to reflect the inserted value.
13417 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013418 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013419 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13420 ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013421 } else {
13422 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013423 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013424 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13425 ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013426
13427 }
13428 return true;
13429 }
13430 }
13431 }
13432 }
13433 }
13434 // TODO: Handle shufflevector here!
13435
13436 return false;
13437}
13438
13439/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13440/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13441/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013442static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner4de84762010-01-04 07:02:48 +000013443 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013444 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013445 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013446 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013447 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013448
13449 if (isa<UndefValue>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013450 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Chris Lattnerefb47352006-04-15 01:39:45 +000013451 return V;
13452 } else if (isa<ConstantAggregateZero>(V)) {
Chris Lattner4de84762010-01-04 07:02:48 +000013453 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013454 return V;
13455 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13456 // If this is an insert of an extract from some other vector, include it.
13457 Value *VecOp = IEI->getOperand(0);
13458 Value *ScalarOp = IEI->getOperand(1);
13459 Value *IdxOp = IEI->getOperand(2);
13460
13461 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13462 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13463 EI->getOperand(0)->getType() == V->getType()) {
13464 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013465 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13466 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013467
13468 // Either the extracted from or inserted into vector must be RHSVec,
13469 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013470 if (EI->getOperand(0) == RHS || RHS == 0) {
13471 RHS = EI->getOperand(0);
Chris Lattner4de84762010-01-04 07:02:48 +000013472 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013473 Mask[InsertedIdx % NumElts] =
Chris Lattner4de84762010-01-04 07:02:48 +000013474 ConstantInt::get(Type::getInt32Ty(V->getContext()),
13475 NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013476 return V;
13477 }
13478
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013479 if (VecOp == RHS) {
Chris Lattner4de84762010-01-04 07:02:48 +000013480 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000013481 // Everything but the extracted element is replaced with the RHS.
13482 for (unsigned i = 0; i != NumElts; ++i) {
13483 if (i != InsertedIdx)
Chris Lattner4de84762010-01-04 07:02:48 +000013484 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
13485 NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013486 }
13487 return V;
13488 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013489
13490 // If this insertelement is a chain that comes from exactly these two
13491 // vectors, return the vector and the effective shuffle.
Chris Lattner4de84762010-01-04 07:02:48 +000013492 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013493 return EI->getOperand(0);
Chris Lattnerefb47352006-04-15 01:39:45 +000013494 }
13495 }
13496 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013497 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013498
13499 // Otherwise, can't do anything fancy. Return an identity vector.
13500 for (unsigned i = 0; i != NumElts; ++i)
Chris Lattner4de84762010-01-04 07:02:48 +000013501 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013502 return V;
13503}
13504
13505Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13506 Value *VecOp = IE.getOperand(0);
13507 Value *ScalarOp = IE.getOperand(1);
13508 Value *IdxOp = IE.getOperand(2);
13509
Chris Lattner599ded12007-04-09 01:11:16 +000013510 // Inserting an undef or into an undefined place, remove this.
13511 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13512 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013513
Chris Lattnerefb47352006-04-15 01:39:45 +000013514 // If the inserted element was extracted from some other vector, and if the
13515 // indexes are constant, try to turn this into a shufflevector operation.
13516 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13517 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13518 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013519 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013520 unsigned ExtractedIdx =
13521 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013522 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013523
13524 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13525 return ReplaceInstUsesWith(IE, VecOp);
13526
13527 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013528 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013529
13530 // If we are extracting a value from a vector, then inserting it right
13531 // back into the same place, just use the input vector.
13532 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13533 return ReplaceInstUsesWith(IE, VecOp);
13534
Chris Lattnerefb47352006-04-15 01:39:45 +000013535 // If this insertelement isn't used by some other insertelement, turn it
13536 // (and any insertelements it points to), into one big shuffle.
13537 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13538 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013539 Value *RHS = 0;
Chris Lattner4de84762010-01-04 07:02:48 +000013540 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013541 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013542 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013543 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013544 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013545 }
13546 }
13547 }
13548
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013549 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13550 APInt UndefElts(VWidth, 0);
13551 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13552 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13553 return &IE;
13554
Chris Lattnerefb47352006-04-15 01:39:45 +000013555 return 0;
13556}
13557
13558
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013559Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13560 Value *LHS = SVI.getOperand(0);
13561 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013562 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013563
13564 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013565
Chris Lattner867b99f2006-10-05 06:55:50 +000013566 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013567 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013568 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013569
Dan Gohman488fbfc2008-09-09 18:11:14 +000013570 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013571
13572 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13573 return 0;
13574
Evan Cheng388df622009-02-03 10:05:09 +000013575 APInt UndefElts(VWidth, 0);
13576 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13577 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013578 LHS = SVI.getOperand(0);
13579 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013580 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013581 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013582
Chris Lattner863bcff2006-05-25 23:48:38 +000013583 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13584 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13585 if (LHS == RHS || isa<UndefValue>(LHS)) {
13586 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013587 // shuffle(undef,undef,mask) -> undef.
13588 return ReplaceInstUsesWith(SVI, LHS);
13589 }
13590
Chris Lattner863bcff2006-05-25 23:48:38 +000013591 // Remap any references to RHS to use LHS.
13592 std::vector<Constant*> Elts;
13593 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013594 if (Mask[i] >= 2*e)
Chris Lattner4de84762010-01-04 07:02:48 +000013595 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013596 else {
13597 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013598 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013599 Mask[i] = 2*e; // Turn into undef.
Chris Lattner4de84762010-01-04 07:02:48 +000013600 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Dan Gohman4ce96272008-08-06 18:17:32 +000013601 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013602 Mask[i] = Mask[i] % e; // Force to LHS.
Chris Lattner4de84762010-01-04 07:02:48 +000013603 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
13604 Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013605 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013606 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013607 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013608 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013609 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013610 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013611 LHS = SVI.getOperand(0);
13612 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013613 MadeChange = true;
13614 }
13615
Chris Lattner7b2e27922006-05-26 00:29:06 +000013616 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013617 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013618
Chris Lattner863bcff2006-05-25 23:48:38 +000013619 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13620 if (Mask[i] >= e*2) continue; // Ignore undef values.
13621 // Is this an identity shuffle of the LHS value?
13622 isLHSID &= (Mask[i] == i);
13623
13624 // Is this an identity shuffle of the RHS value?
13625 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013626 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013627
Chris Lattner863bcff2006-05-25 23:48:38 +000013628 // Eliminate identity shuffles.
13629 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13630 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013631
Chris Lattner7b2e27922006-05-26 00:29:06 +000013632 // If the LHS is a shufflevector itself, see if we can combine it with this
13633 // one without producing an unusual shuffle. Here we are really conservative:
13634 // we are absolutely afraid of producing a shuffle mask not in the input
13635 // program, because the code gen may not be smart enough to turn a merged
13636 // shuffle into two specific shuffles: it may produce worse code. As such,
13637 // we only merge two shuffles if the result is one of the two input shuffle
13638 // masks. In this case, merging the shuffles just removes one instruction,
13639 // which we know is safe. This is good for things like turning:
13640 // (splat(splat)) -> splat.
13641 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13642 if (isa<UndefValue>(RHS)) {
13643 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13644
David Greenef941d292009-11-16 21:52:23 +000013645 if (LHSMask.size() == Mask.size()) {
13646 std::vector<unsigned> NewMask;
13647 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013648 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013649 NewMask.push_back(2*e);
13650 else
13651 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013652
David Greenef941d292009-11-16 21:52:23 +000013653 // If the result mask is equal to the src shuffle or this
13654 // shuffle mask, do the replacement.
13655 if (NewMask == LHSMask || NewMask == Mask) {
13656 unsigned LHSInNElts =
13657 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13658 getNumElements();
13659 std::vector<Constant*> Elts;
13660 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13661 if (NewMask[i] >= LHSInNElts*2) {
Chris Lattner4de84762010-01-04 07:02:48 +000013662 Elts.push_back(UndefValue::get(
13663 Type::getInt32Ty(SVI.getContext())));
David Greenef941d292009-11-16 21:52:23 +000013664 } else {
Chris Lattner4de84762010-01-04 07:02:48 +000013665 Elts.push_back(ConstantInt::get(
13666 Type::getInt32Ty(SVI.getContext()),
David Greenef941d292009-11-16 21:52:23 +000013667 NewMask[i]));
13668 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013669 }
David Greenef941d292009-11-16 21:52:23 +000013670 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13671 LHSSVI->getOperand(1),
13672 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013673 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013674 }
13675 }
13676 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013677
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013678 return MadeChange ? &SVI : 0;
13679}
13680
13681
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013682
Chris Lattnerea1c4542004-12-08 23:43:58 +000013683
13684/// TryToSinkInstruction - Try to move the specified instruction from its
13685/// current block into the beginning of DestBlock, which can only happen if it's
13686/// safe to move the instruction past all of the instructions between it and the
13687/// end of its block.
13688static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13689 assert(I->hasOneUse() && "Invariants didn't hold!");
13690
Chris Lattner108e9022005-10-27 17:13:11 +000013691 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013692 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013693 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013694
Chris Lattnerea1c4542004-12-08 23:43:58 +000013695 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013696 if (isa<AllocaInst>(I) && I->getParent() ==
13697 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013698 return false;
13699
Chris Lattner96a52a62004-12-09 07:14:34 +000013700 // We can only sink load instructions if there is nothing between the load and
13701 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013702 if (I->mayReadFromMemory()) {
13703 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013704 Scan != E; ++Scan)
13705 if (Scan->mayWriteToMemory())
13706 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013707 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013708
Dan Gohman02dea8b2008-05-23 21:05:58 +000013709 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013710
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013711 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013712 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013713 ++NumSunkInst;
13714 return true;
13715}
13716
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013717
13718/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13719/// all reachable code to the worklist.
13720///
13721/// This has a couple of tricks to make the code faster and more powerful. In
13722/// particular, we constant fold and DCE instructions as we go, to avoid adding
13723/// them to the worklist (this significantly speeds up instcombine on code where
13724/// many instructions are dead or constant). Additionally, if we find a branch
13725/// whose condition is a known constant, we only visit the reachable successors.
13726///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013727static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013728 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013729 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013730 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013731 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013732 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013733 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013734
13735 std::vector<Instruction*> InstrsForInstCombineWorklist;
13736 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013737
Chris Lattner2ee743b2009-10-15 04:59:28 +000013738 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13739
Chris Lattner2c7718a2007-03-23 19:17:18 +000013740 while (!Worklist.empty()) {
13741 BB = Worklist.back();
13742 Worklist.pop_back();
13743
13744 // We have now visited this block! If we've already been here, ignore it.
13745 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013746
Chris Lattner2c7718a2007-03-23 19:17:18 +000013747 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13748 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013749
Chris Lattner2c7718a2007-03-23 19:17:18 +000013750 // DCE instruction if trivially dead.
13751 if (isInstructionTriviallyDead(Inst)) {
13752 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013753 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013754 Inst->eraseFromParent();
13755 continue;
13756 }
13757
13758 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013759 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013760 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013761 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13762 << *Inst << '\n');
13763 Inst->replaceAllUsesWith(C);
13764 ++NumConstProp;
13765 Inst->eraseFromParent();
13766 continue;
13767 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013768
13769
13770
13771 if (TD) {
13772 // See if we can constant fold its operands.
13773 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13774 i != e; ++i) {
13775 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13776 if (CE == 0) continue;
13777
13778 // If we already folded this constant, don't try again.
13779 if (!FoldedConstants.insert(CE))
13780 continue;
13781
Chris Lattner7b550cc2009-11-06 04:27:31 +000013782 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013783 if (NewC && NewC != CE) {
13784 *i = NewC;
13785 MadeIRChange = true;
13786 }
13787 }
13788 }
13789
Devang Patel7fe1dec2008-11-19 18:56:50 +000013790
Chris Lattner67f7d542009-10-12 03:58:40 +000013791 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013792 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013793
13794 // Recursively visit successors. If this is a branch or switch on a
13795 // constant, only visit the reachable successor.
13796 TerminatorInst *TI = BB->getTerminator();
13797 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13798 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13799 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013800 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013801 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013802 continue;
13803 }
13804 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13805 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13806 // See if this is an explicit destination.
13807 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13808 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013809 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013810 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013811 continue;
13812 }
13813
13814 // Otherwise it is the default destination.
13815 Worklist.push_back(SI->getSuccessor(0));
13816 continue;
13817 }
13818 }
13819
13820 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13821 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013822 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013823
13824 // Once we've found all of the instructions to add to instcombine's worklist,
13825 // add them in reverse order. This way instcombine will visit from the top
13826 // of the function down. This jives well with the way that it adds all uses
13827 // of instructions to the worklist after doing a transformation, thus avoiding
13828 // some N^2 behavior in pathological cases.
13829 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13830 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013831
13832 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013833}
13834
Chris Lattnerec9c3582007-03-03 02:04:50 +000013835bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013836 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013837
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013838 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13839 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013840
Chris Lattnerb3d59702005-07-07 20:40:38 +000013841 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013842 // Do a depth-first traversal of the function, populate the worklist with
13843 // the reachable instructions. Ignore blocks that are not reachable. Keep
13844 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013845 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013846 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013847
Chris Lattnerb3d59702005-07-07 20:40:38 +000013848 // Do a quick scan over the function. If we find any blocks that are
13849 // unreachable, remove any instructions inside of them. This prevents
13850 // the instcombine code from having to deal with some bad special cases.
13851 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13852 if (!Visited.count(BB)) {
13853 Instruction *Term = BB->getTerminator();
13854 while (Term != BB->begin()) { // Remove instrs bottom-up
13855 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013856
Chris Lattnerbdff5482009-08-23 04:37:46 +000013857 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013858 // A debug intrinsic shouldn't force another iteration if we weren't
13859 // going to do one without it.
13860 if (!isa<DbgInfoIntrinsic>(I)) {
13861 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013862 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013863 }
Devang Patel228ebd02009-10-13 22:56:32 +000013864
Devang Patel228ebd02009-10-13 22:56:32 +000013865 // If I is not void type then replaceAllUsesWith undef.
13866 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013867 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013868 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013869 I->eraseFromParent();
13870 }
13871 }
13872 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013873
Chris Lattner873ff012009-08-30 05:55:36 +000013874 while (!Worklist.isEmpty()) {
13875 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013876 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013877
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013878 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013879 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013880 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013881 EraseInstFromFunction(*I);
13882 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013883 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013884 continue;
13885 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013886
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013887 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013888 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013889 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013890 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013891
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013892 // Add operands to the worklist.
13893 ReplaceInstUsesWith(*I, C);
13894 ++NumConstProp;
13895 EraseInstFromFunction(*I);
13896 MadeIRChange = true;
13897 continue;
13898 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013899
Chris Lattnerea1c4542004-12-08 23:43:58 +000013900 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013901 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013902 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013903 Instruction *UserInst = cast<Instruction>(I->use_back());
13904 BasicBlock *UserParent;
13905
13906 // Get the block the use occurs in.
13907 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13908 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13909 else
13910 UserParent = UserInst->getParent();
13911
Chris Lattnerea1c4542004-12-08 23:43:58 +000013912 if (UserParent != BB) {
13913 bool UserIsSuccessor = false;
13914 // See if the user is one of our successors.
13915 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13916 if (*SI == UserParent) {
13917 UserIsSuccessor = true;
13918 break;
13919 }
13920
13921 // If the user is one of our immediate successors, and if that successor
13922 // only has us as a predecessors (we'd have to split the critical edge
13923 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013924 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013925 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013926 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013927 }
13928 }
13929
Chris Lattner74381062009-08-30 07:44:24 +000013930 // Now that we have an instruction, try combining it to simplify it.
13931 Builder->SetInsertPoint(I->getParent(), I);
13932
Reid Spencera9b81012007-03-26 17:44:01 +000013933#ifndef NDEBUG
13934 std::string OrigI;
13935#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013936 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013937 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13938
Chris Lattner90ac28c2002-08-02 19:29:35 +000013939 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013940 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013941 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013942 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013943 DEBUG(errs() << "IC: Old = " << *I << '\n'
13944 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013945
Chris Lattnerf523d062004-06-09 05:08:07 +000013946 // Everything uses the new instruction now.
13947 I->replaceAllUsesWith(Result);
13948
13949 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013950 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013951 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013952
Chris Lattner6934a042007-02-11 01:23:03 +000013953 // Move the name to the new instruction first.
13954 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013955
13956 // Insert the new instruction into the basic block...
13957 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013958 BasicBlock::iterator InsertPos = I;
13959
13960 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13961 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13962 ++InsertPos;
13963
13964 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013965
Chris Lattner7a1e9242009-08-30 06:13:40 +000013966 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013967 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013968#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013969 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13970 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013971#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013972
Chris Lattner90ac28c2002-08-02 19:29:35 +000013973 // If the instruction was modified, it's possible that it is now dead.
13974 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013975 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013976 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013977 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013978 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013979 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013980 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013981 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013982 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013983 }
13984 }
13985
Chris Lattner873ff012009-08-30 05:55:36 +000013986 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013987 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013988}
13989
Chris Lattnerec9c3582007-03-03 02:04:50 +000013990
13991bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013992 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013993 TD = getAnalysisIfAvailable<TargetData>();
13994
Chris Lattner74381062009-08-30 07:44:24 +000013995
13996 /// Builder - This is an IRBuilder that automatically inserts new
13997 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013998 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013999 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000014000 InstCombineIRInserter(Worklist));
14001 Builder = &TheBuilder;
14002
Chris Lattnerec9c3582007-03-03 02:04:50 +000014003 bool EverMadeChange = false;
14004
14005 // Iterate while there is work to do.
14006 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000014007 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000014008 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000014009
14010 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000014011 return EverMadeChange;
14012}
14013
Brian Gaeke96d4bf72004-07-27 17:43:21 +000014014FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000014015 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014016}