Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1 | //===- InstructionCombining.cpp - Combine multiple instructions -----------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | 081ce94 | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // InstructionCombining - Combine instructions to form fewer, simple |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 11 | // instructions. This pass does not modify the CFG. This pass is where |
| 12 | // algebraic simplification happens. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 13 | // |
| 14 | // This pass combines things like: |
| 15 | // %Y = add i32 %X, 1 |
| 16 | // %Z = add i32 %Y, 1 |
| 17 | // into: |
| 18 | // %Z = add i32 %X, 2 |
| 19 | // |
| 20 | // This is a simple worklist driven algorithm. |
| 21 | // |
| 22 | // This pass guarantees that the following canonicalizations are performed on |
| 23 | // the program: |
| 24 | // 1. If a binary operator has a constant operand, it is moved to the RHS |
| 25 | // 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. |
| 27 | // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible |
| 28 | // 4. All cmp instructions on boolean values are replaced with logical ops |
| 29 | // 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. |
| 32 | // ... etc. |
| 33 | // |
| 34 | //===----------------------------------------------------------------------===// |
| 35 | |
| 36 | #define DEBUG_TYPE "instcombine" |
| 37 | #include "llvm/Transforms/Scalar.h" |
| 38 | #include "llvm/IntrinsicInst.h" |
| 39 | #include "llvm/Pass.h" |
| 40 | #include "llvm/DerivedTypes.h" |
| 41 | #include "llvm/GlobalVariable.h" |
| 42 | #include "llvm/Analysis/ConstantFolding.h" |
Chris Lattner | a432bc7 | 2008-06-02 01:18:21 +0000 | [diff] [blame] | 43 | #include "llvm/Analysis/ValueTracking.h" |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 44 | #include "llvm/Target/TargetData.h" |
| 45 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 46 | #include "llvm/Transforms/Utils/Local.h" |
| 47 | #include "llvm/Support/CallSite.h" |
Nick Lewycky | 0185bbf | 2008-02-03 16:33:09 +0000 | [diff] [blame] | 48 | #include "llvm/Support/ConstantRange.h" |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 49 | #include "llvm/Support/Debug.h" |
| 50 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
| 51 | #include "llvm/Support/InstVisitor.h" |
| 52 | #include "llvm/Support/MathExtras.h" |
| 53 | #include "llvm/Support/PatternMatch.h" |
| 54 | #include "llvm/Support/Compiler.h" |
| 55 | #include "llvm/ADT/DenseMap.h" |
| 56 | #include "llvm/ADT/SmallVector.h" |
| 57 | #include "llvm/ADT/SmallPtrSet.h" |
| 58 | #include "llvm/ADT/Statistic.h" |
| 59 | #include "llvm/ADT/STLExtras.h" |
| 60 | #include <algorithm> |
Edwin Török | a0e6fce | 2008-04-20 08:33:11 +0000 | [diff] [blame] | 61 | #include <climits> |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 62 | #include <sstream> |
| 63 | using namespace llvm; |
| 64 | using namespace llvm::PatternMatch; |
| 65 | |
| 66 | STATISTIC(NumCombined , "Number of insts combined"); |
| 67 | STATISTIC(NumConstProp, "Number of constant folds"); |
| 68 | STATISTIC(NumDeadInst , "Number of dead inst eliminated"); |
| 69 | STATISTIC(NumDeadStore, "Number of dead stores eliminated"); |
| 70 | STATISTIC(NumSunkInst , "Number of instructions sunk"); |
| 71 | |
| 72 | namespace { |
| 73 | class VISIBILITY_HIDDEN InstCombiner |
| 74 | : public FunctionPass, |
| 75 | public InstVisitor<InstCombiner, Instruction*> { |
| 76 | // Worklist of all of the instructions that need to be simplified. |
Chris Lattner | a06291a | 2008-08-15 04:03:01 +0000 | [diff] [blame] | 77 | SmallVector<Instruction*, 256> Worklist; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 78 | DenseMap<Instruction*, unsigned> WorklistMap; |
| 79 | TargetData *TD; |
| 80 | bool MustPreserveLCSSA; |
| 81 | public: |
| 82 | static char ID; // Pass identification, replacement for typeid |
Dan Gohman | 26f8c27 | 2008-09-04 17:05:41 +0000 | [diff] [blame] | 83 | InstCombiner() : FunctionPass(&ID) {} |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 84 | |
| 85 | /// AddToWorkList - Add the specified instruction to the worklist if it |
| 86 | /// isn't already in it. |
| 87 | void AddToWorkList(Instruction *I) { |
Dan Gohman | 55d1966 | 2008-07-07 17:46:23 +0000 | [diff] [blame] | 88 | if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 89 | Worklist.push_back(I); |
| 90 | } |
| 91 | |
| 92 | // RemoveFromWorkList - remove I from the worklist if it exists. |
| 93 | void RemoveFromWorkList(Instruction *I) { |
| 94 | DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I); |
| 95 | if (It == WorklistMap.end()) return; // Not in worklist. |
| 96 | |
| 97 | // Don't bother moving everything down, just null out the slot. |
| 98 | Worklist[It->second] = 0; |
| 99 | |
| 100 | WorklistMap.erase(It); |
| 101 | } |
| 102 | |
| 103 | Instruction *RemoveOneFromWorkList() { |
| 104 | Instruction *I = Worklist.back(); |
| 105 | Worklist.pop_back(); |
| 106 | WorklistMap.erase(I); |
| 107 | return I; |
| 108 | } |
| 109 | |
| 110 | |
| 111 | /// AddUsersToWorkList - When an instruction is simplified, add all users of |
| 112 | /// the instruction to the work lists because they might get more simplified |
| 113 | /// now. |
| 114 | /// |
| 115 | void AddUsersToWorkList(Value &I) { |
| 116 | for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); |
| 117 | UI != UE; ++UI) |
| 118 | AddToWorkList(cast<Instruction>(*UI)); |
| 119 | } |
| 120 | |
| 121 | /// AddUsesToWorkList - When an instruction is simplified, add operands to |
| 122 | /// the work lists because they might get more simplified now. |
| 123 | /// |
| 124 | void AddUsesToWorkList(Instruction &I) { |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 125 | for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i) |
| 126 | if (Instruction *Op = dyn_cast<Instruction>(*i)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 127 | AddToWorkList(Op); |
| 128 | } |
| 129 | |
| 130 | /// AddSoonDeadInstToWorklist - The specified instruction is about to become |
| 131 | /// dead. Add all of its operands to the worklist, turning them into |
| 132 | /// undef's to reduce the number of uses of those instructions. |
| 133 | /// |
| 134 | /// Return the specified operand before it is turned into an undef. |
| 135 | /// |
| 136 | Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) { |
| 137 | Value *R = I.getOperand(op); |
| 138 | |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 139 | for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i) |
| 140 | if (Instruction *Op = dyn_cast<Instruction>(*i)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 141 | AddToWorkList(Op); |
| 142 | // Set the operand to undef to drop the use. |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 143 | *i = UndefValue::get(Op->getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 144 | } |
| 145 | |
| 146 | return R; |
| 147 | } |
| 148 | |
| 149 | public: |
| 150 | virtual bool runOnFunction(Function &F); |
| 151 | |
| 152 | bool DoOneIteration(Function &F, unsigned ItNum); |
| 153 | |
| 154 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
| 155 | AU.addRequired<TargetData>(); |
| 156 | AU.addPreservedID(LCSSAID); |
| 157 | AU.setPreservesCFG(); |
| 158 | } |
| 159 | |
| 160 | TargetData &getTargetData() const { return *TD; } |
| 161 | |
| 162 | // Visitation implementation - Implement instruction combining for different |
| 163 | // instruction types. The semantics are as follows: |
| 164 | // Return Value: |
| 165 | // null - No change was made |
| 166 | // I - Change was made, I is still valid, I may be dead though |
| 167 | // otherwise - Change was made, replace I with returned instruction |
| 168 | // |
| 169 | Instruction *visitAdd(BinaryOperator &I); |
| 170 | Instruction *visitSub(BinaryOperator &I); |
| 171 | Instruction *visitMul(BinaryOperator &I); |
| 172 | Instruction *visitURem(BinaryOperator &I); |
| 173 | Instruction *visitSRem(BinaryOperator &I); |
| 174 | Instruction *visitFRem(BinaryOperator &I); |
Chris Lattner | 76972db | 2008-07-14 00:15:52 +0000 | [diff] [blame] | 175 | bool SimplifyDivRemOfSelect(BinaryOperator &I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 176 | Instruction *commonRemTransforms(BinaryOperator &I); |
| 177 | Instruction *commonIRemTransforms(BinaryOperator &I); |
| 178 | Instruction *commonDivTransforms(BinaryOperator &I); |
| 179 | Instruction *commonIDivTransforms(BinaryOperator &I); |
| 180 | Instruction *visitUDiv(BinaryOperator &I); |
| 181 | Instruction *visitSDiv(BinaryOperator &I); |
| 182 | Instruction *visitFDiv(BinaryOperator &I); |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 183 | Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 184 | Instruction *visitAnd(BinaryOperator &I); |
Chris Lattner | 0c678e5 | 2008-11-16 05:20:07 +0000 | [diff] [blame] | 185 | Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS); |
Bill Wendling | 9912f71 | 2008-12-01 08:32:40 +0000 | [diff] [blame] | 186 | Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 187 | Value *A, Value *B, Value *C); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 188 | Instruction *visitOr (BinaryOperator &I); |
| 189 | Instruction *visitXor(BinaryOperator &I); |
| 190 | Instruction *visitShl(BinaryOperator &I); |
| 191 | Instruction *visitAShr(BinaryOperator &I); |
| 192 | Instruction *visitLShr(BinaryOperator &I); |
| 193 | Instruction *commonShiftTransforms(BinaryOperator &I); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 194 | Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI, |
| 195 | Constant *RHSC); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 196 | Instruction *visitFCmpInst(FCmpInst &I); |
| 197 | Instruction *visitICmpInst(ICmpInst &I); |
| 198 | Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI); |
| 199 | Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, |
| 200 | Instruction *LHS, |
| 201 | ConstantInt *RHS); |
| 202 | Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, |
| 203 | ConstantInt *DivRHS); |
| 204 | |
| 205 | Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS, |
| 206 | ICmpInst::Predicate Cond, Instruction &I); |
| 207 | Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1, |
| 208 | BinaryOperator &I); |
| 209 | Instruction *commonCastTransforms(CastInst &CI); |
| 210 | Instruction *commonIntCastTransforms(CastInst &CI); |
| 211 | Instruction *commonPointerCastTransforms(CastInst &CI); |
| 212 | Instruction *visitTrunc(TruncInst &CI); |
| 213 | Instruction *visitZExt(ZExtInst &CI); |
| 214 | Instruction *visitSExt(SExtInst &CI); |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 215 | Instruction *visitFPTrunc(FPTruncInst &CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 216 | Instruction *visitFPExt(CastInst &CI); |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 217 | Instruction *visitFPToUI(FPToUIInst &FI); |
| 218 | Instruction *visitFPToSI(FPToSIInst &FI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 219 | Instruction *visitUIToFP(CastInst &CI); |
| 220 | Instruction *visitSIToFP(CastInst &CI); |
| 221 | Instruction *visitPtrToInt(CastInst &CI); |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 222 | Instruction *visitIntToPtr(IntToPtrInst &CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 223 | Instruction *visitBitCast(BitCastInst &CI); |
| 224 | Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, |
| 225 | Instruction *FI); |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 226 | Instruction *visitSelectInst(SelectInst &SI); |
| 227 | Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 228 | Instruction *visitCallInst(CallInst &CI); |
| 229 | Instruction *visitInvokeInst(InvokeInst &II); |
| 230 | Instruction *visitPHINode(PHINode &PN); |
| 231 | Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP); |
| 232 | Instruction *visitAllocationInst(AllocationInst &AI); |
| 233 | Instruction *visitFreeInst(FreeInst &FI); |
| 234 | Instruction *visitLoadInst(LoadInst &LI); |
| 235 | Instruction *visitStoreInst(StoreInst &SI); |
| 236 | Instruction *visitBranchInst(BranchInst &BI); |
| 237 | Instruction *visitSwitchInst(SwitchInst &SI); |
| 238 | Instruction *visitInsertElementInst(InsertElementInst &IE); |
| 239 | Instruction *visitExtractElementInst(ExtractElementInst &EI); |
| 240 | Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI); |
Matthijs Kooijman | da9ef70 | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 241 | Instruction *visitExtractValueInst(ExtractValueInst &EV); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 242 | |
| 243 | // visitInstruction - Specify what to return for unhandled instructions... |
| 244 | Instruction *visitInstruction(Instruction &I) { return 0; } |
| 245 | |
| 246 | private: |
| 247 | Instruction *visitCallSite(CallSite CS); |
| 248 | bool transformConstExprCastCall(CallSite CS); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 249 | Instruction *transformCallThroughTrampoline(CallSite CS); |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 250 | Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI, |
| 251 | bool DoXform = true); |
Chris Lattner | 3554f97 | 2008-05-20 05:46:13 +0000 | [diff] [blame] | 252 | bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 253 | |
| 254 | public: |
| 255 | // InsertNewInstBefore - insert an instruction New before instruction Old |
| 256 | // in the program. Add the new instruction to the worklist. |
| 257 | // |
| 258 | Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) { |
| 259 | assert(New && New->getParent() == 0 && |
| 260 | "New instruction already inserted into a basic block!"); |
| 261 | BasicBlock *BB = Old.getParent(); |
| 262 | BB->getInstList().insert(&Old, New); // Insert inst |
| 263 | AddToWorkList(New); |
| 264 | return New; |
| 265 | } |
| 266 | |
| 267 | /// InsertCastBefore - Insert a cast of V to TY before the instruction POS. |
| 268 | /// This also adds the cast to the worklist. Finally, this returns the |
| 269 | /// cast. |
| 270 | Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty, |
| 271 | Instruction &Pos) { |
| 272 | if (V->getType() == Ty) return V; |
| 273 | |
| 274 | if (Constant *CV = dyn_cast<Constant>(V)) |
| 275 | return ConstantExpr::getCast(opc, CV, Ty); |
| 276 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 277 | Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 278 | AddToWorkList(C); |
| 279 | return C; |
| 280 | } |
Chris Lattner | 13c2d6e | 2008-01-13 22:23:22 +0000 | [diff] [blame] | 281 | |
| 282 | Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) { |
| 283 | return InsertCastBefore(Instruction::BitCast, V, Ty, Pos); |
| 284 | } |
| 285 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 286 | |
| 287 | // ReplaceInstUsesWith - This method is to be used when an instruction is |
| 288 | // found to be dead, replacable with another preexisting expression. Here |
| 289 | // we add all uses of I to the worklist, replace all uses of I with the new |
| 290 | // value, then return I, so that the inst combiner will know that I was |
| 291 | // modified. |
| 292 | // |
| 293 | Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) { |
| 294 | AddUsersToWorkList(I); // Add all modified instrs to worklist |
| 295 | if (&I != V) { |
| 296 | I.replaceAllUsesWith(V); |
| 297 | return &I; |
| 298 | } else { |
| 299 | // If we are replacing the instruction with itself, this must be in a |
| 300 | // segment of unreachable code, so just clobber the instruction. |
| 301 | I.replaceAllUsesWith(UndefValue::get(I.getType())); |
| 302 | return &I; |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | // UpdateValueUsesWith - This method is to be used when an value is |
| 307 | // found to be replacable with another preexisting expression or was |
| 308 | // updated. Here we add all uses of I to the worklist, replace all uses of |
| 309 | // I with the new value (unless the instruction was just updated), then |
| 310 | // return true, so that the inst combiner will know that I was modified. |
| 311 | // |
| 312 | bool UpdateValueUsesWith(Value *Old, Value *New) { |
| 313 | AddUsersToWorkList(*Old); // Add all modified instrs to worklist |
| 314 | if (Old != New) |
| 315 | Old->replaceAllUsesWith(New); |
| 316 | if (Instruction *I = dyn_cast<Instruction>(Old)) |
| 317 | AddToWorkList(I); |
| 318 | if (Instruction *I = dyn_cast<Instruction>(New)) |
| 319 | AddToWorkList(I); |
| 320 | return true; |
| 321 | } |
| 322 | |
| 323 | // EraseInstFromFunction - When dealing with an instruction that has side |
| 324 | // effects or produces a void value, we can't rely on DCE to delete the |
| 325 | // instruction. Instead, visit methods should return the value returned by |
| 326 | // this function. |
| 327 | Instruction *EraseInstFromFunction(Instruction &I) { |
| 328 | assert(I.use_empty() && "Cannot erase instruction that is used!"); |
| 329 | AddUsesToWorkList(I); |
| 330 | RemoveFromWorkList(&I); |
| 331 | I.eraseFromParent(); |
| 332 | return 0; // Don't do anything with FI |
| 333 | } |
Chris Lattner | a432bc7 | 2008-06-02 01:18:21 +0000 | [diff] [blame] | 334 | |
| 335 | void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero, |
| 336 | APInt &KnownOne, unsigned Depth = 0) const { |
| 337 | return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth); |
| 338 | } |
| 339 | |
| 340 | bool MaskedValueIsZero(Value *V, const APInt &Mask, |
| 341 | unsigned Depth = 0) const { |
| 342 | return llvm::MaskedValueIsZero(V, Mask, TD, Depth); |
| 343 | } |
| 344 | unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const { |
| 345 | return llvm::ComputeNumSignBits(Op, TD, Depth); |
| 346 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 347 | |
| 348 | private: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 349 | |
| 350 | /// SimplifyCommutative - This performs a few simplifications for |
| 351 | /// commutative operators. |
| 352 | bool SimplifyCommutative(BinaryOperator &I); |
| 353 | |
| 354 | /// SimplifyCompare - This reorders the operands of a CmpInst to get them in |
| 355 | /// most-complex to least-complex order. |
| 356 | bool SimplifyCompare(CmpInst &I); |
| 357 | |
| 358 | /// SimplifyDemandedBits - Attempts to replace V with a simpler value based |
| 359 | /// on the demanded bits. |
| 360 | bool SimplifyDemandedBits(Value *V, APInt DemandedMask, |
| 361 | APInt& KnownZero, APInt& KnownOne, |
| 362 | unsigned Depth = 0); |
| 363 | |
| 364 | Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts, |
| 365 | uint64_t &UndefElts, unsigned Depth = 0); |
| 366 | |
| 367 | // FoldOpIntoPhi - Given a binary operator or cast instruction which has a |
| 368 | // PHI node as operand #0, see if we can fold the instruction into the PHI |
| 369 | // (which is only possible if all operands to the PHI are constants). |
| 370 | Instruction *FoldOpIntoPhi(Instruction &I); |
| 371 | |
| 372 | // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary" |
| 373 | // operator and they all are only used by the PHI, PHI together their |
| 374 | // inputs, and do the operation once, to the result of the PHI. |
| 375 | Instruction *FoldPHIArgOpIntoPHI(PHINode &PN); |
| 376 | Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN); |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 377 | Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN); |
| 378 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 379 | |
| 380 | Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS, |
| 381 | ConstantInt *AndRHS, BinaryOperator &TheAnd); |
| 382 | |
| 383 | Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask, |
| 384 | bool isSub, Instruction &I); |
| 385 | Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, |
| 386 | bool isSigned, bool Inside, Instruction &IB); |
| 387 | Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI); |
| 388 | Instruction *MatchBSwap(BinaryOperator &I); |
| 389 | bool SimplifyStoreAtEndOfBlock(StoreInst &SI); |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 390 | Instruction *SimplifyMemTransfer(MemIntrinsic *MI); |
Chris Lattner | 5af8a91 | 2008-04-30 06:39:11 +0000 | [diff] [blame] | 391 | Instruction *SimplifyMemSet(MemSetInst *MI); |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 392 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 393 | |
| 394 | Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned); |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 395 | |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 396 | bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 397 | unsigned CastOpc, int &NumCastsRemoved); |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 398 | unsigned GetOrEnforceKnownAlignment(Value *V, |
| 399 | unsigned PrefAlign = 0); |
Matthijs Kooijman | da9ef70 | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 400 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 401 | }; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 402 | } |
| 403 | |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 404 | char InstCombiner::ID = 0; |
| 405 | static RegisterPass<InstCombiner> |
| 406 | X("instcombine", "Combine redundant instructions"); |
| 407 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 408 | // getComplexity: Assign a complexity or rank value to LLVM Values... |
| 409 | // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst |
| 410 | static unsigned getComplexity(Value *V) { |
| 411 | if (isa<Instruction>(V)) { |
| 412 | if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V)) |
| 413 | return 3; |
| 414 | return 4; |
| 415 | } |
| 416 | if (isa<Argument>(V)) return 3; |
| 417 | return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2; |
| 418 | } |
| 419 | |
| 420 | // isOnlyUse - Return true if this instruction will be deleted if we stop using |
| 421 | // it. |
| 422 | static bool isOnlyUse(Value *V) { |
| 423 | return V->hasOneUse() || isa<Constant>(V); |
| 424 | } |
| 425 | |
| 426 | // getPromotedType - Return the specified type promoted as it would be to pass |
| 427 | // though a va_arg area... |
| 428 | static const Type *getPromotedType(const Type *Ty) { |
| 429 | if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { |
| 430 | if (ITy->getBitWidth() < 32) |
| 431 | return Type::Int32Ty; |
| 432 | } |
| 433 | return Ty; |
| 434 | } |
| 435 | |
Matthijs Kooijman | 5e2a318 | 2008-10-13 15:17:01 +0000 | [diff] [blame] | 436 | /// getBitCastOperand - If the specified operand is a CastInst, a constant |
| 437 | /// expression bitcast, or a GetElementPtrInst with all zero indices, return the |
| 438 | /// operand value, otherwise return null. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 439 | static Value *getBitCastOperand(Value *V) { |
| 440 | if (BitCastInst *I = dyn_cast<BitCastInst>(V)) |
Matthijs Kooijman | 5e2a318 | 2008-10-13 15:17:01 +0000 | [diff] [blame] | 441 | // BitCastInst? |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 442 | return I->getOperand(0); |
Matthijs Kooijman | 5e2a318 | 2008-10-13 15:17:01 +0000 | [diff] [blame] | 443 | else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { |
| 444 | // GetElementPtrInst? |
| 445 | if (GEP->hasAllZeroIndices()) |
| 446 | return GEP->getOperand(0); |
| 447 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 448 | if (CE->getOpcode() == Instruction::BitCast) |
Matthijs Kooijman | 5e2a318 | 2008-10-13 15:17:01 +0000 | [diff] [blame] | 449 | // BitCast ConstantExp? |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 450 | return CE->getOperand(0); |
Matthijs Kooijman | 5e2a318 | 2008-10-13 15:17:01 +0000 | [diff] [blame] | 451 | else if (CE->getOpcode() == Instruction::GetElementPtr) { |
| 452 | // GetElementPtr ConstantExp? |
| 453 | for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end(); |
| 454 | I != E; ++I) { |
| 455 | ConstantInt *CI = dyn_cast<ConstantInt>(I); |
| 456 | if (!CI || !CI->isZero()) |
| 457 | // Any non-zero indices? Not cast-like. |
| 458 | return 0; |
| 459 | } |
| 460 | // All-zero indices? This is just like casting. |
| 461 | return CE->getOperand(0); |
| 462 | } |
| 463 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 464 | return 0; |
| 465 | } |
| 466 | |
| 467 | /// This function is a wrapper around CastInst::isEliminableCastPair. It |
| 468 | /// simply extracts arguments and returns what that function returns. |
| 469 | static Instruction::CastOps |
| 470 | isEliminableCastPair( |
| 471 | const CastInst *CI, ///< The first cast instruction |
| 472 | unsigned opcode, ///< The opcode of the second cast instruction |
| 473 | const Type *DstTy, ///< The target type for the second cast instruction |
| 474 | TargetData *TD ///< The target data for pointer size |
| 475 | ) { |
| 476 | |
| 477 | const Type *SrcTy = CI->getOperand(0)->getType(); // A from above |
| 478 | const Type *MidTy = CI->getType(); // B from above |
| 479 | |
| 480 | // Get the opcodes of the two Cast instructions |
| 481 | Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode()); |
| 482 | Instruction::CastOps secondOp = Instruction::CastOps(opcode); |
| 483 | |
| 484 | return Instruction::CastOps( |
| 485 | CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, |
| 486 | DstTy, TD->getIntPtrType())); |
| 487 | } |
| 488 | |
| 489 | /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results |
| 490 | /// in any code being generated. It does not require codegen if V is simple |
| 491 | /// enough or if the cast can be folded into other casts. |
| 492 | static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, |
| 493 | const Type *Ty, TargetData *TD) { |
| 494 | if (V->getType() == Ty || isa<Constant>(V)) return false; |
| 495 | |
| 496 | // If this is another cast that can be eliminated, it isn't codegen either. |
| 497 | if (const CastInst *CI = dyn_cast<CastInst>(V)) |
| 498 | if (isEliminableCastPair(CI, opcode, Ty, TD)) |
| 499 | return false; |
| 500 | return true; |
| 501 | } |
| 502 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 503 | // SimplifyCommutative - This performs a few simplifications for commutative |
| 504 | // operators: |
| 505 | // |
| 506 | // 1. Order operands such that they are listed from right (least complex) to |
| 507 | // left (most complex). This puts constants before unary operators before |
| 508 | // binary operators. |
| 509 | // |
| 510 | // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2)) |
| 511 | // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2)) |
| 512 | // |
| 513 | bool InstCombiner::SimplifyCommutative(BinaryOperator &I) { |
| 514 | bool Changed = false; |
| 515 | if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) |
| 516 | Changed = !I.swapOperands(); |
| 517 | |
| 518 | if (!I.isAssociative()) return Changed; |
| 519 | Instruction::BinaryOps Opcode = I.getOpcode(); |
| 520 | if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0))) |
| 521 | if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) { |
| 522 | if (isa<Constant>(I.getOperand(1))) { |
| 523 | Constant *Folded = ConstantExpr::get(I.getOpcode(), |
| 524 | cast<Constant>(I.getOperand(1)), |
| 525 | cast<Constant>(Op->getOperand(1))); |
| 526 | I.setOperand(0, Op->getOperand(0)); |
| 527 | I.setOperand(1, Folded); |
| 528 | return true; |
| 529 | } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1))) |
| 530 | if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) && |
| 531 | isOnlyUse(Op) && isOnlyUse(Op1)) { |
| 532 | Constant *C1 = cast<Constant>(Op->getOperand(1)); |
| 533 | Constant *C2 = cast<Constant>(Op1->getOperand(1)); |
| 534 | |
| 535 | // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2)) |
| 536 | Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 537 | Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 538 | Op1->getOperand(0), |
| 539 | Op1->getName(), &I); |
| 540 | AddToWorkList(New); |
| 541 | I.setOperand(0, New); |
| 542 | I.setOperand(1, Folded); |
| 543 | return true; |
| 544 | } |
| 545 | } |
| 546 | return Changed; |
| 547 | } |
| 548 | |
| 549 | /// SimplifyCompare - For a CmpInst this function just orders the operands |
| 550 | /// so that theyare listed from right (least complex) to left (most complex). |
| 551 | /// This puts constants before unary operators before binary operators. |
| 552 | bool InstCombiner::SimplifyCompare(CmpInst &I) { |
| 553 | if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1))) |
| 554 | return false; |
| 555 | I.swapOperands(); |
| 556 | // Compare instructions are not associative so there's nothing else we can do. |
| 557 | return true; |
| 558 | } |
| 559 | |
| 560 | // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction |
| 561 | // if the LHS is a constant zero (which is the 'negate' form). |
| 562 | // |
| 563 | static inline Value *dyn_castNegVal(Value *V) { |
| 564 | if (BinaryOperator::isNeg(V)) |
| 565 | return BinaryOperator::getNegArgument(V); |
| 566 | |
| 567 | // Constants can be considered to be negated values if they can be folded. |
| 568 | if (ConstantInt *C = dyn_cast<ConstantInt>(V)) |
| 569 | return ConstantExpr::getNeg(C); |
Nick Lewycky | 58867bc | 2008-05-23 04:54:45 +0000 | [diff] [blame] | 570 | |
| 571 | if (ConstantVector *C = dyn_cast<ConstantVector>(V)) |
| 572 | if (C->getType()->getElementType()->isInteger()) |
| 573 | return ConstantExpr::getNeg(C); |
| 574 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 575 | return 0; |
| 576 | } |
| 577 | |
| 578 | static inline Value *dyn_castNotVal(Value *V) { |
| 579 | if (BinaryOperator::isNot(V)) |
| 580 | return BinaryOperator::getNotArgument(V); |
| 581 | |
| 582 | // Constants can be considered to be not'ed values... |
| 583 | if (ConstantInt *C = dyn_cast<ConstantInt>(V)) |
| 584 | return ConstantInt::get(~C->getValue()); |
| 585 | return 0; |
| 586 | } |
| 587 | |
| 588 | // dyn_castFoldableMul - If this value is a multiply that can be folded into |
| 589 | // other computations (because it has a constant operand), return the |
| 590 | // non-constant operand of the multiply, and set CST to point to the multiplier. |
| 591 | // Otherwise, return null. |
| 592 | // |
| 593 | static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) { |
| 594 | if (V->hasOneUse() && V->getType()->isInteger()) |
| 595 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 596 | if (I->getOpcode() == Instruction::Mul) |
| 597 | if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) |
| 598 | return I->getOperand(0); |
| 599 | if (I->getOpcode() == Instruction::Shl) |
| 600 | if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) { |
| 601 | // The multiplier is really 1 << CST. |
| 602 | uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth(); |
| 603 | uint32_t CSTVal = CST->getLimitedValue(BitWidth); |
| 604 | CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal)); |
| 605 | return I->getOperand(0); |
| 606 | } |
| 607 | } |
| 608 | return 0; |
| 609 | } |
| 610 | |
| 611 | /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant |
| 612 | /// expression, return it. |
| 613 | static User *dyn_castGetElementPtr(Value *V) { |
| 614 | if (isa<GetElementPtrInst>(V)) return cast<User>(V); |
| 615 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
| 616 | if (CE->getOpcode() == Instruction::GetElementPtr) |
| 617 | return cast<User>(V); |
| 618 | return false; |
| 619 | } |
| 620 | |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 621 | /// getOpcode - If this is an Instruction or a ConstantExpr, return the |
| 622 | /// opcode value. Otherwise return UserOp1. |
Dan Gohman | 8c39786 | 2008-05-29 19:53:46 +0000 | [diff] [blame] | 623 | static unsigned getOpcode(const Value *V) { |
| 624 | if (const Instruction *I = dyn_cast<Instruction>(V)) |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 625 | return I->getOpcode(); |
Dan Gohman | 8c39786 | 2008-05-29 19:53:46 +0000 | [diff] [blame] | 626 | if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 627 | return CE->getOpcode(); |
| 628 | // Use UserOp1 to mean there's no opcode. |
| 629 | return Instruction::UserOp1; |
| 630 | } |
| 631 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 632 | /// AddOne - Add one to a ConstantInt |
| 633 | static ConstantInt *AddOne(ConstantInt *C) { |
| 634 | APInt Val(C->getValue()); |
| 635 | return ConstantInt::get(++Val); |
| 636 | } |
| 637 | /// SubOne - Subtract one from a ConstantInt |
| 638 | static ConstantInt *SubOne(ConstantInt *C) { |
| 639 | APInt Val(C->getValue()); |
| 640 | return ConstantInt::get(--Val); |
| 641 | } |
| 642 | /// Add - Add two ConstantInts together |
| 643 | static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) { |
| 644 | return ConstantInt::get(C1->getValue() + C2->getValue()); |
| 645 | } |
| 646 | /// And - Bitwise AND two ConstantInts together |
| 647 | static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) { |
| 648 | return ConstantInt::get(C1->getValue() & C2->getValue()); |
| 649 | } |
| 650 | /// Subtract - Subtract one ConstantInt from another |
| 651 | static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) { |
| 652 | return ConstantInt::get(C1->getValue() - C2->getValue()); |
| 653 | } |
| 654 | /// Multiply - Multiply two ConstantInts together |
| 655 | static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) { |
| 656 | return ConstantInt::get(C1->getValue() * C2->getValue()); |
| 657 | } |
Nick Lewycky | 9d798f9 | 2008-02-18 22:48:05 +0000 | [diff] [blame] | 658 | /// MultiplyOverflows - True if the multiply can not be expressed in an int |
| 659 | /// this size. |
| 660 | static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) { |
| 661 | uint32_t W = C1->getBitWidth(); |
| 662 | APInt LHSExt = C1->getValue(), RHSExt = C2->getValue(); |
| 663 | if (sign) { |
| 664 | LHSExt.sext(W * 2); |
| 665 | RHSExt.sext(W * 2); |
| 666 | } else { |
| 667 | LHSExt.zext(W * 2); |
| 668 | RHSExt.zext(W * 2); |
| 669 | } |
| 670 | |
| 671 | APInt MulExt = LHSExt * RHSExt; |
| 672 | |
| 673 | if (sign) { |
| 674 | APInt Min = APInt::getSignedMinValue(W).sext(W * 2); |
| 675 | APInt Max = APInt::getSignedMaxValue(W).sext(W * 2); |
| 676 | return MulExt.slt(Min) || MulExt.sgt(Max); |
| 677 | } else |
| 678 | return MulExt.ugt(APInt::getLowBitsSet(W * 2, W)); |
| 679 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 680 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 681 | |
| 682 | /// ShrinkDemandedConstant - Check to see if the specified operand of the |
| 683 | /// specified instruction is a constant integer. If so, check to see if there |
| 684 | /// are any bits set in the constant that are not demanded. If so, shrink the |
| 685 | /// constant and return true. |
| 686 | static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, |
| 687 | APInt Demanded) { |
| 688 | assert(I && "No instruction?"); |
| 689 | assert(OpNo < I->getNumOperands() && "Operand index too large"); |
| 690 | |
| 691 | // If the operand is not a constant integer, nothing to do. |
| 692 | ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo)); |
| 693 | if (!OpC) return false; |
| 694 | |
| 695 | // If there are no bits set that aren't demanded, nothing to do. |
| 696 | Demanded.zextOrTrunc(OpC->getValue().getBitWidth()); |
| 697 | if ((~Demanded & OpC->getValue()) == 0) |
| 698 | return false; |
| 699 | |
| 700 | // This instruction is producing bits that are not demanded. Shrink the RHS. |
| 701 | Demanded &= OpC->getValue(); |
| 702 | I->setOperand(OpNo, ConstantInt::get(Demanded)); |
| 703 | return true; |
| 704 | } |
| 705 | |
| 706 | // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a |
| 707 | // set of known zero and one bits, compute the maximum and minimum values that |
| 708 | // could have the specified known zero and known one bits, returning them in |
| 709 | // min/max. |
| 710 | static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty, |
| 711 | const APInt& KnownZero, |
| 712 | const APInt& KnownOne, |
| 713 | APInt& Min, APInt& Max) { |
| 714 | uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); |
| 715 | assert(KnownZero.getBitWidth() == BitWidth && |
| 716 | KnownOne.getBitWidth() == BitWidth && |
| 717 | Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth && |
| 718 | "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); |
| 719 | APInt UnknownBits = ~(KnownZero|KnownOne); |
| 720 | |
| 721 | // The minimum value is when all unknown bits are zeros, EXCEPT for the sign |
| 722 | // bit if it is unknown. |
| 723 | Min = KnownOne; |
| 724 | Max = KnownOne|UnknownBits; |
| 725 | |
| 726 | if (UnknownBits[BitWidth-1]) { // Sign bit is unknown |
| 727 | Min.set(BitWidth-1); |
| 728 | Max.clear(BitWidth-1); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and |
| 733 | // a set of known zero and one bits, compute the maximum and minimum values that |
| 734 | // could have the specified known zero and known one bits, returning them in |
| 735 | // min/max. |
| 736 | static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty, |
Chris Lattner | b933ea6 | 2007-08-05 08:47:58 +0000 | [diff] [blame] | 737 | const APInt &KnownZero, |
| 738 | const APInt &KnownOne, |
| 739 | APInt &Min, APInt &Max) { |
| 740 | uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 741 | assert(KnownZero.getBitWidth() == BitWidth && |
| 742 | KnownOne.getBitWidth() == BitWidth && |
| 743 | Min.getBitWidth() == BitWidth && Max.getBitWidth() && |
| 744 | "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); |
| 745 | APInt UnknownBits = ~(KnownZero|KnownOne); |
| 746 | |
| 747 | // The minimum value is when the unknown bits are all zeros. |
| 748 | Min = KnownOne; |
| 749 | // The maximum value is when the unknown bits are all ones. |
| 750 | Max = KnownOne|UnknownBits; |
| 751 | } |
| 752 | |
| 753 | /// SimplifyDemandedBits - This function attempts to replace V with a simpler |
| 754 | /// value based on the demanded bits. When this function is called, it is known |
| 755 | /// that only the bits set in DemandedMask of the result of V are ever used |
| 756 | /// downstream. Consequently, depending on the mask and V, it may be possible |
| 757 | /// to replace V with a constant or one of its operands. In such cases, this |
| 758 | /// function does the replacement and returns true. In all other cases, it |
| 759 | /// returns false after analyzing the expression and setting KnownOne and known |
| 760 | /// to be one in the expression. KnownZero contains all the bits that are known |
| 761 | /// to be zero in the expression. These are provided to potentially allow the |
| 762 | /// caller (which might recursively be SimplifyDemandedBits itself) to simplify |
| 763 | /// the expression. KnownOne and KnownZero always follow the invariant that |
| 764 | /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that |
| 765 | /// the bits in KnownOne and KnownZero may only be accurate for those bits set |
| 766 | /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero |
| 767 | /// and KnownOne must all be the same. |
| 768 | bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask, |
Chris Lattner | c5d7e4e | 2009-01-31 07:26:06 +0000 | [diff] [blame^] | 769 | APInt &KnownZero, APInt &KnownOne, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 770 | unsigned Depth) { |
| 771 | assert(V != 0 && "Null pointer of Value???"); |
| 772 | assert(Depth <= 6 && "Limit Search Depth"); |
| 773 | uint32_t BitWidth = DemandedMask.getBitWidth(); |
| 774 | const IntegerType *VTy = cast<IntegerType>(V->getType()); |
| 775 | assert(VTy->getBitWidth() == BitWidth && |
| 776 | KnownZero.getBitWidth() == BitWidth && |
| 777 | KnownOne.getBitWidth() == BitWidth && |
| 778 | "Value *V, DemandedMask, KnownZero and KnownOne \ |
| 779 | must have same BitWidth"); |
| 780 | if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { |
| 781 | // We know all of the bits for a constant! |
| 782 | KnownOne = CI->getValue() & DemandedMask; |
| 783 | KnownZero = ~KnownOne & DemandedMask; |
| 784 | return false; |
| 785 | } |
| 786 | |
Chris Lattner | c5d7e4e | 2009-01-31 07:26:06 +0000 | [diff] [blame^] | 787 | KnownZero.clear(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 788 | KnownOne.clear(); |
| 789 | if (!V->hasOneUse()) { // Other users may use these bits. |
| 790 | if (Depth != 0) { // Not at the root. |
| 791 | // Just compute the KnownZero/KnownOne bits to simplify things downstream. |
| 792 | ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth); |
| 793 | return false; |
| 794 | } |
| 795 | // If this is the root being simplified, allow it to have multiple uses, |
| 796 | // just set the DemandedMask to all bits. |
| 797 | DemandedMask = APInt::getAllOnesValue(BitWidth); |
| 798 | } else if (DemandedMask == 0) { // Not demanding any bits from V. |
Chris Lattner | c5d7e4e | 2009-01-31 07:26:06 +0000 | [diff] [blame^] | 799 | if (!isa<UndefValue>(V)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 800 | return UpdateValueUsesWith(V, UndefValue::get(VTy)); |
| 801 | return false; |
| 802 | } else if (Depth == 6) { // Limit search depth. |
| 803 | return false; |
| 804 | } |
| 805 | |
| 806 | Instruction *I = dyn_cast<Instruction>(V); |
| 807 | if (!I) return false; // Only analyze instructions. |
| 808 | |
| 809 | APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); |
| 810 | APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne; |
| 811 | switch (I->getOpcode()) { |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 812 | default: |
| 813 | ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth); |
| 814 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 815 | case Instruction::And: |
| 816 | // If either the LHS or the RHS are Zero, the result is zero. |
| 817 | if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, |
| 818 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 819 | return true; |
| 820 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 821 | "Bits known to be one AND zero?"); |
| 822 | |
| 823 | // If something is known zero on the RHS, the bits aren't demanded on the |
| 824 | // LHS. |
| 825 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero, |
| 826 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 827 | return true; |
| 828 | assert((LHSKnownZero & LHSKnownOne) == 0 && |
| 829 | "Bits known to be one AND zero?"); |
| 830 | |
| 831 | // If all of the demanded bits are known 1 on one side, return the other. |
| 832 | // These bits cannot contribute to the result of the 'and'. |
| 833 | if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == |
| 834 | (DemandedMask & ~LHSKnownZero)) |
| 835 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 836 | if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == |
| 837 | (DemandedMask & ~RHSKnownZero)) |
| 838 | return UpdateValueUsesWith(I, I->getOperand(1)); |
| 839 | |
| 840 | // If all of the demanded bits in the inputs are known zeros, return zero. |
| 841 | if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask) |
| 842 | return UpdateValueUsesWith(I, Constant::getNullValue(VTy)); |
| 843 | |
| 844 | // If the RHS is a constant, see if we can simplify it. |
| 845 | if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero)) |
| 846 | return UpdateValueUsesWith(I, I); |
| 847 | |
| 848 | // Output known-1 bits are only known if set in both the LHS & RHS. |
| 849 | RHSKnownOne &= LHSKnownOne; |
| 850 | // Output known-0 are known to be clear if zero in either the LHS | RHS. |
| 851 | RHSKnownZero |= LHSKnownZero; |
| 852 | break; |
| 853 | case Instruction::Or: |
| 854 | // If either the LHS or the RHS are One, the result is One. |
| 855 | if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, |
| 856 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 857 | return true; |
| 858 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 859 | "Bits known to be one AND zero?"); |
| 860 | // If something is known one on the RHS, the bits aren't demanded on the |
| 861 | // LHS. |
| 862 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, |
| 863 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 864 | return true; |
| 865 | assert((LHSKnownZero & LHSKnownOne) == 0 && |
| 866 | "Bits known to be one AND zero?"); |
| 867 | |
| 868 | // If all of the demanded bits are known zero on one side, return the other. |
| 869 | // These bits cannot contribute to the result of the 'or'. |
| 870 | if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == |
| 871 | (DemandedMask & ~LHSKnownOne)) |
| 872 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 873 | if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == |
| 874 | (DemandedMask & ~RHSKnownOne)) |
| 875 | return UpdateValueUsesWith(I, I->getOperand(1)); |
| 876 | |
| 877 | // If all of the potentially set bits on one side are known to be set on |
| 878 | // the other side, just use the 'other' side. |
| 879 | if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == |
| 880 | (DemandedMask & (~RHSKnownZero))) |
| 881 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 882 | if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == |
| 883 | (DemandedMask & (~LHSKnownZero))) |
| 884 | return UpdateValueUsesWith(I, I->getOperand(1)); |
| 885 | |
| 886 | // If the RHS is a constant, see if we can simplify it. |
| 887 | if (ShrinkDemandedConstant(I, 1, DemandedMask)) |
| 888 | return UpdateValueUsesWith(I, I); |
| 889 | |
| 890 | // Output known-0 bits are only known if clear in both the LHS & RHS. |
| 891 | RHSKnownZero &= LHSKnownZero; |
| 892 | // Output known-1 are known to be set if set in either the LHS | RHS. |
| 893 | RHSKnownOne |= LHSKnownOne; |
| 894 | break; |
| 895 | case Instruction::Xor: { |
| 896 | if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, |
| 897 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 898 | return true; |
| 899 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 900 | "Bits known to be one AND zero?"); |
| 901 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, |
| 902 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 903 | return true; |
| 904 | assert((LHSKnownZero & LHSKnownOne) == 0 && |
| 905 | "Bits known to be one AND zero?"); |
| 906 | |
| 907 | // If all of the demanded bits are known zero on one side, return the other. |
| 908 | // These bits cannot contribute to the result of the 'xor'. |
| 909 | if ((DemandedMask & RHSKnownZero) == DemandedMask) |
| 910 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 911 | if ((DemandedMask & LHSKnownZero) == DemandedMask) |
| 912 | return UpdateValueUsesWith(I, I->getOperand(1)); |
| 913 | |
| 914 | // Output known-0 bits are known if clear or set in both the LHS & RHS. |
| 915 | APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | |
| 916 | (RHSKnownOne & LHSKnownOne); |
| 917 | // Output known-1 are known to be set if set in only one of the LHS, RHS. |
| 918 | APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | |
| 919 | (RHSKnownOne & LHSKnownZero); |
| 920 | |
| 921 | // If all of the demanded bits are known to be zero on one side or the |
| 922 | // other, turn this into an *inclusive* or. |
| 923 | // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 |
| 924 | if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) { |
| 925 | Instruction *Or = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 926 | BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 927 | I->getName()); |
| 928 | InsertNewInstBefore(Or, *I); |
| 929 | return UpdateValueUsesWith(I, Or); |
| 930 | } |
| 931 | |
| 932 | // If all of the demanded bits on one side are known, and all of the set |
| 933 | // bits on that side are also known to be set on the other side, turn this |
| 934 | // into an AND, as we know the bits will be cleared. |
| 935 | // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 |
| 936 | if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { |
| 937 | // all known |
| 938 | if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) { |
| 939 | Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask); |
| 940 | Instruction *And = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 941 | BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 942 | InsertNewInstBefore(And, *I); |
| 943 | return UpdateValueUsesWith(I, And); |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | // If the RHS is a constant, see if we can simplify it. |
| 948 | // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1. |
| 949 | if (ShrinkDemandedConstant(I, 1, DemandedMask)) |
| 950 | return UpdateValueUsesWith(I, I); |
| 951 | |
| 952 | RHSKnownZero = KnownZeroOut; |
| 953 | RHSKnownOne = KnownOneOut; |
| 954 | break; |
| 955 | } |
| 956 | case Instruction::Select: |
| 957 | if (SimplifyDemandedBits(I->getOperand(2), DemandedMask, |
| 958 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 959 | return true; |
| 960 | if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, |
| 961 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 962 | return true; |
| 963 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 964 | "Bits known to be one AND zero?"); |
| 965 | assert((LHSKnownZero & LHSKnownOne) == 0 && |
| 966 | "Bits known to be one AND zero?"); |
| 967 | |
| 968 | // If the operands are constants, see if we can simplify them. |
| 969 | if (ShrinkDemandedConstant(I, 1, DemandedMask)) |
| 970 | return UpdateValueUsesWith(I, I); |
| 971 | if (ShrinkDemandedConstant(I, 2, DemandedMask)) |
| 972 | return UpdateValueUsesWith(I, I); |
| 973 | |
| 974 | // Only known if known in both the LHS and RHS. |
| 975 | RHSKnownOne &= LHSKnownOne; |
| 976 | RHSKnownZero &= LHSKnownZero; |
| 977 | break; |
| 978 | case Instruction::Trunc: { |
| 979 | uint32_t truncBf = |
| 980 | cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth(); |
| 981 | DemandedMask.zext(truncBf); |
| 982 | RHSKnownZero.zext(truncBf); |
| 983 | RHSKnownOne.zext(truncBf); |
| 984 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, |
| 985 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 986 | return true; |
| 987 | DemandedMask.trunc(BitWidth); |
| 988 | RHSKnownZero.trunc(BitWidth); |
| 989 | RHSKnownOne.trunc(BitWidth); |
| 990 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 991 | "Bits known to be one AND zero?"); |
| 992 | break; |
| 993 | } |
| 994 | case Instruction::BitCast: |
| 995 | if (!I->getOperand(0)->getType()->isInteger()) |
| 996 | return false; |
| 997 | |
| 998 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, |
| 999 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1000 | return true; |
| 1001 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1002 | "Bits known to be one AND zero?"); |
| 1003 | break; |
| 1004 | case Instruction::ZExt: { |
| 1005 | // Compute the bits in the result that are not present in the input. |
| 1006 | const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType()); |
| 1007 | uint32_t SrcBitWidth = SrcTy->getBitWidth(); |
| 1008 | |
| 1009 | DemandedMask.trunc(SrcBitWidth); |
| 1010 | RHSKnownZero.trunc(SrcBitWidth); |
| 1011 | RHSKnownOne.trunc(SrcBitWidth); |
| 1012 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, |
| 1013 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1014 | return true; |
| 1015 | DemandedMask.zext(BitWidth); |
| 1016 | RHSKnownZero.zext(BitWidth); |
| 1017 | RHSKnownOne.zext(BitWidth); |
| 1018 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1019 | "Bits known to be one AND zero?"); |
| 1020 | // The top bits are known to be zero. |
| 1021 | RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); |
| 1022 | break; |
| 1023 | } |
| 1024 | case Instruction::SExt: { |
| 1025 | // Compute the bits in the result that are not present in the input. |
| 1026 | const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType()); |
| 1027 | uint32_t SrcBitWidth = SrcTy->getBitWidth(); |
| 1028 | |
| 1029 | APInt InputDemandedBits = DemandedMask & |
| 1030 | APInt::getLowBitsSet(BitWidth, SrcBitWidth); |
| 1031 | |
| 1032 | APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth)); |
| 1033 | // If any of the sign extended bits are demanded, we know that the sign |
| 1034 | // bit is demanded. |
| 1035 | if ((NewBits & DemandedMask) != 0) |
| 1036 | InputDemandedBits.set(SrcBitWidth-1); |
| 1037 | |
| 1038 | InputDemandedBits.trunc(SrcBitWidth); |
| 1039 | RHSKnownZero.trunc(SrcBitWidth); |
| 1040 | RHSKnownOne.trunc(SrcBitWidth); |
| 1041 | if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits, |
| 1042 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1043 | return true; |
| 1044 | InputDemandedBits.zext(BitWidth); |
| 1045 | RHSKnownZero.zext(BitWidth); |
| 1046 | RHSKnownOne.zext(BitWidth); |
| 1047 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1048 | "Bits known to be one AND zero?"); |
| 1049 | |
| 1050 | // If the sign bit of the input is known set or clear, then we know the |
| 1051 | // top bits of the result. |
| 1052 | |
| 1053 | // If the input sign bit is known zero, or if the NewBits are not demanded |
| 1054 | // convert this into a zero extension. |
| 1055 | if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) |
| 1056 | { |
| 1057 | // Convert to ZExt cast |
| 1058 | CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I); |
| 1059 | return UpdateValueUsesWith(I, NewCast); |
| 1060 | } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set |
| 1061 | RHSKnownOne |= NewBits; |
| 1062 | } |
| 1063 | break; |
| 1064 | } |
| 1065 | case Instruction::Add: { |
| 1066 | // Figure out what the input bits are. If the top bits of the and result |
| 1067 | // are not demanded, then the add doesn't demand them from its input |
| 1068 | // either. |
| 1069 | uint32_t NLZ = DemandedMask.countLeadingZeros(); |
| 1070 | |
| 1071 | // If there is a constant on the RHS, there are a variety of xformations |
| 1072 | // we can do. |
| 1073 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1074 | // If null, this should be simplified elsewhere. Some of the xforms here |
| 1075 | // won't work if the RHS is zero. |
| 1076 | if (RHS->isZero()) |
| 1077 | break; |
| 1078 | |
| 1079 | // If the top bit of the output is demanded, demand everything from the |
| 1080 | // input. Otherwise, we demand all the input bits except NLZ top bits. |
| 1081 | APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ)); |
| 1082 | |
| 1083 | // Find information about known zero/one bits in the input. |
| 1084 | if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, |
| 1085 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1086 | return true; |
| 1087 | |
| 1088 | // If the RHS of the add has bits set that can't affect the input, reduce |
| 1089 | // the constant. |
| 1090 | if (ShrinkDemandedConstant(I, 1, InDemandedBits)) |
| 1091 | return UpdateValueUsesWith(I, I); |
| 1092 | |
| 1093 | // Avoid excess work. |
| 1094 | if (LHSKnownZero == 0 && LHSKnownOne == 0) |
| 1095 | break; |
| 1096 | |
| 1097 | // Turn it into OR if input bits are zero. |
| 1098 | if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) { |
| 1099 | Instruction *Or = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1100 | BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1101 | I->getName()); |
| 1102 | InsertNewInstBefore(Or, *I); |
| 1103 | return UpdateValueUsesWith(I, Or); |
| 1104 | } |
| 1105 | |
| 1106 | // We can say something about the output known-zero and known-one bits, |
| 1107 | // depending on potential carries from the input constant and the |
| 1108 | // unknowns. For example if the LHS is known to have at most the 0x0F0F0 |
| 1109 | // bits set and the RHS constant is 0x01001, then we know we have a known |
| 1110 | // one mask of 0x00001 and a known zero mask of 0xE0F0E. |
| 1111 | |
| 1112 | // To compute this, we first compute the potential carry bits. These are |
| 1113 | // the bits which may be modified. I'm not aware of a better way to do |
| 1114 | // this scan. |
| 1115 | const APInt& RHSVal = RHS->getValue(); |
| 1116 | APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal)); |
| 1117 | |
| 1118 | // Now that we know which bits have carries, compute the known-1/0 sets. |
| 1119 | |
| 1120 | // Bits are known one if they are known zero in one operand and one in the |
| 1121 | // other, and there is no input carry. |
| 1122 | RHSKnownOne = ((LHSKnownZero & RHSVal) | |
| 1123 | (LHSKnownOne & ~RHSVal)) & ~CarryBits; |
| 1124 | |
| 1125 | // Bits are known zero if they are known zero in both operands and there |
| 1126 | // is no input carry. |
| 1127 | RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits; |
| 1128 | } else { |
| 1129 | // If the high-bits of this ADD are not demanded, then it does not demand |
| 1130 | // the high bits of its LHS or RHS. |
| 1131 | if (DemandedMask[BitWidth-1] == 0) { |
| 1132 | // Right fill the mask of bits for this ADD to demand the most |
| 1133 | // significant bit and all those below it. |
| 1134 | APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ)); |
| 1135 | if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps, |
| 1136 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1137 | return true; |
| 1138 | if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps, |
| 1139 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1140 | return true; |
| 1141 | } |
| 1142 | } |
| 1143 | break; |
| 1144 | } |
| 1145 | case Instruction::Sub: |
| 1146 | // If the high-bits of this SUB are not demanded, then it does not demand |
| 1147 | // the high bits of its LHS or RHS. |
| 1148 | if (DemandedMask[BitWidth-1] == 0) { |
| 1149 | // Right fill the mask of bits for this SUB to demand the most |
| 1150 | // significant bit and all those below it. |
| 1151 | uint32_t NLZ = DemandedMask.countLeadingZeros(); |
| 1152 | APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ)); |
| 1153 | if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps, |
| 1154 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1155 | return true; |
| 1156 | if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps, |
| 1157 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1158 | return true; |
| 1159 | } |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 1160 | // Otherwise just hand the sub off to ComputeMaskedBits to fill in |
| 1161 | // the known zeros and ones. |
| 1162 | ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1163 | break; |
| 1164 | case Instruction::Shl: |
| 1165 | if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1166 | uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); |
| 1167 | APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt)); |
| 1168 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, |
| 1169 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1170 | return true; |
| 1171 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1172 | "Bits known to be one AND zero?"); |
| 1173 | RHSKnownZero <<= ShiftAmt; |
| 1174 | RHSKnownOne <<= ShiftAmt; |
| 1175 | // low bits known zero. |
| 1176 | if (ShiftAmt) |
| 1177 | RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); |
| 1178 | } |
| 1179 | break; |
| 1180 | case Instruction::LShr: |
| 1181 | // For a logical shift right |
| 1182 | if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1183 | uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); |
| 1184 | |
| 1185 | // Unsigned shift right. |
| 1186 | APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); |
| 1187 | if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, |
| 1188 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1189 | return true; |
| 1190 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1191 | "Bits known to be one AND zero?"); |
| 1192 | RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt); |
| 1193 | RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt); |
| 1194 | if (ShiftAmt) { |
| 1195 | // Compute the new bits that are at the top now. |
| 1196 | APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt)); |
| 1197 | RHSKnownZero |= HighBits; // high bits known zero. |
| 1198 | } |
| 1199 | } |
| 1200 | break; |
| 1201 | case Instruction::AShr: |
| 1202 | // If this is an arithmetic shift right and only the low-bit is set, we can |
| 1203 | // always convert this into a logical shr, even if the shift amount is |
| 1204 | // variable. The low bit of the shift cannot be an input sign bit unless |
| 1205 | // the shift amount is >= the size of the datatype, which is undefined. |
| 1206 | if (DemandedMask == 1) { |
| 1207 | // Perform the logical shift right. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1208 | Value *NewVal = BinaryOperator::CreateLShr( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1209 | I->getOperand(0), I->getOperand(1), I->getName()); |
| 1210 | InsertNewInstBefore(cast<Instruction>(NewVal), *I); |
| 1211 | return UpdateValueUsesWith(I, NewVal); |
| 1212 | } |
| 1213 | |
| 1214 | // If the sign bit is the only bit demanded by this ashr, then there is no |
| 1215 | // need to do it, the shift doesn't change the high bit. |
| 1216 | if (DemandedMask.isSignBit()) |
| 1217 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 1218 | |
| 1219 | if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 1220 | uint32_t ShiftAmt = SA->getLimitedValue(BitWidth); |
| 1221 | |
| 1222 | // Signed shift right. |
| 1223 | APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); |
| 1224 | // If any of the "high bits" are demanded, we should set the sign bit as |
| 1225 | // demanded. |
| 1226 | if (DemandedMask.countLeadingZeros() <= ShiftAmt) |
| 1227 | DemandedMaskIn.set(BitWidth-1); |
| 1228 | if (SimplifyDemandedBits(I->getOperand(0), |
| 1229 | DemandedMaskIn, |
| 1230 | RHSKnownZero, RHSKnownOne, Depth+1)) |
| 1231 | return true; |
| 1232 | assert((RHSKnownZero & RHSKnownOne) == 0 && |
| 1233 | "Bits known to be one AND zero?"); |
| 1234 | // Compute the new bits that are at the top now. |
| 1235 | APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt)); |
| 1236 | RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt); |
| 1237 | RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt); |
| 1238 | |
| 1239 | // Handle the sign bits. |
| 1240 | APInt SignBit(APInt::getSignBit(BitWidth)); |
| 1241 | // Adjust to where it is now in the mask. |
| 1242 | SignBit = APIntOps::lshr(SignBit, ShiftAmt); |
| 1243 | |
| 1244 | // If the input sign bit is known to be zero, or if none of the top bits |
| 1245 | // are demanded, turn this into an unsigned shift right. |
Zhou Sheng | 533604e | 2008-06-06 08:32:05 +0000 | [diff] [blame] | 1246 | if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1247 | (HighBits & ~DemandedMask) == HighBits) { |
| 1248 | // Perform the logical shift right. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1249 | Value *NewVal = BinaryOperator::CreateLShr( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1250 | I->getOperand(0), SA, I->getName()); |
| 1251 | InsertNewInstBefore(cast<Instruction>(NewVal), *I); |
| 1252 | return UpdateValueUsesWith(I, NewVal); |
| 1253 | } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one. |
| 1254 | RHSKnownOne |= HighBits; |
| 1255 | } |
| 1256 | } |
| 1257 | break; |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 1258 | case Instruction::SRem: |
| 1259 | if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { |
Nick Lewycky | cfaaece | 2008-11-02 02:41:50 +0000 | [diff] [blame] | 1260 | APInt RA = Rem->getValue().abs(); |
| 1261 | if (RA.isPowerOf2()) { |
Nick Lewycky | 245de42 | 2008-07-12 05:04:38 +0000 | [diff] [blame] | 1262 | if (DemandedMask.ule(RA)) // srem won't affect demanded bits |
| 1263 | return UpdateValueUsesWith(I, I->getOperand(0)); |
| 1264 | |
Nick Lewycky | cfaaece | 2008-11-02 02:41:50 +0000 | [diff] [blame] | 1265 | APInt LowBits = RA - 1; |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 1266 | APInt Mask2 = LowBits | APInt::getSignBit(BitWidth); |
| 1267 | if (SimplifyDemandedBits(I->getOperand(0), Mask2, |
| 1268 | LHSKnownZero, LHSKnownOne, Depth+1)) |
| 1269 | return true; |
| 1270 | |
| 1271 | if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits)) |
| 1272 | LHSKnownZero |= ~LowBits; |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 1273 | |
| 1274 | KnownZero |= LHSKnownZero & DemandedMask; |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 1275 | |
| 1276 | assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); |
| 1277 | } |
| 1278 | } |
| 1279 | break; |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 1280 | case Instruction::URem: { |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 1281 | APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0); |
| 1282 | APInt AllOnes = APInt::getAllOnesValue(BitWidth); |
Dan Gohman | 23ea06d | 2008-05-01 19:13:24 +0000 | [diff] [blame] | 1283 | if (SimplifyDemandedBits(I->getOperand(0), AllOnes, |
| 1284 | KnownZero2, KnownOne2, Depth+1)) |
| 1285 | return true; |
| 1286 | |
Chris Lattner | ee5417c | 2009-01-21 18:09:24 +0000 | [diff] [blame] | 1287 | unsigned Leaders = KnownZero2.countLeadingOnes(); |
Dan Gohman | 23ea06d | 2008-05-01 19:13:24 +0000 | [diff] [blame] | 1288 | if (SimplifyDemandedBits(I->getOperand(1), AllOnes, |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 1289 | KnownZero2, KnownOne2, Depth+1)) |
| 1290 | return true; |
| 1291 | |
| 1292 | Leaders = std::max(Leaders, |
| 1293 | KnownZero2.countLeadingOnes()); |
| 1294 | KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask; |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 1295 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1296 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 1297 | case Instruction::Call: |
| 1298 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 1299 | switch (II->getIntrinsicID()) { |
| 1300 | default: break; |
| 1301 | case Intrinsic::bswap: { |
| 1302 | // If the only bits demanded come from one byte of the bswap result, |
| 1303 | // just shift the input byte into position to eliminate the bswap. |
| 1304 | unsigned NLZ = DemandedMask.countLeadingZeros(); |
| 1305 | unsigned NTZ = DemandedMask.countTrailingZeros(); |
| 1306 | |
| 1307 | // Round NTZ down to the next byte. If we have 11 trailing zeros, then |
| 1308 | // we need all the bits down to bit 8. Likewise, round NLZ. If we |
| 1309 | // have 14 leading zeros, round to 8. |
| 1310 | NLZ &= ~7; |
| 1311 | NTZ &= ~7; |
| 1312 | // If we need exactly one byte, we can do this transformation. |
| 1313 | if (BitWidth-NLZ-NTZ == 8) { |
| 1314 | unsigned ResultBit = NTZ; |
| 1315 | unsigned InputBit = BitWidth-NTZ-8; |
| 1316 | |
| 1317 | // Replace this with either a left or right shift to get the byte into |
| 1318 | // the right place. |
| 1319 | Instruction *NewVal; |
| 1320 | if (InputBit > ResultBit) |
| 1321 | NewVal = BinaryOperator::CreateLShr(I->getOperand(1), |
| 1322 | ConstantInt::get(I->getType(), InputBit-ResultBit)); |
| 1323 | else |
| 1324 | NewVal = BinaryOperator::CreateShl(I->getOperand(1), |
| 1325 | ConstantInt::get(I->getType(), ResultBit-InputBit)); |
| 1326 | NewVal->takeName(I); |
| 1327 | InsertNewInstBefore(NewVal, *I); |
| 1328 | return UpdateValueUsesWith(I, NewVal); |
| 1329 | } |
| 1330 | |
| 1331 | // TODO: Could compute known zero/one bits based on the input. |
| 1332 | break; |
| 1333 | } |
| 1334 | } |
| 1335 | } |
Chris Lattner | 4946e22 | 2008-06-18 18:11:55 +0000 | [diff] [blame] | 1336 | ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth); |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 1337 | break; |
Dan Gohman | bec1605 | 2008-04-28 17:02:21 +0000 | [diff] [blame] | 1338 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1339 | |
| 1340 | // If the client is only demanding bits that we know, return the known |
| 1341 | // constant. |
| 1342 | if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) |
| 1343 | return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne)); |
| 1344 | return false; |
| 1345 | } |
| 1346 | |
| 1347 | |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1348 | /// SimplifyDemandedVectorElts - The specified value produces a vector with |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1349 | /// 64 or fewer elements. DemandedElts contains the set of elements that are |
| 1350 | /// actually used by the caller. This method analyzes which elements of the |
| 1351 | /// operand are undef and returns that information in UndefElts. |
| 1352 | /// |
| 1353 | /// If the information about demanded elements can be used to simplify the |
| 1354 | /// operation, the operation is simplified, then the resultant value is |
| 1355 | /// returned. This returns null if no change was made. |
| 1356 | Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts, |
| 1357 | uint64_t &UndefElts, |
| 1358 | unsigned Depth) { |
| 1359 | unsigned VWidth = cast<VectorType>(V->getType())->getNumElements(); |
| 1360 | assert(VWidth <= 64 && "Vector too wide to analyze!"); |
| 1361 | uint64_t EltMask = ~0ULL >> (64-VWidth); |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1362 | assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1363 | |
| 1364 | if (isa<UndefValue>(V)) { |
| 1365 | // If the entire vector is undefined, just return this info. |
| 1366 | UndefElts = EltMask; |
| 1367 | return 0; |
| 1368 | } else if (DemandedElts == 0) { // If nothing is demanded, provide undef. |
| 1369 | UndefElts = EltMask; |
| 1370 | return UndefValue::get(V->getType()); |
| 1371 | } |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1372 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1373 | UndefElts = 0; |
| 1374 | if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) { |
| 1375 | const Type *EltTy = cast<VectorType>(V->getType())->getElementType(); |
| 1376 | Constant *Undef = UndefValue::get(EltTy); |
| 1377 | |
| 1378 | std::vector<Constant*> Elts; |
| 1379 | for (unsigned i = 0; i != VWidth; ++i) |
| 1380 | if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef. |
| 1381 | Elts.push_back(Undef); |
| 1382 | UndefElts |= (1ULL << i); |
| 1383 | } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef. |
| 1384 | Elts.push_back(Undef); |
| 1385 | UndefElts |= (1ULL << i); |
| 1386 | } else { // Otherwise, defined. |
| 1387 | Elts.push_back(CP->getOperand(i)); |
| 1388 | } |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1389 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1390 | // If we changed the constant, return it. |
| 1391 | Constant *NewCP = ConstantVector::get(Elts); |
| 1392 | return NewCP != CP ? NewCP : 0; |
| 1393 | } else if (isa<ConstantAggregateZero>(V)) { |
| 1394 | // Simplify the CAZ to a ConstantVector where the non-demanded elements are |
| 1395 | // set to undef. |
Mon P Wang | 927daf5 | 2008-11-06 22:52:21 +0000 | [diff] [blame] | 1396 | |
| 1397 | // Check if this is identity. If so, return 0 since we are not simplifying |
| 1398 | // anything. |
| 1399 | if (DemandedElts == ((1ULL << VWidth) -1)) |
| 1400 | return 0; |
| 1401 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1402 | const Type *EltTy = cast<VectorType>(V->getType())->getElementType(); |
| 1403 | Constant *Zero = Constant::getNullValue(EltTy); |
| 1404 | Constant *Undef = UndefValue::get(EltTy); |
| 1405 | std::vector<Constant*> Elts; |
| 1406 | for (unsigned i = 0; i != VWidth; ++i) |
| 1407 | Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef); |
| 1408 | UndefElts = DemandedElts ^ EltMask; |
| 1409 | return ConstantVector::get(Elts); |
| 1410 | } |
| 1411 | |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1412 | // Limit search depth. |
| 1413 | if (Depth == 10) |
| 1414 | return false; |
| 1415 | |
| 1416 | // If multiple users are using the root value, procede with |
| 1417 | // simplification conservatively assuming that all elements |
| 1418 | // are needed. |
| 1419 | if (!V->hasOneUse()) { |
| 1420 | // Quit if we find multiple users of a non-root value though. |
| 1421 | // They'll be handled when it's their turn to be visited by |
| 1422 | // the main instcombine process. |
| 1423 | if (Depth != 0) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1424 | // TODO: Just compute the UndefElts information recursively. |
| 1425 | return false; |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1426 | |
| 1427 | // Conservatively assume that all elements are needed. |
| 1428 | DemandedElts = EltMask; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1429 | } |
| 1430 | |
| 1431 | Instruction *I = dyn_cast<Instruction>(V); |
| 1432 | if (!I) return false; // Only analyze instructions. |
| 1433 | |
| 1434 | bool MadeChange = false; |
| 1435 | uint64_t UndefElts2; |
| 1436 | Value *TmpV; |
| 1437 | switch (I->getOpcode()) { |
| 1438 | default: break; |
| 1439 | |
| 1440 | case Instruction::InsertElement: { |
| 1441 | // If this is a variable index, we don't know which element it overwrites. |
| 1442 | // demand exactly the same input as we produce. |
| 1443 | ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2)); |
| 1444 | if (Idx == 0) { |
| 1445 | // Note that we can't propagate undef elt info, because we don't know |
| 1446 | // which elt is getting updated. |
| 1447 | TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, |
| 1448 | UndefElts2, Depth+1); |
| 1449 | if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; } |
| 1450 | break; |
| 1451 | } |
| 1452 | |
| 1453 | // If this is inserting an element that isn't demanded, remove this |
| 1454 | // insertelement. |
| 1455 | unsigned IdxNo = Idx->getZExtValue(); |
| 1456 | if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0) |
| 1457 | return AddSoonDeadInstToWorklist(*I, 0); |
| 1458 | |
| 1459 | // Otherwise, the element inserted overwrites whatever was there, so the |
| 1460 | // input demanded set is simpler than the output set. |
| 1461 | TmpV = SimplifyDemandedVectorElts(I->getOperand(0), |
| 1462 | DemandedElts & ~(1ULL << IdxNo), |
| 1463 | UndefElts, Depth+1); |
| 1464 | if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; } |
| 1465 | |
| 1466 | // The inserted element is defined. |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1467 | UndefElts &= ~(1ULL << IdxNo); |
| 1468 | break; |
| 1469 | } |
| 1470 | case Instruction::ShuffleVector: { |
| 1471 | ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1472 | uint64_t LHSVWidth = |
| 1473 | cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements(); |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1474 | uint64_t LeftDemanded = 0, RightDemanded = 0; |
| 1475 | for (unsigned i = 0; i < VWidth; i++) { |
| 1476 | if (DemandedElts & (1ULL << i)) { |
| 1477 | unsigned MaskVal = Shuffle->getMaskValue(i); |
| 1478 | if (MaskVal != -1u) { |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1479 | assert(MaskVal < LHSVWidth * 2 && |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1480 | "shufflevector mask index out of range!"); |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1481 | if (MaskVal < LHSVWidth) |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1482 | LeftDemanded |= 1ULL << MaskVal; |
| 1483 | else |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1484 | RightDemanded |= 1ULL << (MaskVal - LHSVWidth); |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1485 | } |
| 1486 | } |
| 1487 | } |
| 1488 | |
| 1489 | TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded, |
| 1490 | UndefElts2, Depth+1); |
| 1491 | if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; } |
| 1492 | |
| 1493 | uint64_t UndefElts3; |
| 1494 | TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded, |
| 1495 | UndefElts3, Depth+1); |
| 1496 | if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; } |
| 1497 | |
| 1498 | bool NewUndefElts = false; |
| 1499 | for (unsigned i = 0; i < VWidth; i++) { |
| 1500 | unsigned MaskVal = Shuffle->getMaskValue(i); |
Dan Gohman | 24f6ee2 | 2008-09-10 01:09:32 +0000 | [diff] [blame] | 1501 | if (MaskVal == -1u) { |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1502 | uint64_t NewBit = 1ULL << i; |
| 1503 | UndefElts |= NewBit; |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1504 | } else if (MaskVal < LHSVWidth) { |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1505 | uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i; |
| 1506 | NewUndefElts |= NewBit; |
| 1507 | UndefElts |= NewBit; |
| 1508 | } else { |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 1509 | uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i; |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 1510 | NewUndefElts |= NewBit; |
| 1511 | UndefElts |= NewBit; |
| 1512 | } |
| 1513 | } |
| 1514 | |
| 1515 | if (NewUndefElts) { |
| 1516 | // Add additional discovered undefs. |
| 1517 | std::vector<Constant*> Elts; |
| 1518 | for (unsigned i = 0; i < VWidth; ++i) { |
| 1519 | if (UndefElts & (1ULL << i)) |
| 1520 | Elts.push_back(UndefValue::get(Type::Int32Ty)); |
| 1521 | else |
| 1522 | Elts.push_back(ConstantInt::get(Type::Int32Ty, |
| 1523 | Shuffle->getMaskValue(i))); |
| 1524 | } |
| 1525 | I->setOperand(2, ConstantVector::get(Elts)); |
| 1526 | MadeChange = true; |
| 1527 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1528 | break; |
| 1529 | } |
| 1530 | case Instruction::BitCast: { |
| 1531 | // Vector->vector casts only. |
| 1532 | const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType()); |
| 1533 | if (!VTy) break; |
| 1534 | unsigned InVWidth = VTy->getNumElements(); |
| 1535 | uint64_t InputDemandedElts = 0; |
| 1536 | unsigned Ratio; |
| 1537 | |
| 1538 | if (VWidth == InVWidth) { |
| 1539 | // If we are converting from <4 x i32> -> <4 x f32>, we demand the same |
| 1540 | // elements as are demanded of us. |
| 1541 | Ratio = 1; |
| 1542 | InputDemandedElts = DemandedElts; |
| 1543 | } else if (VWidth > InVWidth) { |
| 1544 | // Untested so far. |
| 1545 | break; |
| 1546 | |
| 1547 | // If there are more elements in the result than there are in the source, |
| 1548 | // then an input element is live if any of the corresponding output |
| 1549 | // elements are live. |
| 1550 | Ratio = VWidth/InVWidth; |
| 1551 | for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) { |
| 1552 | if (DemandedElts & (1ULL << OutIdx)) |
| 1553 | InputDemandedElts |= 1ULL << (OutIdx/Ratio); |
| 1554 | } |
| 1555 | } else { |
| 1556 | // Untested so far. |
| 1557 | break; |
| 1558 | |
| 1559 | // If there are more elements in the source than there are in the result, |
| 1560 | // then an input element is live if the corresponding output element is |
| 1561 | // live. |
| 1562 | Ratio = InVWidth/VWidth; |
| 1563 | for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx) |
| 1564 | if (DemandedElts & (1ULL << InIdx/Ratio)) |
| 1565 | InputDemandedElts |= 1ULL << InIdx; |
| 1566 | } |
| 1567 | |
| 1568 | // div/rem demand all inputs, because they don't want divide by zero. |
| 1569 | TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts, |
| 1570 | UndefElts2, Depth+1); |
| 1571 | if (TmpV) { |
| 1572 | I->setOperand(0, TmpV); |
| 1573 | MadeChange = true; |
| 1574 | } |
| 1575 | |
| 1576 | UndefElts = UndefElts2; |
| 1577 | if (VWidth > InVWidth) { |
| 1578 | assert(0 && "Unimp"); |
| 1579 | // If there are more elements in the result than there are in the source, |
| 1580 | // then an output element is undef if the corresponding input element is |
| 1581 | // undef. |
| 1582 | for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) |
| 1583 | if (UndefElts2 & (1ULL << (OutIdx/Ratio))) |
| 1584 | UndefElts |= 1ULL << OutIdx; |
| 1585 | } else if (VWidth < InVWidth) { |
| 1586 | assert(0 && "Unimp"); |
| 1587 | // If there are more elements in the source than there are in the result, |
| 1588 | // then a result element is undef if all of the corresponding input |
| 1589 | // elements are undef. |
| 1590 | UndefElts = ~0ULL >> (64-VWidth); // Start out all undef. |
| 1591 | for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx) |
| 1592 | if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef? |
| 1593 | UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit. |
| 1594 | } |
| 1595 | break; |
| 1596 | } |
| 1597 | case Instruction::And: |
| 1598 | case Instruction::Or: |
| 1599 | case Instruction::Xor: |
| 1600 | case Instruction::Add: |
| 1601 | case Instruction::Sub: |
| 1602 | case Instruction::Mul: |
| 1603 | // div/rem demand all inputs, because they don't want divide by zero. |
| 1604 | TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts, |
| 1605 | UndefElts, Depth+1); |
| 1606 | if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; } |
| 1607 | TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts, |
| 1608 | UndefElts2, Depth+1); |
| 1609 | if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; } |
| 1610 | |
| 1611 | // Output elements are undefined if both are undefined. Consider things |
| 1612 | // like undef&0. The result is known zero, not undef. |
| 1613 | UndefElts &= UndefElts2; |
| 1614 | break; |
| 1615 | |
| 1616 | case Instruction::Call: { |
| 1617 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); |
| 1618 | if (!II) break; |
| 1619 | switch (II->getIntrinsicID()) { |
| 1620 | default: break; |
| 1621 | |
| 1622 | // Binary vector operations that work column-wise. A dest element is a |
| 1623 | // function of the corresponding input elements from the two inputs. |
| 1624 | case Intrinsic::x86_sse_sub_ss: |
| 1625 | case Intrinsic::x86_sse_mul_ss: |
| 1626 | case Intrinsic::x86_sse_min_ss: |
| 1627 | case Intrinsic::x86_sse_max_ss: |
| 1628 | case Intrinsic::x86_sse2_sub_sd: |
| 1629 | case Intrinsic::x86_sse2_mul_sd: |
| 1630 | case Intrinsic::x86_sse2_min_sd: |
| 1631 | case Intrinsic::x86_sse2_max_sd: |
| 1632 | TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts, |
| 1633 | UndefElts, Depth+1); |
| 1634 | if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; } |
| 1635 | TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts, |
| 1636 | UndefElts2, Depth+1); |
| 1637 | if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; } |
| 1638 | |
| 1639 | // If only the low elt is demanded and this is a scalarizable intrinsic, |
| 1640 | // scalarize it now. |
| 1641 | if (DemandedElts == 1) { |
| 1642 | switch (II->getIntrinsicID()) { |
| 1643 | default: break; |
| 1644 | case Intrinsic::x86_sse_sub_ss: |
| 1645 | case Intrinsic::x86_sse_mul_ss: |
| 1646 | case Intrinsic::x86_sse2_sub_sd: |
| 1647 | case Intrinsic::x86_sse2_mul_sd: |
| 1648 | // TODO: Lower MIN/MAX/ABS/etc |
| 1649 | Value *LHS = II->getOperand(1); |
| 1650 | Value *RHS = II->getOperand(2); |
| 1651 | // Extract the element as scalars. |
| 1652 | LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II); |
| 1653 | RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II); |
| 1654 | |
| 1655 | switch (II->getIntrinsicID()) { |
| 1656 | default: assert(0 && "Case stmts out of sync!"); |
| 1657 | case Intrinsic::x86_sse_sub_ss: |
| 1658 | case Intrinsic::x86_sse2_sub_sd: |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1659 | TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1660 | II->getName()), *II); |
| 1661 | break; |
| 1662 | case Intrinsic::x86_sse_mul_ss: |
| 1663 | case Intrinsic::x86_sse2_mul_sd: |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1664 | TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1665 | II->getName()), *II); |
| 1666 | break; |
| 1667 | } |
| 1668 | |
| 1669 | Instruction *New = |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1670 | InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U, |
| 1671 | II->getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1672 | InsertNewInstBefore(New, *II); |
| 1673 | AddSoonDeadInstToWorklist(*II, 0); |
| 1674 | return New; |
| 1675 | } |
| 1676 | } |
| 1677 | |
| 1678 | // Output elements are undefined if both are undefined. Consider things |
| 1679 | // like undef&0. The result is known zero, not undef. |
| 1680 | UndefElts &= UndefElts2; |
| 1681 | break; |
| 1682 | } |
| 1683 | break; |
| 1684 | } |
| 1685 | } |
| 1686 | return MadeChange ? I : 0; |
| 1687 | } |
| 1688 | |
Dan Gohman | 5d56fd4 | 2008-05-19 22:14:15 +0000 | [diff] [blame] | 1689 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1690 | /// AssociativeOpt - Perform an optimization on an associative operator. This |
| 1691 | /// function is designed to check a chain of associative operators for a |
| 1692 | /// potential to apply a certain optimization. Since the optimization may be |
| 1693 | /// applicable if the expression was reassociated, this checks the chain, then |
| 1694 | /// reassociates the expression as necessary to expose the optimization |
| 1695 | /// opportunity. This makes use of a special Functor, which must define |
| 1696 | /// 'shouldApply' and 'apply' methods. |
| 1697 | /// |
| 1698 | template<typename Functor> |
Dan Gohman | d8bcf5b | 2008-05-20 01:14:05 +0000 | [diff] [blame] | 1699 | static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1700 | unsigned Opcode = Root.getOpcode(); |
| 1701 | Value *LHS = Root.getOperand(0); |
| 1702 | |
| 1703 | // Quick check, see if the immediate LHS matches... |
| 1704 | if (F.shouldApply(LHS)) |
| 1705 | return F.apply(Root); |
| 1706 | |
| 1707 | // Otherwise, if the LHS is not of the same opcode as the root, return. |
| 1708 | Instruction *LHSI = dyn_cast<Instruction>(LHS); |
| 1709 | while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) { |
| 1710 | // Should we apply this transform to the RHS? |
| 1711 | bool ShouldApply = F.shouldApply(LHSI->getOperand(1)); |
| 1712 | |
| 1713 | // If not to the RHS, check to see if we should apply to the LHS... |
| 1714 | if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) { |
| 1715 | cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS |
| 1716 | ShouldApply = true; |
| 1717 | } |
| 1718 | |
| 1719 | // If the functor wants to apply the optimization to the RHS of LHSI, |
| 1720 | // reassociate the expression from ((? op A) op B) to (? op (A op B)) |
| 1721 | if (ShouldApply) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1722 | // Now all of the instructions are in the current basic block, go ahead |
| 1723 | // and perform the reassociation. |
| 1724 | Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0)); |
| 1725 | |
| 1726 | // First move the selected RHS to the LHS of the root... |
| 1727 | Root.setOperand(0, LHSI->getOperand(1)); |
| 1728 | |
| 1729 | // Make what used to be the LHS of the root be the user of the root... |
| 1730 | Value *ExtraOperand = TmpLHSI->getOperand(1); |
| 1731 | if (&Root == TmpLHSI) { |
| 1732 | Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType())); |
| 1733 | return 0; |
| 1734 | } |
| 1735 | Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI |
| 1736 | TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1737 | BasicBlock::iterator ARI = &Root; ++ARI; |
Dan Gohman | 0bb9a3d | 2008-06-19 17:47:47 +0000 | [diff] [blame] | 1738 | TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1739 | ARI = Root; |
| 1740 | |
| 1741 | // Now propagate the ExtraOperand down the chain of instructions until we |
| 1742 | // get to LHSI. |
| 1743 | while (TmpLHSI != LHSI) { |
| 1744 | Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0)); |
| 1745 | // Move the instruction to immediately before the chain we are |
| 1746 | // constructing to avoid breaking dominance properties. |
Dan Gohman | 0bb9a3d | 2008-06-19 17:47:47 +0000 | [diff] [blame] | 1747 | NextLHSI->moveBefore(ARI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1748 | ARI = NextLHSI; |
| 1749 | |
| 1750 | Value *NextOp = NextLHSI->getOperand(1); |
| 1751 | NextLHSI->setOperand(1, ExtraOperand); |
| 1752 | TmpLHSI = NextLHSI; |
| 1753 | ExtraOperand = NextOp; |
| 1754 | } |
| 1755 | |
| 1756 | // Now that the instructions are reassociated, have the functor perform |
| 1757 | // the transformation... |
| 1758 | return F.apply(Root); |
| 1759 | } |
| 1760 | |
| 1761 | LHSI = dyn_cast<Instruction>(LHSI->getOperand(0)); |
| 1762 | } |
| 1763 | return 0; |
| 1764 | } |
| 1765 | |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 1766 | namespace { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1767 | |
Nick Lewycky | 27f6c13 | 2008-05-23 04:34:58 +0000 | [diff] [blame] | 1768 | // AddRHS - Implements: X + X --> X << 1 |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1769 | struct AddRHS { |
| 1770 | Value *RHS; |
| 1771 | AddRHS(Value *rhs) : RHS(rhs) {} |
| 1772 | bool shouldApply(Value *LHS) const { return LHS == RHS; } |
| 1773 | Instruction *apply(BinaryOperator &Add) const { |
Nick Lewycky | 27f6c13 | 2008-05-23 04:34:58 +0000 | [diff] [blame] | 1774 | return BinaryOperator::CreateShl(Add.getOperand(0), |
| 1775 | ConstantInt::get(Add.getType(), 1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1776 | } |
| 1777 | }; |
| 1778 | |
| 1779 | // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2) |
| 1780 | // iff C1&C2 == 0 |
| 1781 | struct AddMaskingAnd { |
| 1782 | Constant *C2; |
| 1783 | AddMaskingAnd(Constant *c) : C2(c) {} |
| 1784 | bool shouldApply(Value *LHS) const { |
| 1785 | ConstantInt *C1; |
| 1786 | return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) && |
| 1787 | ConstantExpr::getAnd(C1, C2)->isNullValue(); |
| 1788 | } |
| 1789 | Instruction *apply(BinaryOperator &Add) const { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1790 | return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1791 | } |
| 1792 | }; |
| 1793 | |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 1794 | } |
| 1795 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1796 | static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO, |
| 1797 | InstCombiner *IC) { |
| 1798 | if (CastInst *CI = dyn_cast<CastInst>(&I)) { |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 1799 | return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1800 | } |
| 1801 | |
| 1802 | // Figure out if the constant is the left or the right argument. |
| 1803 | bool ConstIsRHS = isa<Constant>(I.getOperand(1)); |
| 1804 | Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); |
| 1805 | |
| 1806 | if (Constant *SOC = dyn_cast<Constant>(SO)) { |
| 1807 | if (ConstIsRHS) |
| 1808 | return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); |
| 1809 | return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); |
| 1810 | } |
| 1811 | |
| 1812 | Value *Op0 = SO, *Op1 = ConstOperand; |
| 1813 | if (!ConstIsRHS) |
| 1814 | std::swap(Op0, Op1); |
| 1815 | Instruction *New; |
| 1816 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1817 | New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1818 | else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1819 | New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1820 | SO->getName()+".cmp"); |
| 1821 | else { |
| 1822 | assert(0 && "Unknown binary instruction type!"); |
| 1823 | abort(); |
| 1824 | } |
| 1825 | return IC->InsertNewInstBefore(New, I); |
| 1826 | } |
| 1827 | |
| 1828 | // FoldOpIntoSelect - Given an instruction with a select as one operand and a |
| 1829 | // constant as the other operand, try to fold the binary operator into the |
| 1830 | // select arguments. This also works for Cast instructions, which obviously do |
| 1831 | // not have a second operand. |
| 1832 | static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI, |
| 1833 | InstCombiner *IC) { |
| 1834 | // Don't modify shared select instructions |
| 1835 | if (!SI->hasOneUse()) return 0; |
| 1836 | Value *TV = SI->getOperand(1); |
| 1837 | Value *FV = SI->getOperand(2); |
| 1838 | |
| 1839 | if (isa<Constant>(TV) || isa<Constant>(FV)) { |
| 1840 | // Bool selects with constant operands can be folded to logical ops. |
| 1841 | if (SI->getType() == Type::Int1Ty) return 0; |
| 1842 | |
| 1843 | Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC); |
| 1844 | Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC); |
| 1845 | |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1846 | return SelectInst::Create(SI->getCondition(), SelectTrueVal, |
| 1847 | SelectFalseVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1848 | } |
| 1849 | return 0; |
| 1850 | } |
| 1851 | |
| 1852 | |
| 1853 | /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI |
| 1854 | /// node as operand #0, see if we can fold the instruction into the PHI (which |
| 1855 | /// is only possible if all operands to the PHI are constants). |
| 1856 | Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) { |
| 1857 | PHINode *PN = cast<PHINode>(I.getOperand(0)); |
| 1858 | unsigned NumPHIValues = PN->getNumIncomingValues(); |
| 1859 | if (!PN->hasOneUse() || NumPHIValues == 0) return 0; |
| 1860 | |
| 1861 | // Check to see if all of the operands of the PHI are constants. If there is |
| 1862 | // one non-constant value, remember the BB it is. If there is more than one |
| 1863 | // or if *it* is a PHI, bail out. |
| 1864 | BasicBlock *NonConstBB = 0; |
| 1865 | for (unsigned i = 0; i != NumPHIValues; ++i) |
| 1866 | if (!isa<Constant>(PN->getIncomingValue(i))) { |
| 1867 | if (NonConstBB) return 0; // More than one non-const value. |
| 1868 | if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi. |
| 1869 | NonConstBB = PN->getIncomingBlock(i); |
| 1870 | |
| 1871 | // If the incoming non-constant value is in I's block, we have an infinite |
| 1872 | // loop. |
| 1873 | if (NonConstBB == I.getParent()) |
| 1874 | return 0; |
| 1875 | } |
| 1876 | |
| 1877 | // If there is exactly one non-constant value, we can insert a copy of the |
| 1878 | // operation in that block. However, if this is a critical edge, we would be |
| 1879 | // inserting the computation one some other paths (e.g. inside a loop). Only |
| 1880 | // do this if the pred block is unconditionally branching into the phi block. |
| 1881 | if (NonConstBB) { |
| 1882 | BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); |
| 1883 | if (!BI || !BI->isUnconditional()) return 0; |
| 1884 | } |
| 1885 | |
| 1886 | // Okay, we can do the transformation: create the new PHI node. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1887 | PHINode *NewPN = PHINode::Create(I.getType(), ""); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1888 | NewPN->reserveOperandSpace(PN->getNumOperands()/2); |
| 1889 | InsertNewInstBefore(NewPN, *PN); |
| 1890 | NewPN->takeName(PN); |
| 1891 | |
| 1892 | // Next, add all of the operands to the PHI. |
| 1893 | if (I.getNumOperands() == 2) { |
| 1894 | Constant *C = cast<Constant>(I.getOperand(1)); |
| 1895 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
Chris Lattner | b933ea6 | 2007-08-05 08:47:58 +0000 | [diff] [blame] | 1896 | Value *InV = 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1897 | if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { |
| 1898 | if (CmpInst *CI = dyn_cast<CmpInst>(&I)) |
| 1899 | InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); |
| 1900 | else |
| 1901 | InV = ConstantExpr::get(I.getOpcode(), InC, C); |
| 1902 | } else { |
| 1903 | assert(PN->getIncomingBlock(i) == NonConstBB); |
| 1904 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1905 | InV = BinaryOperator::Create(BO->getOpcode(), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1906 | PN->getIncomingValue(i), C, "phitmp", |
| 1907 | NonConstBB->getTerminator()); |
| 1908 | else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1909 | InV = CmpInst::Create(CI->getOpcode(), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1910 | CI->getPredicate(), |
| 1911 | PN->getIncomingValue(i), C, "phitmp", |
| 1912 | NonConstBB->getTerminator()); |
| 1913 | else |
| 1914 | assert(0 && "Unknown binop!"); |
| 1915 | |
| 1916 | AddToWorkList(cast<Instruction>(InV)); |
| 1917 | } |
| 1918 | NewPN->addIncoming(InV, PN->getIncomingBlock(i)); |
| 1919 | } |
| 1920 | } else { |
| 1921 | CastInst *CI = cast<CastInst>(&I); |
| 1922 | const Type *RetTy = CI->getType(); |
| 1923 | for (unsigned i = 0; i != NumPHIValues; ++i) { |
| 1924 | Value *InV; |
| 1925 | if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { |
| 1926 | InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); |
| 1927 | } else { |
| 1928 | assert(PN->getIncomingBlock(i) == NonConstBB); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1929 | InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1930 | I.getType(), "phitmp", |
| 1931 | NonConstBB->getTerminator()); |
| 1932 | AddToWorkList(cast<Instruction>(InV)); |
| 1933 | } |
| 1934 | NewPN->addIncoming(InV, PN->getIncomingBlock(i)); |
| 1935 | } |
| 1936 | } |
| 1937 | return ReplaceInstUsesWith(I, NewPN); |
| 1938 | } |
| 1939 | |
Chris Lattner | 5547616 | 2008-01-29 06:52:45 +0000 | [diff] [blame] | 1940 | |
Chris Lattner | 3554f97 | 2008-05-20 05:46:13 +0000 | [diff] [blame] | 1941 | /// WillNotOverflowSignedAdd - Return true if we can prove that: |
| 1942 | /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS)) |
| 1943 | /// This basically requires proving that the add in the original type would not |
| 1944 | /// overflow to change the sign bit or have a carry out. |
| 1945 | bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) { |
| 1946 | // There are different heuristics we can use for this. Here are some simple |
| 1947 | // ones. |
| 1948 | |
| 1949 | // Add has the property that adding any two 2's complement numbers can only |
| 1950 | // have one carry bit which can change a sign. As such, if LHS and RHS each |
| 1951 | // have at least two sign bits, we know that the addition of the two values will |
| 1952 | // sign extend fine. |
| 1953 | if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1) |
| 1954 | return true; |
| 1955 | |
| 1956 | |
| 1957 | // If one of the operands only has one non-zero bit, and if the other operand |
| 1958 | // has a known-zero bit in a more significant place than it (not including the |
| 1959 | // sign bit) the ripple may go up to and fill the zero, but won't change the |
| 1960 | // sign. For example, (X & ~4) + 1. |
| 1961 | |
| 1962 | // TODO: Implement. |
| 1963 | |
| 1964 | return false; |
| 1965 | } |
| 1966 | |
Chris Lattner | 5547616 | 2008-01-29 06:52:45 +0000 | [diff] [blame] | 1967 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1968 | Instruction *InstCombiner::visitAdd(BinaryOperator &I) { |
| 1969 | bool Changed = SimplifyCommutative(I); |
| 1970 | Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); |
| 1971 | |
| 1972 | if (Constant *RHSC = dyn_cast<Constant>(RHS)) { |
| 1973 | // X + undef -> undef |
| 1974 | if (isa<UndefValue>(RHS)) |
| 1975 | return ReplaceInstUsesWith(I, RHS); |
| 1976 | |
| 1977 | // X + 0 --> X |
| 1978 | if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0. |
| 1979 | if (RHSC->isNullValue()) |
| 1980 | return ReplaceInstUsesWith(I, LHS); |
| 1981 | } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) { |
Dale Johannesen | 2fc2078 | 2007-09-14 22:26:36 +0000 | [diff] [blame] | 1982 | if (CFP->isExactlyValue(ConstantFP::getNegativeZero |
| 1983 | (I.getType())->getValueAPF())) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1984 | return ReplaceInstUsesWith(I, LHS); |
| 1985 | } |
| 1986 | |
| 1987 | if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) { |
| 1988 | // X + (signbit) --> X ^ signbit |
| 1989 | const APInt& Val = CI->getValue(); |
| 1990 | uint32_t BitWidth = Val.getBitWidth(); |
| 1991 | if (Val == APInt::getSignBit(BitWidth)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 1992 | return BinaryOperator::CreateXor(LHS, RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 1993 | |
| 1994 | // See if SimplifyDemandedBits can simplify this. This handles stuff like |
| 1995 | // (X & 254)+1 -> (X&254)|1 |
| 1996 | if (!isa<VectorType>(I.getType())) { |
| 1997 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 1998 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth), |
| 1999 | KnownZero, KnownOne)) |
| 2000 | return &I; |
| 2001 | } |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 2002 | |
| 2003 | // zext(i1) - 1 -> select i1, 0, -1 |
| 2004 | if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS)) |
| 2005 | if (CI->isAllOnesValue() && |
| 2006 | ZI->getOperand(0)->getType() == Type::Int1Ty) |
| 2007 | return SelectInst::Create(ZI->getOperand(0), |
| 2008 | Constant::getNullValue(I.getType()), |
| 2009 | ConstantInt::getAllOnesValue(I.getType())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2010 | } |
| 2011 | |
| 2012 | if (isa<PHINode>(LHS)) |
| 2013 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 2014 | return NV; |
| 2015 | |
| 2016 | ConstantInt *XorRHS = 0; |
| 2017 | Value *XorLHS = 0; |
| 2018 | if (isa<ConstantInt>(RHSC) && |
| 2019 | match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) { |
| 2020 | uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits(); |
| 2021 | const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue(); |
| 2022 | |
| 2023 | uint32_t Size = TySizeBits / 2; |
| 2024 | APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1)); |
| 2025 | APInt CFF80Val(-C0080Val); |
| 2026 | do { |
| 2027 | if (TySizeBits > Size) { |
| 2028 | // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext. |
| 2029 | // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext. |
| 2030 | if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) || |
| 2031 | (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) { |
| 2032 | // This is a sign extend if the top bits are known zero. |
| 2033 | if (!MaskedValueIsZero(XorLHS, |
| 2034 | APInt::getHighBitsSet(TySizeBits, TySizeBits - Size))) |
| 2035 | Size = 0; // Not a sign ext, but can't be any others either. |
| 2036 | break; |
| 2037 | } |
| 2038 | } |
| 2039 | Size >>= 1; |
| 2040 | C0080Val = APIntOps::lshr(C0080Val, Size); |
| 2041 | CFF80Val = APIntOps::ashr(CFF80Val, Size); |
| 2042 | } while (Size >= 1); |
| 2043 | |
| 2044 | // FIXME: This shouldn't be necessary. When the backends can handle types |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 2045 | // with funny bit widths then this switch statement should be removed. It |
| 2046 | // is just here to get the size of the "middle" type back up to something |
| 2047 | // that the back ends can handle. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2048 | const Type *MiddleType = 0; |
| 2049 | switch (Size) { |
| 2050 | default: break; |
| 2051 | case 32: MiddleType = Type::Int32Ty; break; |
| 2052 | case 16: MiddleType = Type::Int16Ty; break; |
| 2053 | case 8: MiddleType = Type::Int8Ty; break; |
| 2054 | } |
| 2055 | if (MiddleType) { |
| 2056 | Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext"); |
| 2057 | InsertNewInstBefore(NewTrunc, I); |
| 2058 | return new SExtInst(NewTrunc, I.getType(), I.getName()); |
| 2059 | } |
| 2060 | } |
| 2061 | } |
| 2062 | |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2063 | if (I.getType() == Type::Int1Ty) |
| 2064 | return BinaryOperator::CreateXor(LHS, RHS); |
| 2065 | |
Nick Lewycky | 4d474cd | 2008-05-23 04:39:38 +0000 | [diff] [blame] | 2066 | // X + X --> X << 1 |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2067 | if (I.getType()->isInteger()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2068 | if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result; |
| 2069 | |
| 2070 | if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) { |
| 2071 | if (RHSI->getOpcode() == Instruction::Sub) |
| 2072 | if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B |
| 2073 | return ReplaceInstUsesWith(I, RHSI->getOperand(0)); |
| 2074 | } |
| 2075 | if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) { |
| 2076 | if (LHSI->getOpcode() == Instruction::Sub) |
| 2077 | if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B |
| 2078 | return ReplaceInstUsesWith(I, LHSI->getOperand(0)); |
| 2079 | } |
| 2080 | } |
| 2081 | |
| 2082 | // -A + B --> B - A |
Chris Lattner | 53c9fbf | 2008-02-17 21:03:36 +0000 | [diff] [blame] | 2083 | // -A + -B --> -(A + B) |
| 2084 | if (Value *LHSV = dyn_castNegVal(LHS)) { |
Chris Lattner | 322a919 | 2008-02-18 17:50:16 +0000 | [diff] [blame] | 2085 | if (LHS->getType()->isIntOrIntVector()) { |
| 2086 | if (Value *RHSV = dyn_castNegVal(RHS)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2087 | Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum"); |
Chris Lattner | 322a919 | 2008-02-18 17:50:16 +0000 | [diff] [blame] | 2088 | InsertNewInstBefore(NewAdd, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2089 | return BinaryOperator::CreateNeg(NewAdd); |
Chris Lattner | 322a919 | 2008-02-18 17:50:16 +0000 | [diff] [blame] | 2090 | } |
Chris Lattner | 53c9fbf | 2008-02-17 21:03:36 +0000 | [diff] [blame] | 2091 | } |
| 2092 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2093 | return BinaryOperator::CreateSub(RHS, LHSV); |
Chris Lattner | 53c9fbf | 2008-02-17 21:03:36 +0000 | [diff] [blame] | 2094 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2095 | |
| 2096 | // A + -B --> A - B |
| 2097 | if (!isa<Constant>(RHS)) |
| 2098 | if (Value *V = dyn_castNegVal(RHS)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2099 | return BinaryOperator::CreateSub(LHS, V); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2100 | |
| 2101 | |
| 2102 | ConstantInt *C2; |
| 2103 | if (Value *X = dyn_castFoldableMul(LHS, C2)) { |
| 2104 | if (X == RHS) // X*C + X --> X * (C+1) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2105 | return BinaryOperator::CreateMul(RHS, AddOne(C2)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2106 | |
| 2107 | // X*C1 + X*C2 --> X * (C1+C2) |
| 2108 | ConstantInt *C1; |
| 2109 | if (X == dyn_castFoldableMul(RHS, C1)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2110 | return BinaryOperator::CreateMul(X, Add(C1, C2)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2111 | } |
| 2112 | |
| 2113 | // X + X*C --> X * (C+1) |
| 2114 | if (dyn_castFoldableMul(RHS, C2) == LHS) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2115 | return BinaryOperator::CreateMul(LHS, AddOne(C2)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2116 | |
| 2117 | // X + ~X --> -1 since ~X = -X-1 |
| 2118 | if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS) |
| 2119 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 2120 | |
| 2121 | |
| 2122 | // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0 |
| 2123 | if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)))) |
| 2124 | if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) |
| 2125 | return R; |
Chris Lattner | c1575ce | 2008-05-19 20:01:56 +0000 | [diff] [blame] | 2126 | |
| 2127 | // A+B --> A|B iff A and B have no bits set in common. |
| 2128 | if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) { |
| 2129 | APInt Mask = APInt::getAllOnesValue(IT->getBitWidth()); |
| 2130 | APInt LHSKnownOne(IT->getBitWidth(), 0); |
| 2131 | APInt LHSKnownZero(IT->getBitWidth(), 0); |
| 2132 | ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne); |
| 2133 | if (LHSKnownZero != 0) { |
| 2134 | APInt RHSKnownOne(IT->getBitWidth(), 0); |
| 2135 | APInt RHSKnownZero(IT->getBitWidth(), 0); |
| 2136 | ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne); |
| 2137 | |
| 2138 | // No bits in common -> bitwise or. |
Chris Lattner | 130443c | 2008-05-19 20:03:53 +0000 | [diff] [blame] | 2139 | if ((LHSKnownZero|RHSKnownZero).isAllOnesValue()) |
Chris Lattner | c1575ce | 2008-05-19 20:01:56 +0000 | [diff] [blame] | 2140 | return BinaryOperator::CreateOr(LHS, RHS); |
Chris Lattner | c1575ce | 2008-05-19 20:01:56 +0000 | [diff] [blame] | 2141 | } |
| 2142 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2143 | |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2144 | // W*X + Y*Z --> W * (X+Z) iff W == Y |
Nick Lewycky | 5d03b51 | 2008-02-03 08:19:11 +0000 | [diff] [blame] | 2145 | if (I.getType()->isIntOrIntVector()) { |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2146 | Value *W, *X, *Y, *Z; |
| 2147 | if (match(LHS, m_Mul(m_Value(W), m_Value(X))) && |
| 2148 | match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) { |
| 2149 | if (W != Y) { |
| 2150 | if (W == Z) { |
Bill Wendling | 44a36ea | 2008-02-26 10:53:30 +0000 | [diff] [blame] | 2151 | std::swap(Y, Z); |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2152 | } else if (Y == X) { |
Bill Wendling | 44a36ea | 2008-02-26 10:53:30 +0000 | [diff] [blame] | 2153 | std::swap(W, X); |
| 2154 | } else if (X == Z) { |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2155 | std::swap(Y, Z); |
| 2156 | std::swap(W, X); |
| 2157 | } |
| 2158 | } |
| 2159 | |
| 2160 | if (W == Y) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2161 | Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z, |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2162 | LHS->getName()), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2163 | return BinaryOperator::CreateMul(W, NewAdd); |
Nick Lewycky | 83598a7 | 2008-02-03 07:42:09 +0000 | [diff] [blame] | 2164 | } |
| 2165 | } |
| 2166 | } |
| 2167 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2168 | if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) { |
| 2169 | Value *X = 0; |
| 2170 | if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2171 | return BinaryOperator::CreateSub(SubOne(CRHS), X); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2172 | |
| 2173 | // (X & FF00) + xx00 -> (X+xx00) & FF00 |
| 2174 | if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) { |
| 2175 | Constant *Anded = And(CRHS, C2); |
| 2176 | if (Anded == CRHS) { |
| 2177 | // See if all bits from the first bit set in the Add RHS up are included |
| 2178 | // in the mask. First, get the rightmost bit. |
| 2179 | const APInt& AddRHSV = CRHS->getValue(); |
| 2180 | |
| 2181 | // Form a mask of all bits from the lowest bit added through the top. |
| 2182 | APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1)); |
| 2183 | |
| 2184 | // See if the and mask includes all of these bits. |
| 2185 | APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue()); |
| 2186 | |
| 2187 | if (AddRHSHighBits == AddRHSHighBitsAnd) { |
| 2188 | // Okay, the xform is safe. Insert the new add pronto. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2189 | Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2190 | LHS->getName()), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2191 | return BinaryOperator::CreateAnd(NewAdd, C2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2192 | } |
| 2193 | } |
| 2194 | } |
| 2195 | |
| 2196 | // Try to fold constant add into select arguments. |
| 2197 | if (SelectInst *SI = dyn_cast<SelectInst>(LHS)) |
| 2198 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 2199 | return R; |
| 2200 | } |
| 2201 | |
| 2202 | // add (cast *A to intptrtype) B -> |
Chris Lattner | bf0c5f3 | 2007-12-20 01:56:58 +0000 | [diff] [blame] | 2203 | // cast (GEP (cast *A to sbyte*) B) --> intptrtype |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2204 | { |
| 2205 | CastInst *CI = dyn_cast<CastInst>(LHS); |
| 2206 | Value *Other = RHS; |
| 2207 | if (!CI) { |
| 2208 | CI = dyn_cast<CastInst>(RHS); |
| 2209 | Other = LHS; |
| 2210 | } |
| 2211 | if (CI && CI->getType()->isSized() && |
| 2212 | (CI->getType()->getPrimitiveSizeInBits() == |
| 2213 | TD->getIntPtrType()->getPrimitiveSizeInBits()) |
| 2214 | && isa<PointerType>(CI->getOperand(0)->getType())) { |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 2215 | unsigned AS = |
| 2216 | cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace(); |
Chris Lattner | 13c2d6e | 2008-01-13 22:23:22 +0000 | [diff] [blame] | 2217 | Value *I2 = InsertBitCastBefore(CI->getOperand(0), |
| 2218 | PointerType::get(Type::Int8Ty, AS), I); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 2219 | I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2220 | return new PtrToIntInst(I2, CI->getType()); |
| 2221 | } |
| 2222 | } |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2223 | |
Chris Lattner | bf0c5f3 | 2007-12-20 01:56:58 +0000 | [diff] [blame] | 2224 | // add (select X 0 (sub n A)) A --> select X A n |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2225 | { |
| 2226 | SelectInst *SI = dyn_cast<SelectInst>(LHS); |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 2227 | Value *A = RHS; |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2228 | if (!SI) { |
| 2229 | SI = dyn_cast<SelectInst>(RHS); |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 2230 | A = LHS; |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2231 | } |
Chris Lattner | bf0c5f3 | 2007-12-20 01:56:58 +0000 | [diff] [blame] | 2232 | if (SI && SI->hasOneUse()) { |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2233 | Value *TV = SI->getTrueValue(); |
| 2234 | Value *FV = SI->getFalseValue(); |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 2235 | Value *N; |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2236 | |
| 2237 | // Can we fold the add into the argument of the select? |
| 2238 | // We check both true and false select arguments for a matching subtract. |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 2239 | if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A)))) |
| 2240 | // Fold the add into the true select value. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 2241 | return SelectInst::Create(SI->getCondition(), N, A); |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 2242 | if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A)))) |
| 2243 | // Fold the add into the false select value. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 2244 | return SelectInst::Create(SI->getCondition(), A, N); |
Christopher Lamb | 244ec28 | 2007-12-18 09:34:41 +0000 | [diff] [blame] | 2245 | } |
| 2246 | } |
Chris Lattner | 5547616 | 2008-01-29 06:52:45 +0000 | [diff] [blame] | 2247 | |
| 2248 | // Check for X+0.0. Simplify it to X if we know X is not -0.0. |
| 2249 | if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) |
| 2250 | if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS)) |
| 2251 | return ReplaceInstUsesWith(I, LHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2252 | |
Chris Lattner | 3554f97 | 2008-05-20 05:46:13 +0000 | [diff] [blame] | 2253 | // Check for (add (sext x), y), see if we can merge this into an |
| 2254 | // integer add followed by a sext. |
| 2255 | if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) { |
| 2256 | // (add (sext x), cst) --> (sext (add x, cst')) |
| 2257 | if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) { |
| 2258 | Constant *CI = |
| 2259 | ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType()); |
| 2260 | if (LHSConv->hasOneUse() && |
| 2261 | ConstantExpr::getSExt(CI, I.getType()) == RHSC && |
| 2262 | WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) { |
| 2263 | // Insert the new, smaller add. |
| 2264 | Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), |
| 2265 | CI, "addconv"); |
| 2266 | InsertNewInstBefore(NewAdd, I); |
| 2267 | return new SExtInst(NewAdd, I.getType()); |
| 2268 | } |
| 2269 | } |
| 2270 | |
| 2271 | // (add (sext x), (sext y)) --> (sext (add int x, y)) |
| 2272 | if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) { |
| 2273 | // Only do this if x/y have the same type, if at last one of them has a |
| 2274 | // single use (so we don't increase the number of sexts), and if the |
| 2275 | // integer add will not overflow. |
| 2276 | if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&& |
| 2277 | (LHSConv->hasOneUse() || RHSConv->hasOneUse()) && |
| 2278 | WillNotOverflowSignedAdd(LHSConv->getOperand(0), |
| 2279 | RHSConv->getOperand(0))) { |
| 2280 | // Insert the new integer add. |
| 2281 | Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), |
| 2282 | RHSConv->getOperand(0), |
| 2283 | "addconv"); |
| 2284 | InsertNewInstBefore(NewAdd, I); |
| 2285 | return new SExtInst(NewAdd, I.getType()); |
| 2286 | } |
| 2287 | } |
| 2288 | } |
| 2289 | |
| 2290 | // Check for (add double (sitofp x), y), see if we can merge this into an |
| 2291 | // integer add followed by a promotion. |
| 2292 | if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) { |
| 2293 | // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst)) |
| 2294 | // ... if the constant fits in the integer value. This is useful for things |
| 2295 | // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer |
| 2296 | // requires a constant pool load, and generally allows the add to be better |
| 2297 | // instcombined. |
| 2298 | if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) { |
| 2299 | Constant *CI = |
| 2300 | ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType()); |
| 2301 | if (LHSConv->hasOneUse() && |
| 2302 | ConstantExpr::getSIToFP(CI, I.getType()) == CFP && |
| 2303 | WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) { |
| 2304 | // Insert the new integer add. |
| 2305 | Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), |
| 2306 | CI, "addconv"); |
| 2307 | InsertNewInstBefore(NewAdd, I); |
| 2308 | return new SIToFPInst(NewAdd, I.getType()); |
| 2309 | } |
| 2310 | } |
| 2311 | |
| 2312 | // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y)) |
| 2313 | if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) { |
| 2314 | // Only do this if x/y have the same type, if at last one of them has a |
| 2315 | // single use (so we don't increase the number of int->fp conversions), |
| 2316 | // and if the integer add will not overflow. |
| 2317 | if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&& |
| 2318 | (LHSConv->hasOneUse() || RHSConv->hasOneUse()) && |
| 2319 | WillNotOverflowSignedAdd(LHSConv->getOperand(0), |
| 2320 | RHSConv->getOperand(0))) { |
| 2321 | // Insert the new integer add. |
| 2322 | Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), |
| 2323 | RHSConv->getOperand(0), |
| 2324 | "addconv"); |
| 2325 | InsertNewInstBefore(NewAdd, I); |
| 2326 | return new SIToFPInst(NewAdd, I.getType()); |
| 2327 | } |
| 2328 | } |
| 2329 | } |
| 2330 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2331 | return Changed ? &I : 0; |
| 2332 | } |
| 2333 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2334 | Instruction *InstCombiner::visitSub(BinaryOperator &I) { |
| 2335 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2336 | |
Chris Lattner | 27fbef4 | 2008-07-17 06:07:20 +0000 | [diff] [blame] | 2337 | if (Op0 == Op1 && // sub X, X -> 0 |
| 2338 | !I.getType()->isFPOrFPVector()) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2339 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2340 | |
| 2341 | // If this is a 'B = x-(-A)', change to B = x+A... |
| 2342 | if (Value *V = dyn_castNegVal(Op1)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2343 | return BinaryOperator::CreateAdd(Op0, V); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2344 | |
| 2345 | if (isa<UndefValue>(Op0)) |
| 2346 | return ReplaceInstUsesWith(I, Op0); // undef - X -> undef |
| 2347 | if (isa<UndefValue>(Op1)) |
| 2348 | return ReplaceInstUsesWith(I, Op1); // X - undef -> undef |
| 2349 | |
| 2350 | if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) { |
| 2351 | // Replace (-1 - A) with (~A)... |
| 2352 | if (C->isAllOnesValue()) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2353 | return BinaryOperator::CreateNot(Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2354 | |
| 2355 | // C - ~X == X + (1+C) |
| 2356 | Value *X = 0; |
| 2357 | if (match(Op1, m_Not(m_Value(X)))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2358 | return BinaryOperator::CreateAdd(X, AddOne(C)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2359 | |
| 2360 | // -(X >>u 31) -> (X >>s 31) |
| 2361 | // -(X >>s 31) -> (X >>u 31) |
| 2362 | if (C->isZero()) { |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 2363 | if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2364 | if (SI->getOpcode() == Instruction::LShr) { |
| 2365 | if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) { |
| 2366 | // Check to see if we are shifting out everything but the sign bit. |
| 2367 | if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) == |
| 2368 | SI->getType()->getPrimitiveSizeInBits()-1) { |
| 2369 | // Ok, the transformation is safe. Insert AShr. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2370 | return BinaryOperator::Create(Instruction::AShr, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2371 | SI->getOperand(0), CU, SI->getName()); |
| 2372 | } |
| 2373 | } |
| 2374 | } |
| 2375 | else if (SI->getOpcode() == Instruction::AShr) { |
| 2376 | if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) { |
| 2377 | // Check to see if we are shifting out everything but the sign bit. |
| 2378 | if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) == |
| 2379 | SI->getType()->getPrimitiveSizeInBits()-1) { |
| 2380 | // Ok, the transformation is safe. Insert LShr. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2381 | return BinaryOperator::CreateLShr( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2382 | SI->getOperand(0), CU, SI->getName()); |
| 2383 | } |
| 2384 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 2385 | } |
| 2386 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2387 | } |
| 2388 | |
| 2389 | // Try to fold constant sub into select arguments. |
| 2390 | if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) |
| 2391 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 2392 | return R; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2393 | } |
| 2394 | |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2395 | if (I.getType() == Type::Int1Ty) |
| 2396 | return BinaryOperator::CreateXor(Op0, Op1); |
| 2397 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2398 | if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) { |
| 2399 | if (Op1I->getOpcode() == Instruction::Add && |
| 2400 | !Op0->getType()->isFPOrFPVector()) { |
| 2401 | if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2402 | return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2403 | else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2404 | return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2405 | else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) { |
| 2406 | if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1))) |
| 2407 | // C1-(X+C2) --> (C1-C2)-X |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2408 | return BinaryOperator::CreateSub(Subtract(CI1, CI2), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2409 | Op1I->getOperand(0)); |
| 2410 | } |
| 2411 | } |
| 2412 | |
| 2413 | if (Op1I->hasOneUse()) { |
| 2414 | // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression |
| 2415 | // is not used by anyone else... |
| 2416 | // |
| 2417 | if (Op1I->getOpcode() == Instruction::Sub && |
| 2418 | !Op1I->getType()->isFPOrFPVector()) { |
| 2419 | // Swap the two operands of the subexpr... |
| 2420 | Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1); |
| 2421 | Op1I->setOperand(0, IIOp1); |
| 2422 | Op1I->setOperand(1, IIOp0); |
| 2423 | |
| 2424 | // Create the new top level add instruction... |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2425 | return BinaryOperator::CreateAdd(Op0, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2426 | } |
| 2427 | |
| 2428 | // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)... |
| 2429 | // |
| 2430 | if (Op1I->getOpcode() == Instruction::And && |
| 2431 | (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) { |
| 2432 | Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0); |
| 2433 | |
| 2434 | Value *NewNot = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2435 | InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I); |
| 2436 | return BinaryOperator::CreateAnd(Op0, NewNot); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2437 | } |
| 2438 | |
| 2439 | // 0 - (X sdiv C) -> (X sdiv -C) |
| 2440 | if (Op1I->getOpcode() == Instruction::SDiv) |
| 2441 | if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) |
| 2442 | if (CSI->isZero()) |
| 2443 | if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2444 | return BinaryOperator::CreateSDiv(Op1I->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2445 | ConstantExpr::getNeg(DivRHS)); |
| 2446 | |
| 2447 | // X - X*C --> X * (1-C) |
| 2448 | ConstantInt *C2 = 0; |
| 2449 | if (dyn_castFoldableMul(Op1I, C2) == Op0) { |
| 2450 | Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2451 | return BinaryOperator::CreateMul(Op0, CP1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2452 | } |
| 2453 | } |
| 2454 | } |
| 2455 | |
| 2456 | if (!Op0->getType()->isFPOrFPVector()) |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 2457 | if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2458 | if (Op0I->getOpcode() == Instruction::Add) { |
| 2459 | if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X |
| 2460 | return ReplaceInstUsesWith(I, Op0I->getOperand(1)); |
| 2461 | else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X |
| 2462 | return ReplaceInstUsesWith(I, Op0I->getOperand(0)); |
| 2463 | } else if (Op0I->getOpcode() == Instruction::Sub) { |
| 2464 | if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2465 | return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2466 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 2467 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2468 | |
| 2469 | ConstantInt *C1; |
| 2470 | if (Value *X = dyn_castFoldableMul(Op0, C1)) { |
| 2471 | if (X == Op1) // X*C - X --> X * (C-1) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2472 | return BinaryOperator::CreateMul(Op1, SubOne(C1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2473 | |
| 2474 | ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2) |
| 2475 | if (X == dyn_castFoldableMul(Op1, C2)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2476 | return BinaryOperator::CreateMul(X, Subtract(C1, C2)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2477 | } |
| 2478 | return 0; |
| 2479 | } |
| 2480 | |
| 2481 | /// isSignBitCheck - Given an exploded icmp instruction, return true if the |
| 2482 | /// comparison only checks the sign bit. If it only checks the sign bit, set |
| 2483 | /// TrueIfSigned if the result of the comparison is true when the input value is |
| 2484 | /// signed. |
| 2485 | static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS, |
| 2486 | bool &TrueIfSigned) { |
| 2487 | switch (pred) { |
| 2488 | case ICmpInst::ICMP_SLT: // True if LHS s< 0 |
| 2489 | TrueIfSigned = true; |
| 2490 | return RHS->isZero(); |
| 2491 | case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 |
| 2492 | TrueIfSigned = true; |
| 2493 | return RHS->isAllOnesValue(); |
| 2494 | case ICmpInst::ICMP_SGT: // True if LHS s> -1 |
| 2495 | TrueIfSigned = false; |
| 2496 | return RHS->isAllOnesValue(); |
| 2497 | case ICmpInst::ICMP_UGT: |
| 2498 | // True if LHS u> RHS and RHS == high-bit-mask - 1 |
| 2499 | TrueIfSigned = true; |
| 2500 | return RHS->getValue() == |
| 2501 | APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits()); |
| 2502 | case ICmpInst::ICMP_UGE: |
| 2503 | // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) |
| 2504 | TrueIfSigned = true; |
Chris Lattner | 60813c2 | 2008-06-02 01:29:46 +0000 | [diff] [blame] | 2505 | return RHS->getValue().isSignBit(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2506 | default: |
| 2507 | return false; |
| 2508 | } |
| 2509 | } |
| 2510 | |
| 2511 | Instruction *InstCombiner::visitMul(BinaryOperator &I) { |
| 2512 | bool Changed = SimplifyCommutative(I); |
| 2513 | Value *Op0 = I.getOperand(0); |
| 2514 | |
| 2515 | if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0 |
| 2516 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2517 | |
| 2518 | // Simplify mul instructions with a constant RHS... |
| 2519 | if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) { |
| 2520 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { |
| 2521 | |
| 2522 | // ((X << C1)*C2) == (X * (C2 << C1)) |
| 2523 | if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0)) |
| 2524 | if (SI->getOpcode() == Instruction::Shl) |
| 2525 | if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2526 | return BinaryOperator::CreateMul(SI->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2527 | ConstantExpr::getShl(CI, ShOp)); |
| 2528 | |
| 2529 | if (CI->isZero()) |
| 2530 | return ReplaceInstUsesWith(I, Op1); // X * 0 == 0 |
| 2531 | if (CI->equalsInt(1)) // X * 1 == X |
| 2532 | return ReplaceInstUsesWith(I, Op0); |
| 2533 | if (CI->isAllOnesValue()) // X * -1 == 0 - X |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2534 | return BinaryOperator::CreateNeg(Op0, I.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2535 | |
| 2536 | const APInt& Val = cast<ConstantInt>(CI)->getValue(); |
| 2537 | if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2538 | return BinaryOperator::CreateShl(Op0, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2539 | ConstantInt::get(Op0->getType(), Val.logBase2())); |
| 2540 | } |
| 2541 | } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) { |
| 2542 | if (Op1F->isNullValue()) |
| 2543 | return ReplaceInstUsesWith(I, Op1); |
| 2544 | |
| 2545 | // "In IEEE floating point, x*1 is not equivalent to x for nans. However, |
| 2546 | // ANSI says we can drop signals, so we can do this anyway." (from GCC) |
Chris Lattner | 6297fc7 | 2008-08-11 22:06:05 +0000 | [diff] [blame] | 2547 | if (Op1F->isExactlyValue(1.0)) |
| 2548 | return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0' |
| 2549 | } else if (isa<VectorType>(Op1->getType())) { |
| 2550 | if (isa<ConstantAggregateZero>(Op1)) |
| 2551 | return ReplaceInstUsesWith(I, Op1); |
Nick Lewycky | 9441873 | 2008-11-27 20:21:08 +0000 | [diff] [blame] | 2552 | |
| 2553 | if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) { |
| 2554 | if (Op1V->isAllOnesValue()) // X * -1 == 0 - X |
| 2555 | return BinaryOperator::CreateNeg(Op0, I.getName()); |
| 2556 | |
| 2557 | // As above, vector X*splat(1.0) -> X in all defined cases. |
| 2558 | if (Constant *Splat = Op1V->getSplatValue()) { |
| 2559 | if (ConstantFP *F = dyn_cast<ConstantFP>(Splat)) |
| 2560 | if (F->isExactlyValue(1.0)) |
| 2561 | return ReplaceInstUsesWith(I, Op0); |
| 2562 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat)) |
| 2563 | if (CI->equalsInt(1)) |
| 2564 | return ReplaceInstUsesWith(I, Op0); |
| 2565 | } |
| 2566 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2567 | } |
| 2568 | |
| 2569 | if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) |
| 2570 | if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() && |
Chris Lattner | 5819408 | 2008-05-18 04:11:26 +0000 | [diff] [blame] | 2571 | isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2572 | // Canonicalize (X+C1)*C2 -> X*C2+C1*C2. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2573 | Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2574 | Op1, "tmp"); |
| 2575 | InsertNewInstBefore(Add, I); |
| 2576 | Value *C1C2 = ConstantExpr::getMul(Op1, |
| 2577 | cast<Constant>(Op0I->getOperand(1))); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2578 | return BinaryOperator::CreateAdd(Add, C1C2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2579 | |
| 2580 | } |
| 2581 | |
| 2582 | // Try to fold constant mul into select arguments. |
| 2583 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 2584 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 2585 | return R; |
| 2586 | |
| 2587 | if (isa<PHINode>(Op0)) |
| 2588 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 2589 | return NV; |
| 2590 | } |
| 2591 | |
| 2592 | if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y |
| 2593 | if (Value *Op1v = dyn_castNegVal(I.getOperand(1))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2594 | return BinaryOperator::CreateMul(Op0v, Op1v); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2595 | |
Nick Lewycky | 1c24640 | 2008-11-21 07:33:58 +0000 | [diff] [blame] | 2596 | // (X / Y) * Y = X - (X % Y) |
| 2597 | // (X / Y) * -Y = (X % Y) - X |
| 2598 | { |
| 2599 | Value *Op1 = I.getOperand(1); |
| 2600 | BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0); |
| 2601 | if (!BO || |
| 2602 | (BO->getOpcode() != Instruction::UDiv && |
| 2603 | BO->getOpcode() != Instruction::SDiv)) { |
| 2604 | Op1 = Op0; |
| 2605 | BO = dyn_cast<BinaryOperator>(I.getOperand(1)); |
| 2606 | } |
| 2607 | Value *Neg = dyn_castNegVal(Op1); |
| 2608 | if (BO && BO->hasOneUse() && |
| 2609 | (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) && |
| 2610 | (BO->getOpcode() == Instruction::UDiv || |
| 2611 | BO->getOpcode() == Instruction::SDiv)) { |
| 2612 | Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1); |
| 2613 | |
| 2614 | Instruction *Rem; |
| 2615 | if (BO->getOpcode() == Instruction::UDiv) |
| 2616 | Rem = BinaryOperator::CreateURem(Op0BO, Op1BO); |
| 2617 | else |
| 2618 | Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO); |
| 2619 | |
| 2620 | InsertNewInstBefore(Rem, I); |
| 2621 | Rem->takeName(BO); |
| 2622 | |
| 2623 | if (Op1BO == Op1) |
| 2624 | return BinaryOperator::CreateSub(Op0BO, Rem); |
| 2625 | else |
| 2626 | return BinaryOperator::CreateSub(Rem, Op0BO); |
| 2627 | } |
| 2628 | } |
| 2629 | |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2630 | if (I.getType() == Type::Int1Ty) |
| 2631 | return BinaryOperator::CreateAnd(Op0, I.getOperand(1)); |
| 2632 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2633 | // If one of the operands of the multiply is a cast from a boolean value, then |
| 2634 | // we know the bool is either zero or one, so this is a 'masking' multiply. |
| 2635 | // See if we can simplify things based on how the boolean was originally |
| 2636 | // formed. |
| 2637 | CastInst *BoolCast = 0; |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2638 | if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2639 | if (CI->getOperand(0)->getType() == Type::Int1Ty) |
| 2640 | BoolCast = CI; |
| 2641 | if (!BoolCast) |
| 2642 | if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1))) |
| 2643 | if (CI->getOperand(0)->getType() == Type::Int1Ty) |
| 2644 | BoolCast = CI; |
| 2645 | if (BoolCast) { |
| 2646 | if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) { |
| 2647 | Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1); |
| 2648 | const Type *SCOpTy = SCIOp0->getType(); |
| 2649 | bool TIS = false; |
| 2650 | |
| 2651 | // If the icmp is true iff the sign bit of X is set, then convert this |
| 2652 | // multiply into a shift/and combination. |
| 2653 | if (isa<ConstantInt>(SCIOp1) && |
| 2654 | isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) && |
| 2655 | TIS) { |
| 2656 | // Shift the X value right to turn it into "all signbits". |
| 2657 | Constant *Amt = ConstantInt::get(SCIOp0->getType(), |
| 2658 | SCOpTy->getPrimitiveSizeInBits()-1); |
| 2659 | Value *V = |
| 2660 | InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2661 | BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2662 | BoolCast->getOperand(0)->getName()+ |
| 2663 | ".mask"), I); |
| 2664 | |
| 2665 | // If the multiply type is not the same as the source type, sign extend |
| 2666 | // or truncate to the multiply type. |
| 2667 | if (I.getType() != V->getType()) { |
| 2668 | uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits(); |
| 2669 | uint32_t DstBits = I.getType()->getPrimitiveSizeInBits(); |
| 2670 | Instruction::CastOps opcode = |
| 2671 | (SrcBits == DstBits ? Instruction::BitCast : |
| 2672 | (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc)); |
| 2673 | V = InsertCastBefore(opcode, V, I.getType(), I); |
| 2674 | } |
| 2675 | |
| 2676 | Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0; |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2677 | return BinaryOperator::CreateAnd(V, OtherOp); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2678 | } |
| 2679 | } |
| 2680 | } |
| 2681 | |
| 2682 | return Changed ? &I : 0; |
| 2683 | } |
| 2684 | |
Chris Lattner | 76972db | 2008-07-14 00:15:52 +0000 | [diff] [blame] | 2685 | /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select |
| 2686 | /// instruction. |
| 2687 | bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) { |
| 2688 | SelectInst *SI = cast<SelectInst>(I.getOperand(1)); |
| 2689 | |
| 2690 | // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y |
| 2691 | int NonNullOperand = -1; |
| 2692 | if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1))) |
| 2693 | if (ST->isNullValue()) |
| 2694 | NonNullOperand = 2; |
| 2695 | // div/rem X, (Cond ? Y : 0) -> div/rem X, Y |
| 2696 | if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2))) |
| 2697 | if (ST->isNullValue()) |
| 2698 | NonNullOperand = 1; |
| 2699 | |
| 2700 | if (NonNullOperand == -1) |
| 2701 | return false; |
| 2702 | |
| 2703 | Value *SelectCond = SI->getOperand(0); |
| 2704 | |
| 2705 | // Change the div/rem to use 'Y' instead of the select. |
| 2706 | I.setOperand(1, SI->getOperand(NonNullOperand)); |
| 2707 | |
| 2708 | // Okay, we know we replace the operand of the div/rem with 'Y' with no |
| 2709 | // problem. However, the select, or the condition of the select may have |
| 2710 | // multiple uses. Based on our knowledge that the operand must be non-zero, |
| 2711 | // propagate the known value for the select into other uses of it, and |
| 2712 | // propagate a known value of the condition into its other users. |
| 2713 | |
| 2714 | // If the select and condition only have a single use, don't bother with this, |
| 2715 | // early exit. |
| 2716 | if (SI->use_empty() && SelectCond->hasOneUse()) |
| 2717 | return true; |
| 2718 | |
| 2719 | // Scan the current block backward, looking for other uses of SI. |
| 2720 | BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin(); |
| 2721 | |
| 2722 | while (BBI != BBFront) { |
| 2723 | --BBI; |
| 2724 | // If we found a call to a function, we can't assume it will return, so |
| 2725 | // information from below it cannot be propagated above it. |
| 2726 | if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI)) |
| 2727 | break; |
| 2728 | |
| 2729 | // Replace uses of the select or its condition with the known values. |
| 2730 | for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end(); |
| 2731 | I != E; ++I) { |
| 2732 | if (*I == SI) { |
| 2733 | *I = SI->getOperand(NonNullOperand); |
| 2734 | AddToWorkList(BBI); |
| 2735 | } else if (*I == SelectCond) { |
| 2736 | *I = NonNullOperand == 1 ? ConstantInt::getTrue() : |
| 2737 | ConstantInt::getFalse(); |
| 2738 | AddToWorkList(BBI); |
| 2739 | } |
| 2740 | } |
| 2741 | |
| 2742 | // If we past the instruction, quit looking for it. |
| 2743 | if (&*BBI == SI) |
| 2744 | SI = 0; |
| 2745 | if (&*BBI == SelectCond) |
| 2746 | SelectCond = 0; |
| 2747 | |
| 2748 | // If we ran out of things to eliminate, break out of the loop. |
| 2749 | if (SelectCond == 0 && SI == 0) |
| 2750 | break; |
| 2751 | |
| 2752 | } |
| 2753 | return true; |
| 2754 | } |
| 2755 | |
| 2756 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2757 | /// This function implements the transforms on div instructions that work |
| 2758 | /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is |
| 2759 | /// used by the visitors to those instructions. |
| 2760 | /// @brief Transforms common to all three div instructions |
| 2761 | Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) { |
| 2762 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2763 | |
Chris Lattner | 653ef3c | 2008-02-19 06:12:18 +0000 | [diff] [blame] | 2764 | // undef / X -> 0 for integer. |
| 2765 | // undef / X -> undef for FP (the undef could be a snan). |
| 2766 | if (isa<UndefValue>(Op0)) { |
| 2767 | if (Op0->getType()->isFPOrFPVector()) |
| 2768 | return ReplaceInstUsesWith(I, Op0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2769 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
Chris Lattner | 653ef3c | 2008-02-19 06:12:18 +0000 | [diff] [blame] | 2770 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2771 | |
| 2772 | // X / undef -> undef |
| 2773 | if (isa<UndefValue>(Op1)) |
| 2774 | return ReplaceInstUsesWith(I, Op1); |
| 2775 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2776 | return 0; |
| 2777 | } |
| 2778 | |
| 2779 | /// This function implements the transforms common to both integer division |
| 2780 | /// instructions (udiv and sdiv). It is called by the visitors to those integer |
| 2781 | /// division instructions. |
| 2782 | /// @brief Common integer divide transforms |
| 2783 | Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) { |
| 2784 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2785 | |
Chris Lattner | cefb36c | 2008-05-16 02:59:42 +0000 | [diff] [blame] | 2786 | // (sdiv X, X) --> 1 (udiv X, X) --> 1 |
Nick Lewycky | 386c013 | 2008-05-23 03:26:47 +0000 | [diff] [blame] | 2787 | if (Op0 == Op1) { |
| 2788 | if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) { |
| 2789 | ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1); |
| 2790 | std::vector<Constant*> Elts(Ty->getNumElements(), CI); |
| 2791 | return ReplaceInstUsesWith(I, ConstantVector::get(Elts)); |
| 2792 | } |
| 2793 | |
| 2794 | ConstantInt *CI = ConstantInt::get(I.getType(), 1); |
| 2795 | return ReplaceInstUsesWith(I, CI); |
| 2796 | } |
Chris Lattner | cefb36c | 2008-05-16 02:59:42 +0000 | [diff] [blame] | 2797 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2798 | if (Instruction *Common = commonDivTransforms(I)) |
| 2799 | return Common; |
Chris Lattner | 76972db | 2008-07-14 00:15:52 +0000 | [diff] [blame] | 2800 | |
| 2801 | // Handle cases involving: [su]div X, (select Cond, Y, Z) |
| 2802 | // This does not apply for fdiv. |
| 2803 | if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) |
| 2804 | return &I; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2805 | |
| 2806 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
| 2807 | // div X, 1 == X |
| 2808 | if (RHS->equalsInt(1)) |
| 2809 | return ReplaceInstUsesWith(I, Op0); |
| 2810 | |
| 2811 | // (X / C1) / C2 -> X / (C1*C2) |
| 2812 | if (Instruction *LHS = dyn_cast<Instruction>(Op0)) |
| 2813 | if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode()) |
| 2814 | if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) { |
Nick Lewycky | 9d798f9 | 2008-02-18 22:48:05 +0000 | [diff] [blame] | 2815 | if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv)) |
| 2816 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2817 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2818 | return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0), |
Nick Lewycky | 9d798f9 | 2008-02-18 22:48:05 +0000 | [diff] [blame] | 2819 | Multiply(RHS, LHSRHS)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2820 | } |
| 2821 | |
| 2822 | if (!RHS->isZero()) { // avoid X udiv 0 |
| 2823 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 2824 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 2825 | return R; |
| 2826 | if (isa<PHINode>(Op0)) |
| 2827 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 2828 | return NV; |
| 2829 | } |
| 2830 | } |
| 2831 | |
| 2832 | // 0 / X == 0, we don't need to preserve faults! |
| 2833 | if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0)) |
| 2834 | if (LHS->equalsInt(0)) |
| 2835 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2836 | |
Nick Lewycky | d4b6367 | 2008-05-31 17:59:52 +0000 | [diff] [blame] | 2837 | // It can't be division by zero, hence it must be division by one. |
| 2838 | if (I.getType() == Type::Int1Ty) |
| 2839 | return ReplaceInstUsesWith(I, Op0); |
| 2840 | |
Nick Lewycky | 9441873 | 2008-11-27 20:21:08 +0000 | [diff] [blame] | 2841 | if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) { |
| 2842 | if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue())) |
| 2843 | // div X, 1 == X |
| 2844 | if (X->isOne()) |
| 2845 | return ReplaceInstUsesWith(I, Op0); |
| 2846 | } |
| 2847 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2848 | return 0; |
| 2849 | } |
| 2850 | |
| 2851 | Instruction *InstCombiner::visitUDiv(BinaryOperator &I) { |
| 2852 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2853 | |
| 2854 | // Handle the integer div common cases |
| 2855 | if (Instruction *Common = commonIDivTransforms(I)) |
| 2856 | return Common; |
| 2857 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2858 | if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) { |
Nick Lewycky | 240182a | 2008-11-27 22:41:10 +0000 | [diff] [blame] | 2859 | // X udiv C^2 -> X >> C |
| 2860 | // Check to see if this is an unsigned division with an exact power of 2, |
| 2861 | // if so, convert to a right shift. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2862 | if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2 |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2863 | return BinaryOperator::CreateLShr(Op0, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2864 | ConstantInt::get(Op0->getType(), C->getValue().logBase2())); |
Nick Lewycky | 240182a | 2008-11-27 22:41:10 +0000 | [diff] [blame] | 2865 | |
| 2866 | // X udiv C, where C >= signbit |
| 2867 | if (C->getValue().isNegative()) { |
| 2868 | Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C), |
| 2869 | I); |
| 2870 | return SelectInst::Create(IC, Constant::getNullValue(I.getType()), |
| 2871 | ConstantInt::get(I.getType(), 1)); |
| 2872 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2873 | } |
| 2874 | |
| 2875 | // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2) |
| 2876 | if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) { |
| 2877 | if (RHSI->getOpcode() == Instruction::Shl && |
| 2878 | isa<ConstantInt>(RHSI->getOperand(0))) { |
| 2879 | const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue(); |
| 2880 | if (C1.isPowerOf2()) { |
| 2881 | Value *N = RHSI->getOperand(1); |
| 2882 | const Type *NTy = N->getType(); |
| 2883 | if (uint32_t C2 = C1.logBase2()) { |
| 2884 | Constant *C2V = ConstantInt::get(NTy, C2); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2885 | N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2886 | } |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2887 | return BinaryOperator::CreateLShr(Op0, N); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2888 | } |
| 2889 | } |
| 2890 | } |
| 2891 | |
| 2892 | // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2) |
| 2893 | // where C1&C2 are powers of two. |
| 2894 | if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) |
| 2895 | if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1))) |
| 2896 | if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) { |
| 2897 | const APInt &TVA = STO->getValue(), &FVA = SFO->getValue(); |
| 2898 | if (TVA.isPowerOf2() && FVA.isPowerOf2()) { |
| 2899 | // Compute the shift amounts |
| 2900 | uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2(); |
| 2901 | // Construct the "on true" case of the select |
| 2902 | Constant *TC = ConstantInt::get(Op0->getType(), TSA); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2903 | Instruction *TSI = BinaryOperator::CreateLShr( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2904 | Op0, TC, SI->getName()+".t"); |
| 2905 | TSI = InsertNewInstBefore(TSI, I); |
| 2906 | |
| 2907 | // Construct the "on false" case of the select |
| 2908 | Constant *FC = ConstantInt::get(Op0->getType(), FSA); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2909 | Instruction *FSI = BinaryOperator::CreateLShr( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2910 | Op0, FC, SI->getName()+".f"); |
| 2911 | FSI = InsertNewInstBefore(FSI, I); |
| 2912 | |
| 2913 | // construct the select instruction and return it. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 2914 | return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2915 | } |
| 2916 | } |
| 2917 | return 0; |
| 2918 | } |
| 2919 | |
| 2920 | Instruction *InstCombiner::visitSDiv(BinaryOperator &I) { |
| 2921 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2922 | |
| 2923 | // Handle the integer div common cases |
| 2924 | if (Instruction *Common = commonIDivTransforms(I)) |
| 2925 | return Common; |
| 2926 | |
| 2927 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
| 2928 | // sdiv X, -1 == -X |
| 2929 | if (RHS->isAllOnesValue()) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2930 | return BinaryOperator::CreateNeg(Op0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2931 | } |
| 2932 | |
| 2933 | // If the sign bits of both operands are zero (i.e. we can prove they are |
| 2934 | // unsigned inputs), turn this into a udiv. |
| 2935 | if (I.getType()->isInteger()) { |
| 2936 | APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); |
| 2937 | if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { |
Dan Gohman | db3dd96 | 2007-11-05 23:16:33 +0000 | [diff] [blame] | 2938 | // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 2939 | return BinaryOperator::CreateUDiv(Op0, Op1, I.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2940 | } |
| 2941 | } |
| 2942 | |
| 2943 | return 0; |
| 2944 | } |
| 2945 | |
| 2946 | Instruction *InstCombiner::visitFDiv(BinaryOperator &I) { |
| 2947 | return commonDivTransforms(I); |
| 2948 | } |
| 2949 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2950 | /// This function implements the transforms on rem instructions that work |
| 2951 | /// regardless of the kind of rem instruction it is (urem, srem, or frem). It |
| 2952 | /// is used by the visitors to those instructions. |
| 2953 | /// @brief Transforms common to all three rem instructions |
| 2954 | Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) { |
| 2955 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2956 | |
Chris Lattner | 653ef3c | 2008-02-19 06:12:18 +0000 | [diff] [blame] | 2957 | if (isa<UndefValue>(Op0)) { // undef % X -> 0 |
| 2958 | if (I.getType()->isFPOrFPVector()) |
| 2959 | return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2960 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
Chris Lattner | 653ef3c | 2008-02-19 06:12:18 +0000 | [diff] [blame] | 2961 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2962 | if (isa<UndefValue>(Op1)) |
| 2963 | return ReplaceInstUsesWith(I, Op1); // X % undef -> undef |
| 2964 | |
| 2965 | // Handle cases involving: rem X, (select Cond, Y, Z) |
Chris Lattner | 76972db | 2008-07-14 00:15:52 +0000 | [diff] [blame] | 2966 | if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I)) |
| 2967 | return &I; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2968 | |
| 2969 | return 0; |
| 2970 | } |
| 2971 | |
| 2972 | /// This function implements the transforms common to both integer remainder |
| 2973 | /// instructions (urem and srem). It is called by the visitors to those integer |
| 2974 | /// remainder instructions. |
| 2975 | /// @brief Common integer remainder transforms |
| 2976 | Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) { |
| 2977 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 2978 | |
| 2979 | if (Instruction *common = commonRemTransforms(I)) |
| 2980 | return common; |
| 2981 | |
Dale Johannesen | a51f737 | 2009-01-21 00:35:19 +0000 | [diff] [blame] | 2982 | // 0 % X == 0 for integer, we don't need to preserve faults! |
| 2983 | if (Constant *LHS = dyn_cast<Constant>(Op0)) |
| 2984 | if (LHS->isNullValue()) |
| 2985 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2986 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 2987 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
| 2988 | // X % 0 == undef, we don't need to preserve faults! |
| 2989 | if (RHS->equalsInt(0)) |
| 2990 | return ReplaceInstUsesWith(I, UndefValue::get(I.getType())); |
| 2991 | |
| 2992 | if (RHS->equalsInt(1)) // X % 1 == 0 |
| 2993 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 2994 | |
| 2995 | if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) { |
| 2996 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) { |
| 2997 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 2998 | return R; |
| 2999 | } else if (isa<PHINode>(Op0I)) { |
| 3000 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 3001 | return NV; |
| 3002 | } |
Nick Lewycky | c1372c8 | 2008-03-06 06:48:30 +0000 | [diff] [blame] | 3003 | |
| 3004 | // See if we can fold away this rem instruction. |
| 3005 | uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth(); |
| 3006 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 3007 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth), |
| 3008 | KnownZero, KnownOne)) |
| 3009 | return &I; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3010 | } |
| 3011 | } |
| 3012 | |
| 3013 | return 0; |
| 3014 | } |
| 3015 | |
| 3016 | Instruction *InstCombiner::visitURem(BinaryOperator &I) { |
| 3017 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 3018 | |
| 3019 | if (Instruction *common = commonIRemTransforms(I)) |
| 3020 | return common; |
| 3021 | |
| 3022 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
| 3023 | // X urem C^2 -> X and C |
| 3024 | // Check to see if this is an unsigned remainder with an exact power of 2, |
| 3025 | // if so, convert to a bitwise and. |
| 3026 | if (ConstantInt *C = dyn_cast<ConstantInt>(RHS)) |
| 3027 | if (C->getValue().isPowerOf2()) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3028 | return BinaryOperator::CreateAnd(Op0, SubOne(C)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3029 | } |
| 3030 | |
| 3031 | if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) { |
| 3032 | // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) |
| 3033 | if (RHSI->getOpcode() == Instruction::Shl && |
| 3034 | isa<ConstantInt>(RHSI->getOperand(0))) { |
| 3035 | if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) { |
| 3036 | Constant *N1 = ConstantInt::getAllOnesValue(I.getType()); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3037 | Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3038 | "tmp"), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3039 | return BinaryOperator::CreateAnd(Op0, Add); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3040 | } |
| 3041 | } |
| 3042 | } |
| 3043 | |
| 3044 | // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2) |
| 3045 | // where C1&C2 are powers of two. |
| 3046 | if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) { |
| 3047 | if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1))) |
| 3048 | if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) { |
| 3049 | // STO == 0 and SFO == 0 handled above. |
| 3050 | if ((STO->getValue().isPowerOf2()) && |
| 3051 | (SFO->getValue().isPowerOf2())) { |
| 3052 | Value *TrueAnd = InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3053 | BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3054 | Value *FalseAnd = InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3055 | BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 3056 | return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3057 | } |
| 3058 | } |
| 3059 | } |
| 3060 | |
| 3061 | return 0; |
| 3062 | } |
| 3063 | |
| 3064 | Instruction *InstCombiner::visitSRem(BinaryOperator &I) { |
| 3065 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 3066 | |
Dan Gohman | db3dd96 | 2007-11-05 23:16:33 +0000 | [diff] [blame] | 3067 | // Handle the integer rem common cases |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3068 | if (Instruction *common = commonIRemTransforms(I)) |
| 3069 | return common; |
| 3070 | |
| 3071 | if (Value *RHSNeg = dyn_castNegVal(Op1)) |
Nick Lewycky | cfadfbd | 2008-09-03 06:24:21 +0000 | [diff] [blame] | 3072 | if (!isa<Constant>(RHSNeg) || |
| 3073 | (isa<ConstantInt>(RHSNeg) && |
| 3074 | cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3075 | // X % -Y -> X % Y |
| 3076 | AddUsesToWorkList(I); |
| 3077 | I.setOperand(1, RHSNeg); |
| 3078 | return &I; |
| 3079 | } |
Nick Lewycky | 5515c7a | 2008-09-30 06:08:34 +0000 | [diff] [blame] | 3080 | |
Dan Gohman | db3dd96 | 2007-11-05 23:16:33 +0000 | [diff] [blame] | 3081 | // If the sign bits of both operands are zero (i.e. we can prove they are |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3082 | // unsigned inputs), turn this into a urem. |
Dan Gohman | db3dd96 | 2007-11-05 23:16:33 +0000 | [diff] [blame] | 3083 | if (I.getType()->isInteger()) { |
| 3084 | APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())); |
| 3085 | if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) { |
| 3086 | // X srem Y -> X urem Y, iff X and Y don't have sign bit set |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3087 | return BinaryOperator::CreateURem(Op0, Op1, I.getName()); |
Dan Gohman | db3dd96 | 2007-11-05 23:16:33 +0000 | [diff] [blame] | 3088 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3089 | } |
| 3090 | |
Nick Lewycky | da9fa43 | 2008-12-18 06:31:11 +0000 | [diff] [blame] | 3091 | // If it's a constant vector, flip any negative values positive. |
Nick Lewycky | fd74683 | 2008-12-20 16:48:00 +0000 | [diff] [blame] | 3092 | if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) { |
| 3093 | unsigned VWidth = RHSV->getNumOperands(); |
Nick Lewycky | da9fa43 | 2008-12-18 06:31:11 +0000 | [diff] [blame] | 3094 | |
Nick Lewycky | fd74683 | 2008-12-20 16:48:00 +0000 | [diff] [blame] | 3095 | bool hasNegative = false; |
| 3096 | for (unsigned i = 0; !hasNegative && i != VWidth; ++i) |
| 3097 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) |
| 3098 | if (RHS->getValue().isNegative()) |
| 3099 | hasNegative = true; |
| 3100 | |
| 3101 | if (hasNegative) { |
| 3102 | std::vector<Constant *> Elts(VWidth); |
Nick Lewycky | da9fa43 | 2008-12-18 06:31:11 +0000 | [diff] [blame] | 3103 | for (unsigned i = 0; i != VWidth; ++i) { |
| 3104 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) { |
| 3105 | if (RHS->getValue().isNegative()) |
| 3106 | Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS)); |
| 3107 | else |
| 3108 | Elts[i] = RHS; |
| 3109 | } |
| 3110 | } |
| 3111 | |
| 3112 | Constant *NewRHSV = ConstantVector::get(Elts); |
| 3113 | if (NewRHSV != RHSV) { |
Nick Lewycky | 338ecd5 | 2008-12-18 06:42:28 +0000 | [diff] [blame] | 3114 | AddUsesToWorkList(I); |
Nick Lewycky | da9fa43 | 2008-12-18 06:31:11 +0000 | [diff] [blame] | 3115 | I.setOperand(1, NewRHSV); |
| 3116 | return &I; |
| 3117 | } |
| 3118 | } |
| 3119 | } |
| 3120 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3121 | return 0; |
| 3122 | } |
| 3123 | |
| 3124 | Instruction *InstCombiner::visitFRem(BinaryOperator &I) { |
| 3125 | return commonRemTransforms(I); |
| 3126 | } |
| 3127 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3128 | // isOneBitSet - Return true if there is exactly one bit set in the specified |
| 3129 | // constant. |
| 3130 | static bool isOneBitSet(const ConstantInt *CI) { |
| 3131 | return CI->getValue().isPowerOf2(); |
| 3132 | } |
| 3133 | |
| 3134 | // isHighOnes - Return true if the constant is of the form 1+0+. |
| 3135 | // This is the same as lowones(~X). |
| 3136 | static bool isHighOnes(const ConstantInt *CI) { |
| 3137 | return (~CI->getValue() + 1).isPowerOf2(); |
| 3138 | } |
| 3139 | |
| 3140 | /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits |
| 3141 | /// are carefully arranged to allow folding of expressions such as: |
| 3142 | /// |
| 3143 | /// (A < B) | (A > B) --> (A != B) |
| 3144 | /// |
| 3145 | /// Note that this is only valid if the first and second predicates have the |
| 3146 | /// same sign. Is illegal to do: (A u< B) | (A s> B) |
| 3147 | /// |
| 3148 | /// Three bits are used to represent the condition, as follows: |
| 3149 | /// 0 A > B |
| 3150 | /// 1 A == B |
| 3151 | /// 2 A < B |
| 3152 | /// |
| 3153 | /// <=> Value Definition |
| 3154 | /// 000 0 Always false |
| 3155 | /// 001 1 A > B |
| 3156 | /// 010 2 A == B |
| 3157 | /// 011 3 A >= B |
| 3158 | /// 100 4 A < B |
| 3159 | /// 101 5 A != B |
| 3160 | /// 110 6 A <= B |
| 3161 | /// 111 7 Always true |
| 3162 | /// |
| 3163 | static unsigned getICmpCode(const ICmpInst *ICI) { |
| 3164 | switch (ICI->getPredicate()) { |
| 3165 | // False -> 0 |
| 3166 | case ICmpInst::ICMP_UGT: return 1; // 001 |
| 3167 | case ICmpInst::ICMP_SGT: return 1; // 001 |
| 3168 | case ICmpInst::ICMP_EQ: return 2; // 010 |
| 3169 | case ICmpInst::ICMP_UGE: return 3; // 011 |
| 3170 | case ICmpInst::ICMP_SGE: return 3; // 011 |
| 3171 | case ICmpInst::ICMP_ULT: return 4; // 100 |
| 3172 | case ICmpInst::ICMP_SLT: return 4; // 100 |
| 3173 | case ICmpInst::ICMP_NE: return 5; // 101 |
| 3174 | case ICmpInst::ICMP_ULE: return 6; // 110 |
| 3175 | case ICmpInst::ICMP_SLE: return 6; // 110 |
| 3176 | // True -> 7 |
| 3177 | default: |
| 3178 | assert(0 && "Invalid ICmp predicate!"); |
| 3179 | return 0; |
| 3180 | } |
| 3181 | } |
| 3182 | |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3183 | /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp |
| 3184 | /// predicate into a three bit mask. It also returns whether it is an ordered |
| 3185 | /// predicate by reference. |
| 3186 | static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) { |
| 3187 | isOrdered = false; |
| 3188 | switch (CC) { |
| 3189 | case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000 |
| 3190 | case FCmpInst::FCMP_UNO: return 0; // 000 |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 3191 | case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001 |
| 3192 | case FCmpInst::FCMP_UGT: return 1; // 001 |
| 3193 | case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010 |
| 3194 | case FCmpInst::FCMP_UEQ: return 2; // 010 |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3195 | case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011 |
| 3196 | case FCmpInst::FCMP_UGE: return 3; // 011 |
| 3197 | case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100 |
| 3198 | case FCmpInst::FCMP_ULT: return 4; // 100 |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 3199 | case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101 |
| 3200 | case FCmpInst::FCMP_UNE: return 5; // 101 |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3201 | case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110 |
| 3202 | case FCmpInst::FCMP_ULE: return 6; // 110 |
Evan Cheng | 7298805 | 2008-10-14 18:44:08 +0000 | [diff] [blame] | 3203 | // True -> 7 |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3204 | default: |
| 3205 | // Not expecting FCMP_FALSE and FCMP_TRUE; |
| 3206 | assert(0 && "Unexpected FCmp predicate!"); |
| 3207 | return 0; |
| 3208 | } |
| 3209 | } |
| 3210 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3211 | /// getICmpValue - This is the complement of getICmpCode, which turns an |
| 3212 | /// opcode and two operands into either a constant true or false, or a brand |
Dan Gohman | da33874 | 2007-09-17 17:31:57 +0000 | [diff] [blame] | 3213 | /// new ICmp instruction. The sign is passed in to determine which kind |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3214 | /// of predicate to use in the new icmp instruction. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3215 | static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) { |
| 3216 | switch (code) { |
| 3217 | default: assert(0 && "Illegal ICmp code!"); |
| 3218 | case 0: return ConstantInt::getFalse(); |
| 3219 | case 1: |
| 3220 | if (sign) |
| 3221 | return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS); |
| 3222 | else |
| 3223 | return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS); |
| 3224 | case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS); |
| 3225 | case 3: |
| 3226 | if (sign) |
| 3227 | return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS); |
| 3228 | else |
| 3229 | return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS); |
| 3230 | case 4: |
| 3231 | if (sign) |
| 3232 | return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS); |
| 3233 | else |
| 3234 | return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS); |
| 3235 | case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS); |
| 3236 | case 6: |
| 3237 | if (sign) |
| 3238 | return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS); |
| 3239 | else |
| 3240 | return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS); |
| 3241 | case 7: return ConstantInt::getTrue(); |
| 3242 | } |
| 3243 | } |
| 3244 | |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3245 | /// getFCmpValue - This is the complement of getFCmpCode, which turns an |
| 3246 | /// opcode and two operands into either a FCmp instruction. isordered is passed |
| 3247 | /// in to determine which kind of predicate to use in the new fcmp instruction. |
| 3248 | static Value *getFCmpValue(bool isordered, unsigned code, |
| 3249 | Value *LHS, Value *RHS) { |
| 3250 | switch (code) { |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 3251 | default: assert(0 && "Illegal FCmp code!"); |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3252 | case 0: |
| 3253 | if (isordered) |
| 3254 | return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS); |
| 3255 | else |
| 3256 | return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS); |
| 3257 | case 1: |
| 3258 | if (isordered) |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3259 | return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS); |
| 3260 | else |
| 3261 | return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS); |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 3262 | case 2: |
| 3263 | if (isordered) |
| 3264 | return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS); |
| 3265 | else |
| 3266 | return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS); |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3267 | case 3: |
| 3268 | if (isordered) |
| 3269 | return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS); |
| 3270 | else |
| 3271 | return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS); |
| 3272 | case 4: |
| 3273 | if (isordered) |
| 3274 | return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS); |
| 3275 | else |
| 3276 | return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS); |
| 3277 | case 5: |
| 3278 | if (isordered) |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 3279 | return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS); |
| 3280 | else |
| 3281 | return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS); |
| 3282 | case 6: |
| 3283 | if (isordered) |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3284 | return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS); |
| 3285 | else |
| 3286 | return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS); |
Evan Cheng | 7298805 | 2008-10-14 18:44:08 +0000 | [diff] [blame] | 3287 | case 7: return ConstantInt::getTrue(); |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 3288 | } |
| 3289 | } |
| 3290 | |
Chris Lattner | 2972b82 | 2008-11-16 04:55:20 +0000 | [diff] [blame] | 3291 | /// PredicatesFoldable - Return true if both predicates match sign or if at |
| 3292 | /// least one of them is an equality comparison (which is signless). |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3293 | static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) { |
| 3294 | return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) || |
Chris Lattner | 2972b82 | 2008-11-16 04:55:20 +0000 | [diff] [blame] | 3295 | (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) || |
| 3296 | (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3297 | } |
| 3298 | |
| 3299 | namespace { |
| 3300 | // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B) |
| 3301 | struct FoldICmpLogical { |
| 3302 | InstCombiner &IC; |
| 3303 | Value *LHS, *RHS; |
| 3304 | ICmpInst::Predicate pred; |
| 3305 | FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI) |
| 3306 | : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)), |
| 3307 | pred(ICI->getPredicate()) {} |
| 3308 | bool shouldApply(Value *V) const { |
| 3309 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(V)) |
| 3310 | if (PredicatesFoldable(pred, ICI->getPredicate())) |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 3311 | return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) || |
| 3312 | (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3313 | return false; |
| 3314 | } |
| 3315 | Instruction *apply(Instruction &Log) const { |
| 3316 | ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0)); |
| 3317 | if (ICI->getOperand(0) != LHS) { |
| 3318 | assert(ICI->getOperand(1) == LHS); |
| 3319 | ICI->swapOperands(); // Swap the LHS and RHS of the ICmp |
| 3320 | } |
| 3321 | |
| 3322 | ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1)); |
| 3323 | unsigned LHSCode = getICmpCode(ICI); |
| 3324 | unsigned RHSCode = getICmpCode(RHSICI); |
| 3325 | unsigned Code; |
| 3326 | switch (Log.getOpcode()) { |
| 3327 | case Instruction::And: Code = LHSCode & RHSCode; break; |
| 3328 | case Instruction::Or: Code = LHSCode | RHSCode; break; |
| 3329 | case Instruction::Xor: Code = LHSCode ^ RHSCode; break; |
| 3330 | default: assert(0 && "Illegal logical opcode!"); return 0; |
| 3331 | } |
| 3332 | |
| 3333 | bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || |
| 3334 | ICmpInst::isSignedPredicate(ICI->getPredicate()); |
| 3335 | |
| 3336 | Value *RV = getICmpValue(isSigned, Code, LHS, RHS); |
| 3337 | if (Instruction *I = dyn_cast<Instruction>(RV)) |
| 3338 | return I; |
| 3339 | // Otherwise, it's a constant boolean value... |
| 3340 | return IC.ReplaceInstUsesWith(Log, RV); |
| 3341 | } |
| 3342 | }; |
| 3343 | } // end anonymous namespace |
| 3344 | |
| 3345 | // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where |
| 3346 | // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is |
| 3347 | // guaranteed to be a binary operator. |
| 3348 | Instruction *InstCombiner::OptAndOp(Instruction *Op, |
| 3349 | ConstantInt *OpRHS, |
| 3350 | ConstantInt *AndRHS, |
| 3351 | BinaryOperator &TheAnd) { |
| 3352 | Value *X = Op->getOperand(0); |
| 3353 | Constant *Together = 0; |
| 3354 | if (!Op->isShift()) |
| 3355 | Together = And(AndRHS, OpRHS); |
| 3356 | |
| 3357 | switch (Op->getOpcode()) { |
| 3358 | case Instruction::Xor: |
| 3359 | if (Op->hasOneUse()) { |
| 3360 | // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3361 | Instruction *And = BinaryOperator::CreateAnd(X, AndRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3362 | InsertNewInstBefore(And, TheAnd); |
| 3363 | And->takeName(Op); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3364 | return BinaryOperator::CreateXor(And, Together); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3365 | } |
| 3366 | break; |
| 3367 | case Instruction::Or: |
| 3368 | if (Together == AndRHS) // (X | C) & C --> C |
| 3369 | return ReplaceInstUsesWith(TheAnd, AndRHS); |
| 3370 | |
| 3371 | if (Op->hasOneUse() && Together != OpRHS) { |
| 3372 | // (X | C1) & C2 --> (X | (C1&C2)) & C2 |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3373 | Instruction *Or = BinaryOperator::CreateOr(X, Together); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3374 | InsertNewInstBefore(Or, TheAnd); |
| 3375 | Or->takeName(Op); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3376 | return BinaryOperator::CreateAnd(Or, AndRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3377 | } |
| 3378 | break; |
| 3379 | case Instruction::Add: |
| 3380 | if (Op->hasOneUse()) { |
| 3381 | // Adding a one to a single bit bit-field should be turned into an XOR |
| 3382 | // of the bit. First thing to check is to see if this AND is with a |
| 3383 | // single bit constant. |
| 3384 | const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue(); |
| 3385 | |
| 3386 | // If there is only one bit set... |
| 3387 | if (isOneBitSet(cast<ConstantInt>(AndRHS))) { |
| 3388 | // Ok, at this point, we know that we are masking the result of the |
| 3389 | // ADD down to exactly one bit. If the constant we are adding has |
| 3390 | // no bits set below this bit, then we can eliminate the ADD. |
| 3391 | const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue(); |
| 3392 | |
| 3393 | // Check to see if any bits below the one bit set in AndRHSV are set. |
| 3394 | if ((AddRHS & (AndRHSV-1)) == 0) { |
| 3395 | // If not, the only thing that can effect the output of the AND is |
| 3396 | // the bit specified by AndRHSV. If that bit is set, the effect of |
| 3397 | // the XOR is to toggle the bit. If it is clear, then the ADD has |
| 3398 | // no effect. |
| 3399 | if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop |
| 3400 | TheAnd.setOperand(0, X); |
| 3401 | return &TheAnd; |
| 3402 | } else { |
| 3403 | // Pull the XOR out of the AND. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3404 | Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3405 | InsertNewInstBefore(NewAnd, TheAnd); |
| 3406 | NewAnd->takeName(Op); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3407 | return BinaryOperator::CreateXor(NewAnd, AndRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3408 | } |
| 3409 | } |
| 3410 | } |
| 3411 | } |
| 3412 | break; |
| 3413 | |
| 3414 | case Instruction::Shl: { |
| 3415 | // We know that the AND will not produce any of the bits shifted in, so if |
| 3416 | // the anded constant includes them, clear them now! |
| 3417 | // |
| 3418 | uint32_t BitWidth = AndRHS->getType()->getBitWidth(); |
| 3419 | uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth); |
| 3420 | APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal)); |
| 3421 | ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask); |
| 3422 | |
| 3423 | if (CI->getValue() == ShlMask) { |
| 3424 | // Masking out bits that the shift already masks |
| 3425 | return ReplaceInstUsesWith(TheAnd, Op); // No need for the and. |
| 3426 | } else if (CI != AndRHS) { // Reducing bits set in and. |
| 3427 | TheAnd.setOperand(1, CI); |
| 3428 | return &TheAnd; |
| 3429 | } |
| 3430 | break; |
| 3431 | } |
| 3432 | case Instruction::LShr: |
| 3433 | { |
| 3434 | // We know that the AND will not produce any of the bits shifted in, so if |
| 3435 | // the anded constant includes them, clear them now! This only applies to |
| 3436 | // unsigned shifts, because a signed shr may bring in set bits! |
| 3437 | // |
| 3438 | uint32_t BitWidth = AndRHS->getType()->getBitWidth(); |
| 3439 | uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth); |
| 3440 | APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal)); |
| 3441 | ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask); |
| 3442 | |
| 3443 | if (CI->getValue() == ShrMask) { |
| 3444 | // Masking out bits that the shift already masks. |
| 3445 | return ReplaceInstUsesWith(TheAnd, Op); |
| 3446 | } else if (CI != AndRHS) { |
| 3447 | TheAnd.setOperand(1, CI); // Reduce bits set in and cst. |
| 3448 | return &TheAnd; |
| 3449 | } |
| 3450 | break; |
| 3451 | } |
| 3452 | case Instruction::AShr: |
| 3453 | // Signed shr. |
| 3454 | // See if this is shifting in some sign extension, then masking it out |
| 3455 | // with an and. |
| 3456 | if (Op->hasOneUse()) { |
| 3457 | uint32_t BitWidth = AndRHS->getType()->getBitWidth(); |
| 3458 | uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth); |
| 3459 | APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal)); |
| 3460 | Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask); |
| 3461 | if (C == AndRHS) { // Masking out bits shifted in. |
| 3462 | // (Val ashr C1) & C2 -> (Val lshr C1) & C2 |
| 3463 | // Make the argument unsigned. |
| 3464 | Value *ShVal = Op->getOperand(0); |
| 3465 | ShVal = InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3466 | BinaryOperator::CreateLShr(ShVal, OpRHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3467 | Op->getName()), TheAnd); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3468 | return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3469 | } |
| 3470 | } |
| 3471 | break; |
| 3472 | } |
| 3473 | return 0; |
| 3474 | } |
| 3475 | |
| 3476 | |
| 3477 | /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is |
| 3478 | /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient |
| 3479 | /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates |
| 3480 | /// whether to treat the V, Lo and HI as signed or not. IB is the location to |
| 3481 | /// insert new instructions. |
| 3482 | Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, |
| 3483 | bool isSigned, bool Inside, |
| 3484 | Instruction &IB) { |
| 3485 | assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? |
| 3486 | ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() && |
| 3487 | "Lo is not <= Hi in range emission code!"); |
| 3488 | |
| 3489 | if (Inside) { |
| 3490 | if (Lo == Hi) // Trivially false. |
| 3491 | return new ICmpInst(ICmpInst::ICMP_NE, V, V); |
| 3492 | |
| 3493 | // V >= Min && V < Hi --> V < Hi |
| 3494 | if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) { |
| 3495 | ICmpInst::Predicate pred = (isSigned ? |
| 3496 | ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT); |
| 3497 | return new ICmpInst(pred, V, Hi); |
| 3498 | } |
| 3499 | |
| 3500 | // Emit V-Lo <u Hi-Lo |
| 3501 | Constant *NegLo = ConstantExpr::getNeg(Lo); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3502 | Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3503 | InsertNewInstBefore(Add, IB); |
| 3504 | Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi); |
| 3505 | return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound); |
| 3506 | } |
| 3507 | |
| 3508 | if (Lo == Hi) // Trivially true. |
| 3509 | return new ICmpInst(ICmpInst::ICMP_EQ, V, V); |
| 3510 | |
| 3511 | // V < Min || V >= Hi -> V > Hi-1 |
| 3512 | Hi = SubOne(cast<ConstantInt>(Hi)); |
| 3513 | if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) { |
| 3514 | ICmpInst::Predicate pred = (isSigned ? |
| 3515 | ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT); |
| 3516 | return new ICmpInst(pred, V, Hi); |
| 3517 | } |
| 3518 | |
| 3519 | // Emit V-Lo >u Hi-1-Lo |
| 3520 | // Note that Hi has already had one subtracted from it, above. |
| 3521 | ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3522 | Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3523 | InsertNewInstBefore(Add, IB); |
| 3524 | Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi); |
| 3525 | return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound); |
| 3526 | } |
| 3527 | |
| 3528 | // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with |
| 3529 | // any number of 0s on either side. The 1s are allowed to wrap from LSB to |
| 3530 | // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is |
| 3531 | // not, since all 1s are not contiguous. |
| 3532 | static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) { |
| 3533 | const APInt& V = Val->getValue(); |
| 3534 | uint32_t BitWidth = Val->getType()->getBitWidth(); |
| 3535 | if (!APIntOps::isShiftedMask(BitWidth, V)) return false; |
| 3536 | |
| 3537 | // look for the first zero bit after the run of ones |
| 3538 | MB = BitWidth - ((V - 1) ^ V).countLeadingZeros(); |
| 3539 | // look for the first non-zero bit |
| 3540 | ME = V.getActiveBits(); |
| 3541 | return true; |
| 3542 | } |
| 3543 | |
| 3544 | /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask, |
| 3545 | /// where isSub determines whether the operator is a sub. If we can fold one of |
| 3546 | /// the following xforms: |
| 3547 | /// |
| 3548 | /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask |
| 3549 | /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0 |
| 3550 | /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0 |
| 3551 | /// |
| 3552 | /// return (A +/- B). |
| 3553 | /// |
| 3554 | Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS, |
| 3555 | ConstantInt *Mask, bool isSub, |
| 3556 | Instruction &I) { |
| 3557 | Instruction *LHSI = dyn_cast<Instruction>(LHS); |
| 3558 | if (!LHSI || LHSI->getNumOperands() != 2 || |
| 3559 | !isa<ConstantInt>(LHSI->getOperand(1))) return 0; |
| 3560 | |
| 3561 | ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1)); |
| 3562 | |
| 3563 | switch (LHSI->getOpcode()) { |
| 3564 | default: return 0; |
| 3565 | case Instruction::And: |
| 3566 | if (And(N, Mask) == Mask) { |
| 3567 | // If the AndRHS is a power of two minus one (0+1+), this is simple. |
| 3568 | if ((Mask->getValue().countLeadingZeros() + |
| 3569 | Mask->getValue().countPopulation()) == |
| 3570 | Mask->getValue().getBitWidth()) |
| 3571 | break; |
| 3572 | |
| 3573 | // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+ |
| 3574 | // part, we don't need any explicit masks to take them out of A. If that |
| 3575 | // is all N is, ignore it. |
| 3576 | uint32_t MB = 0, ME = 0; |
| 3577 | if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive |
| 3578 | uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth(); |
| 3579 | APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1)); |
| 3580 | if (MaskedValueIsZero(RHS, Mask)) |
| 3581 | break; |
| 3582 | } |
| 3583 | } |
| 3584 | return 0; |
| 3585 | case Instruction::Or: |
| 3586 | case Instruction::Xor: |
| 3587 | // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0 |
| 3588 | if ((Mask->getValue().countLeadingZeros() + |
| 3589 | Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth() |
| 3590 | && And(N, Mask)->isZero()) |
| 3591 | break; |
| 3592 | return 0; |
| 3593 | } |
| 3594 | |
| 3595 | Instruction *New; |
| 3596 | if (isSub) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3597 | New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3598 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3599 | New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3600 | return InsertNewInstBefore(New, I); |
| 3601 | } |
| 3602 | |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3603 | /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible. |
| 3604 | Instruction *InstCombiner::FoldAndOfICmps(Instruction &I, |
| 3605 | ICmpInst *LHS, ICmpInst *RHS) { |
Chris Lattner | f380348 | 2008-11-16 05:10:52 +0000 | [diff] [blame] | 3606 | Value *Val, *Val2; |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3607 | ConstantInt *LHSCst, *RHSCst; |
| 3608 | ICmpInst::Predicate LHSCC, RHSCC; |
| 3609 | |
Chris Lattner | f380348 | 2008-11-16 05:10:52 +0000 | [diff] [blame] | 3610 | // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2). |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3611 | if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) || |
Chris Lattner | f380348 | 2008-11-16 05:10:52 +0000 | [diff] [blame] | 3612 | !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst)))) |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3613 | return 0; |
Chris Lattner | f380348 | 2008-11-16 05:10:52 +0000 | [diff] [blame] | 3614 | |
| 3615 | // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C) |
| 3616 | // where C is a power of 2 |
| 3617 | if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT && |
| 3618 | LHSCst->getValue().isPowerOf2()) { |
| 3619 | Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2); |
| 3620 | InsertNewInstBefore(NewOr, I); |
| 3621 | return new ICmpInst(LHSCC, NewOr, LHSCst); |
| 3622 | } |
| 3623 | |
| 3624 | // From here on, we only handle: |
| 3625 | // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler. |
| 3626 | if (Val != Val2) return 0; |
| 3627 | |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3628 | // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere. |
| 3629 | if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE || |
| 3630 | RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE || |
| 3631 | LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE || |
| 3632 | RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE) |
| 3633 | return 0; |
| 3634 | |
| 3635 | // We can't fold (ugt x, C) & (sgt x, C2). |
| 3636 | if (!PredicatesFoldable(LHSCC, RHSCC)) |
| 3637 | return 0; |
| 3638 | |
| 3639 | // Ensure that the larger constant is on the RHS. |
Chris Lattner | 665298f | 2008-11-16 05:14:43 +0000 | [diff] [blame] | 3640 | bool ShouldSwap; |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3641 | if (ICmpInst::isSignedPredicate(LHSCC) || |
| 3642 | (ICmpInst::isEquality(LHSCC) && |
| 3643 | ICmpInst::isSignedPredicate(RHSCC))) |
Chris Lattner | 665298f | 2008-11-16 05:14:43 +0000 | [diff] [blame] | 3644 | ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue()); |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3645 | else |
Chris Lattner | 665298f | 2008-11-16 05:14:43 +0000 | [diff] [blame] | 3646 | ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue()); |
| 3647 | |
| 3648 | if (ShouldSwap) { |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3649 | std::swap(LHS, RHS); |
| 3650 | std::swap(LHSCst, RHSCst); |
| 3651 | std::swap(LHSCC, RHSCC); |
| 3652 | } |
| 3653 | |
| 3654 | // At this point, we know we have have two icmp instructions |
| 3655 | // comparing a value against two constants and and'ing the result |
| 3656 | // together. Because of the above check, we know that we only have |
| 3657 | // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know |
| 3658 | // (from the FoldICmpLogical check above), that the two constants |
| 3659 | // are not equal and that the larger constant is on the RHS |
| 3660 | assert(LHSCst != RHSCst && "Compares not folded above?"); |
| 3661 | |
| 3662 | switch (LHSCC) { |
| 3663 | default: assert(0 && "Unknown integer condition code!"); |
| 3664 | case ICmpInst::ICMP_EQ: |
| 3665 | switch (RHSCC) { |
| 3666 | default: assert(0 && "Unknown integer condition code!"); |
| 3667 | case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false |
| 3668 | case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false |
| 3669 | case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false |
| 3670 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 3671 | case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13 |
| 3672 | case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13 |
| 3673 | case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13 |
| 3674 | return ReplaceInstUsesWith(I, LHS); |
| 3675 | } |
| 3676 | case ICmpInst::ICMP_NE: |
| 3677 | switch (RHSCC) { |
| 3678 | default: assert(0 && "Unknown integer condition code!"); |
| 3679 | case ICmpInst::ICMP_ULT: |
| 3680 | if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13 |
| 3681 | return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst); |
| 3682 | break; // (X != 13 & X u< 15) -> no change |
| 3683 | case ICmpInst::ICMP_SLT: |
| 3684 | if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13 |
| 3685 | return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst); |
| 3686 | break; // (X != 13 & X s< 15) -> no change |
| 3687 | case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15 |
| 3688 | case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15 |
| 3689 | case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15 |
| 3690 | return ReplaceInstUsesWith(I, RHS); |
| 3691 | case ICmpInst::ICMP_NE: |
| 3692 | if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1 |
| 3693 | Constant *AddCST = ConstantExpr::getNeg(LHSCst); |
| 3694 | Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST, |
| 3695 | Val->getName()+".off"); |
| 3696 | InsertNewInstBefore(Add, I); |
| 3697 | return new ICmpInst(ICmpInst::ICMP_UGT, Add, |
| 3698 | ConstantInt::get(Add->getType(), 1)); |
| 3699 | } |
| 3700 | break; // (X != 13 & X != 15) -> no change |
| 3701 | } |
| 3702 | break; |
| 3703 | case ICmpInst::ICMP_ULT: |
| 3704 | switch (RHSCC) { |
| 3705 | default: assert(0 && "Unknown integer condition code!"); |
| 3706 | case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false |
| 3707 | case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false |
| 3708 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 3709 | case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change |
| 3710 | break; |
| 3711 | case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13 |
| 3712 | case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13 |
| 3713 | return ReplaceInstUsesWith(I, LHS); |
| 3714 | case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change |
| 3715 | break; |
| 3716 | } |
| 3717 | break; |
| 3718 | case ICmpInst::ICMP_SLT: |
| 3719 | switch (RHSCC) { |
| 3720 | default: assert(0 && "Unknown integer condition code!"); |
| 3721 | case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false |
| 3722 | case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false |
| 3723 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 3724 | case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change |
| 3725 | break; |
| 3726 | case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13 |
| 3727 | case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13 |
| 3728 | return ReplaceInstUsesWith(I, LHS); |
| 3729 | case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change |
| 3730 | break; |
| 3731 | } |
| 3732 | break; |
| 3733 | case ICmpInst::ICMP_UGT: |
| 3734 | switch (RHSCC) { |
| 3735 | default: assert(0 && "Unknown integer condition code!"); |
| 3736 | case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15 |
| 3737 | case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15 |
| 3738 | return ReplaceInstUsesWith(I, RHS); |
| 3739 | case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change |
| 3740 | break; |
| 3741 | case ICmpInst::ICMP_NE: |
| 3742 | if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14 |
| 3743 | return new ICmpInst(LHSCC, Val, RHSCst); |
| 3744 | break; // (X u> 13 & X != 15) -> no change |
Chris Lattner | 0c678e5 | 2008-11-16 05:20:07 +0000 | [diff] [blame] | 3745 | case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1 |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3746 | return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I); |
| 3747 | case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change |
| 3748 | break; |
| 3749 | } |
| 3750 | break; |
| 3751 | case ICmpInst::ICMP_SGT: |
| 3752 | switch (RHSCC) { |
| 3753 | default: assert(0 && "Unknown integer condition code!"); |
| 3754 | case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15 |
| 3755 | case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15 |
| 3756 | return ReplaceInstUsesWith(I, RHS); |
| 3757 | case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change |
| 3758 | break; |
| 3759 | case ICmpInst::ICMP_NE: |
| 3760 | if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14 |
| 3761 | return new ICmpInst(LHSCC, Val, RHSCst); |
| 3762 | break; // (X s> 13 & X != 15) -> no change |
Chris Lattner | 0c678e5 | 2008-11-16 05:20:07 +0000 | [diff] [blame] | 3763 | case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1 |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3764 | return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I); |
| 3765 | case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change |
| 3766 | break; |
| 3767 | } |
| 3768 | break; |
| 3769 | } |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 3770 | |
| 3771 | return 0; |
| 3772 | } |
| 3773 | |
| 3774 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3775 | Instruction *InstCombiner::visitAnd(BinaryOperator &I) { |
| 3776 | bool Changed = SimplifyCommutative(I); |
| 3777 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 3778 | |
| 3779 | if (isa<UndefValue>(Op1)) // X & undef -> 0 |
| 3780 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 3781 | |
| 3782 | // and X, X = X |
| 3783 | if (Op0 == Op1) |
| 3784 | return ReplaceInstUsesWith(I, Op1); |
| 3785 | |
| 3786 | // See if we can simplify any instructions used by the instruction whose sole |
| 3787 | // purpose is to compute bits we don't care about. |
| 3788 | if (!isa<VectorType>(I.getType())) { |
| 3789 | uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth(); |
| 3790 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 3791 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth), |
| 3792 | KnownZero, KnownOne)) |
| 3793 | return &I; |
| 3794 | } else { |
| 3795 | if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) { |
| 3796 | if (CP->isAllOnesValue()) // X & <-1,-1> -> X |
| 3797 | return ReplaceInstUsesWith(I, I.getOperand(0)); |
| 3798 | } else if (isa<ConstantAggregateZero>(Op1)) { |
| 3799 | return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0> |
| 3800 | } |
| 3801 | } |
| 3802 | |
| 3803 | if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) { |
| 3804 | const APInt& AndRHSMask = AndRHS->getValue(); |
| 3805 | APInt NotAndRHS(~AndRHSMask); |
| 3806 | |
| 3807 | // Optimize a variety of ((val OP C1) & C2) combinations... |
| 3808 | if (isa<BinaryOperator>(Op0)) { |
| 3809 | Instruction *Op0I = cast<Instruction>(Op0); |
| 3810 | Value *Op0LHS = Op0I->getOperand(0); |
| 3811 | Value *Op0RHS = Op0I->getOperand(1); |
| 3812 | switch (Op0I->getOpcode()) { |
| 3813 | case Instruction::Xor: |
| 3814 | case Instruction::Or: |
| 3815 | // If the mask is only needed on one incoming arm, push it up. |
| 3816 | if (Op0I->hasOneUse()) { |
| 3817 | if (MaskedValueIsZero(Op0LHS, NotAndRHS)) { |
| 3818 | // Not masking anything out for the LHS, move to RHS. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3819 | Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3820 | Op0RHS->getName()+".masked"); |
| 3821 | InsertNewInstBefore(NewRHS, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3822 | return BinaryOperator::Create( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3823 | cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS); |
| 3824 | } |
| 3825 | if (!isa<Constant>(Op0RHS) && |
| 3826 | MaskedValueIsZero(Op0RHS, NotAndRHS)) { |
| 3827 | // Not masking anything out for the RHS, move to LHS. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3828 | Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3829 | Op0LHS->getName()+".masked"); |
| 3830 | InsertNewInstBefore(NewLHS, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3831 | return BinaryOperator::Create( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3832 | cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS); |
| 3833 | } |
| 3834 | } |
| 3835 | |
| 3836 | break; |
| 3837 | case Instruction::Add: |
| 3838 | // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS. |
| 3839 | // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0 |
| 3840 | // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0 |
| 3841 | if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3842 | return BinaryOperator::CreateAnd(V, AndRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3843 | if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3844 | return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3845 | break; |
| 3846 | |
| 3847 | case Instruction::Sub: |
| 3848 | // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS. |
| 3849 | // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0 |
| 3850 | // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0 |
| 3851 | if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3852 | return BinaryOperator::CreateAnd(V, AndRHS); |
Nick Lewycky | ffed71b | 2008-07-09 04:32:37 +0000 | [diff] [blame] | 3853 | |
Nick Lewycky | a349ba4 | 2008-07-10 05:51:40 +0000 | [diff] [blame] | 3854 | // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS |
| 3855 | // has 1's for all bits that the subtraction with A might affect. |
| 3856 | if (Op0I->hasOneUse()) { |
| 3857 | uint32_t BitWidth = AndRHSMask.getBitWidth(); |
| 3858 | uint32_t Zeros = AndRHSMask.countLeadingZeros(); |
| 3859 | APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros); |
| 3860 | |
Nick Lewycky | ffed71b | 2008-07-09 04:32:37 +0000 | [diff] [blame] | 3861 | ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS); |
Nick Lewycky | a349ba4 | 2008-07-10 05:51:40 +0000 | [diff] [blame] | 3862 | if (!(A && A->isZero()) && // avoid infinite recursion. |
| 3863 | MaskedValueIsZero(Op0LHS, Mask)) { |
Nick Lewycky | ffed71b | 2008-07-09 04:32:37 +0000 | [diff] [blame] | 3864 | Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS); |
| 3865 | InsertNewInstBefore(NewNeg, I); |
| 3866 | return BinaryOperator::CreateAnd(NewNeg, AndRHS); |
| 3867 | } |
| 3868 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3869 | break; |
Nick Lewycky | 659ed4d | 2008-07-09 05:20:13 +0000 | [diff] [blame] | 3870 | |
| 3871 | case Instruction::Shl: |
| 3872 | case Instruction::LShr: |
| 3873 | // (1 << x) & 1 --> zext(x == 0) |
| 3874 | // (1 >> x) & 1 --> zext(x == 0) |
Nick Lewycky | f1b1222 | 2008-07-09 07:35:26 +0000 | [diff] [blame] | 3875 | if (AndRHSMask == 1 && Op0LHS == AndRHS) { |
Nick Lewycky | 659ed4d | 2008-07-09 05:20:13 +0000 | [diff] [blame] | 3876 | Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS, |
| 3877 | Constant::getNullValue(I.getType())); |
| 3878 | InsertNewInstBefore(NewICmp, I); |
| 3879 | return new ZExtInst(NewICmp, I.getType()); |
| 3880 | } |
| 3881 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3882 | } |
| 3883 | |
| 3884 | if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) |
| 3885 | if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I)) |
| 3886 | return Res; |
| 3887 | } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) { |
| 3888 | // If this is an integer truncation or change from signed-to-unsigned, and |
| 3889 | // if the source is an and/or with immediate, transform it. This |
| 3890 | // frequently occurs for bitfield accesses. |
| 3891 | if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) { |
| 3892 | if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) && |
| 3893 | CastOp->getNumOperands() == 2) |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 3894 | if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3895 | if (CastOp->getOpcode() == Instruction::And) { |
| 3896 | // Change: and (cast (and X, C1) to T), C2 |
| 3897 | // into : and (cast X to T), trunc_or_bitcast(C1)&C2 |
| 3898 | // This will fold the two constants together, which may allow |
| 3899 | // other simplifications. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3900 | Instruction *NewCast = CastInst::CreateTruncOrBitCast( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3901 | CastOp->getOperand(0), I.getType(), |
| 3902 | CastOp->getName()+".shrunk"); |
| 3903 | NewCast = InsertNewInstBefore(NewCast, I); |
| 3904 | // trunc_or_bitcast(C1)&C2 |
| 3905 | Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType()); |
| 3906 | C3 = ConstantExpr::getAnd(C3, AndRHS); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3907 | return BinaryOperator::CreateAnd(NewCast, C3); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3908 | } else if (CastOp->getOpcode() == Instruction::Or) { |
| 3909 | // Change: and (cast (or X, C1) to T), C2 |
| 3910 | // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2 |
| 3911 | Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType()); |
| 3912 | if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2 |
| 3913 | return ReplaceInstUsesWith(I, AndRHS); |
| 3914 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 3915 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3916 | } |
| 3917 | } |
| 3918 | |
| 3919 | // Try to fold constant and into select arguments. |
| 3920 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 3921 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 3922 | return R; |
| 3923 | if (isa<PHINode>(Op0)) |
| 3924 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 3925 | return NV; |
| 3926 | } |
| 3927 | |
| 3928 | Value *Op0NotVal = dyn_castNotVal(Op0); |
| 3929 | Value *Op1NotVal = dyn_castNotVal(Op1); |
| 3930 | |
| 3931 | if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0 |
| 3932 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 3933 | |
| 3934 | // (~A & ~B) == (~(A | B)) - De Morgan's Law |
| 3935 | if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3936 | Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3937 | I.getName()+".demorgan"); |
| 3938 | InsertNewInstBefore(Or, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3939 | return BinaryOperator::CreateNot(Or); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3940 | } |
| 3941 | |
| 3942 | { |
| 3943 | Value *A = 0, *B = 0, *C = 0, *D = 0; |
| 3944 | if (match(Op0, m_Or(m_Value(A), m_Value(B)))) { |
| 3945 | if (A == Op1 || B == Op1) // (A | ?) & A --> A |
| 3946 | return ReplaceInstUsesWith(I, Op1); |
| 3947 | |
| 3948 | // (A|B) & ~(A&B) -> A^B |
| 3949 | if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) { |
| 3950 | if ((A == C && B == D) || (A == D && B == C)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3951 | return BinaryOperator::CreateXor(A, B); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3952 | } |
| 3953 | } |
| 3954 | |
| 3955 | if (match(Op1, m_Or(m_Value(A), m_Value(B)))) { |
| 3956 | if (A == Op0 || B == Op0) // A & (A | ?) --> A |
| 3957 | return ReplaceInstUsesWith(I, Op0); |
| 3958 | |
| 3959 | // ~(A&B) & (A|B) -> A^B |
| 3960 | if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) { |
| 3961 | if ((A == C && B == D) || (A == D && B == C)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3962 | return BinaryOperator::CreateXor(A, B); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3963 | } |
| 3964 | } |
| 3965 | |
| 3966 | if (Op0->hasOneUse() && |
| 3967 | match(Op0, m_Xor(m_Value(A), m_Value(B)))) { |
| 3968 | if (A == Op1) { // (A^B)&A -> A&(A^B) |
| 3969 | I.swapOperands(); // Simplify below |
| 3970 | std::swap(Op0, Op1); |
| 3971 | } else if (B == Op1) { // (A^B)&B -> B&(B^A) |
| 3972 | cast<BinaryOperator>(Op0)->swapOperands(); |
| 3973 | I.swapOperands(); // Simplify below |
| 3974 | std::swap(Op0, Op1); |
| 3975 | } |
| 3976 | } |
Bill Wendling | ce5e0af | 2008-11-30 13:08:13 +0000 | [diff] [blame] | 3977 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3978 | if (Op1->hasOneUse() && |
| 3979 | match(Op1, m_Xor(m_Value(A), m_Value(B)))) { |
| 3980 | if (B == Op0) { // B&(A^B) -> B&(B^A) |
| 3981 | cast<BinaryOperator>(Op1)->swapOperands(); |
| 3982 | std::swap(A, B); |
| 3983 | } |
| 3984 | if (A == Op0) { // A&(A^B) -> A & ~B |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3985 | Instruction *NotB = BinaryOperator::CreateNot(B, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3986 | InsertNewInstBefore(NotB, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 3987 | return BinaryOperator::CreateAnd(A, NotB); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3988 | } |
| 3989 | } |
Bill Wendling | ce5e0af | 2008-11-30 13:08:13 +0000 | [diff] [blame] | 3990 | |
| 3991 | // (A&((~A)|B)) -> A&B |
Chris Lattner | 9db479f | 2008-12-01 05:16:26 +0000 | [diff] [blame] | 3992 | if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) || |
| 3993 | match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))))) |
| 3994 | return BinaryOperator::CreateAnd(A, Op1); |
| 3995 | if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) || |
| 3996 | match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))))) |
| 3997 | return BinaryOperator::CreateAnd(A, Op0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 3998 | } |
| 3999 | |
| 4000 | if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) { |
| 4001 | // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B) |
| 4002 | if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS))) |
| 4003 | return R; |
| 4004 | |
Chris Lattner | 0631ea7 | 2008-11-16 05:06:21 +0000 | [diff] [blame] | 4005 | if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0)) |
| 4006 | if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS)) |
| 4007 | return Res; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4008 | } |
| 4009 | |
| 4010 | // fold (and (cast A), (cast B)) -> (cast (and A, B)) |
| 4011 | if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) |
| 4012 | if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) |
| 4013 | if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ? |
| 4014 | const Type *SrcTy = Op0C->getOperand(0)->getType(); |
| 4015 | if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() && |
| 4016 | // Only do this if the casts both really cause code to be generated. |
| 4017 | ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), |
| 4018 | I.getType(), TD) && |
| 4019 | ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), |
| 4020 | I.getType(), TD)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4021 | Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4022 | Op1C->getOperand(0), |
| 4023 | I.getName()); |
| 4024 | InsertNewInstBefore(NewOp, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4025 | return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4026 | } |
| 4027 | } |
| 4028 | |
| 4029 | // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts. |
| 4030 | if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) { |
| 4031 | if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0)) |
| 4032 | if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && |
| 4033 | SI0->getOperand(1) == SI1->getOperand(1) && |
| 4034 | (SI0->hasOneUse() || SI1->hasOneUse())) { |
| 4035 | Instruction *NewOp = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4036 | InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4037 | SI1->getOperand(0), |
| 4038 | SI0->getName()), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4039 | return BinaryOperator::Create(SI1->getOpcode(), NewOp, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4040 | SI1->getOperand(1)); |
| 4041 | } |
| 4042 | } |
| 4043 | |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 4044 | // If and'ing two fcmp, try combine them into one. |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4045 | if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) { |
| 4046 | if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) { |
| 4047 | if (LHS->getPredicate() == FCmpInst::FCMP_ORD && |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 4048 | RHS->getPredicate() == FCmpInst::FCMP_ORD) { |
| 4049 | // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y) |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4050 | if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1))) |
| 4051 | if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) { |
| 4052 | // If either of the constants are nans, then the whole thing returns |
| 4053 | // false. |
Chris Lattner | a6c7dce | 2007-10-24 18:54:45 +0000 | [diff] [blame] | 4054 | if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN()) |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4055 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 4056 | return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0), |
| 4057 | RHS->getOperand(0)); |
| 4058 | } |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 4059 | } else { |
| 4060 | Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS; |
| 4061 | FCmpInst::Predicate Op0CC, Op1CC; |
| 4062 | if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) && |
| 4063 | match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) { |
Evan Cheng | f1f2cea | 2008-10-14 18:13:38 +0000 | [diff] [blame] | 4064 | if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) { |
| 4065 | // Swap RHS operands to match LHS. |
| 4066 | Op1CC = FCmpInst::getSwappedPredicate(Op1CC); |
| 4067 | std::swap(Op1LHS, Op1RHS); |
| 4068 | } |
Evan Cheng | 0ac3a4d | 2008-10-14 17:15:11 +0000 | [diff] [blame] | 4069 | if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) { |
| 4070 | // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y). |
| 4071 | if (Op0CC == Op1CC) |
| 4072 | return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS); |
| 4073 | else if (Op0CC == FCmpInst::FCMP_FALSE || |
| 4074 | Op1CC == FCmpInst::FCMP_FALSE) |
| 4075 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 4076 | else if (Op0CC == FCmpInst::FCMP_TRUE) |
| 4077 | return ReplaceInstUsesWith(I, Op1); |
| 4078 | else if (Op1CC == FCmpInst::FCMP_TRUE) |
| 4079 | return ReplaceInstUsesWith(I, Op0); |
| 4080 | bool Op0Ordered; |
| 4081 | bool Op1Ordered; |
| 4082 | unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered); |
| 4083 | unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered); |
| 4084 | if (Op1Pred == 0) { |
| 4085 | std::swap(Op0, Op1); |
| 4086 | std::swap(Op0Pred, Op1Pred); |
| 4087 | std::swap(Op0Ordered, Op1Ordered); |
| 4088 | } |
| 4089 | if (Op0Pred == 0) { |
| 4090 | // uno && ueq -> uno && (uno || eq) -> ueq |
| 4091 | // ord && olt -> ord && (ord && lt) -> olt |
| 4092 | if (Op0Ordered == Op1Ordered) |
| 4093 | return ReplaceInstUsesWith(I, Op1); |
| 4094 | // uno && oeq -> uno && (ord && eq) -> false |
| 4095 | // uno && ord -> false |
| 4096 | if (!Op0Ordered) |
| 4097 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 4098 | // ord && ueq -> ord && (uno || eq) -> oeq |
| 4099 | return cast<Instruction>(getFCmpValue(true, Op1Pred, |
| 4100 | Op0LHS, Op0RHS)); |
| 4101 | } |
| 4102 | } |
| 4103 | } |
| 4104 | } |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4105 | } |
| 4106 | } |
Nick Lewycky | ffed71b | 2008-07-09 04:32:37 +0000 | [diff] [blame] | 4107 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4108 | return Changed ? &I : 0; |
| 4109 | } |
| 4110 | |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4111 | /// CollectBSwapParts - Analyze the specified subexpression and see if it is |
| 4112 | /// capable of providing pieces of a bswap. The subexpression provides pieces |
| 4113 | /// of a bswap if it is proven that each of the non-zero bytes in the output of |
| 4114 | /// the expression came from the corresponding "byte swapped" byte in some other |
| 4115 | /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then |
| 4116 | /// we know that the expression deposits the low byte of %X into the high byte |
| 4117 | /// of the bswap result and that all other bytes are zero. This expression is |
| 4118 | /// accepted, the high byte of ByteValues is set to X to indicate a correct |
| 4119 | /// match. |
| 4120 | /// |
| 4121 | /// This function returns true if the match was unsuccessful and false if so. |
| 4122 | /// On entry to the function the "OverallLeftShift" is a signed integer value |
| 4123 | /// indicating the number of bytes that the subexpression is later shifted. For |
| 4124 | /// example, if the expression is later right shifted by 16 bits, the |
| 4125 | /// OverallLeftShift value would be -2 on entry. This is used to specify which |
| 4126 | /// byte of ByteValues is actually being set. |
| 4127 | /// |
| 4128 | /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding |
| 4129 | /// byte is masked to zero by a user. For example, in (X & 255), X will be |
| 4130 | /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits |
| 4131 | /// this function to working on up to 32-byte (256 bit) values. ByteMask is |
| 4132 | /// always in the local (OverallLeftShift) coordinate space. |
| 4133 | /// |
| 4134 | static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask, |
| 4135 | SmallVector<Value*, 8> &ByteValues) { |
| 4136 | if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 4137 | // If this is an or instruction, it may be an inner node of the bswap. |
| 4138 | if (I->getOpcode() == Instruction::Or) { |
| 4139 | return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, |
| 4140 | ByteValues) || |
| 4141 | CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask, |
| 4142 | ByteValues); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4143 | } |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4144 | |
| 4145 | // If this is a logical shift by a constant multiple of 8, recurse with |
| 4146 | // OverallLeftShift and ByteMask adjusted. |
| 4147 | if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) { |
| 4148 | unsigned ShAmt = |
| 4149 | cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U); |
| 4150 | // Ensure the shift amount is defined and of a byte value. |
| 4151 | if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size())) |
| 4152 | return true; |
| 4153 | |
| 4154 | unsigned ByteShift = ShAmt >> 3; |
| 4155 | if (I->getOpcode() == Instruction::Shl) { |
| 4156 | // X << 2 -> collect(X, +2) |
| 4157 | OverallLeftShift += ByteShift; |
| 4158 | ByteMask >>= ByteShift; |
| 4159 | } else { |
| 4160 | // X >>u 2 -> collect(X, -2) |
| 4161 | OverallLeftShift -= ByteShift; |
| 4162 | ByteMask <<= ByteShift; |
Chris Lattner | 4444859 | 2008-10-08 06:42:28 +0000 | [diff] [blame] | 4163 | ByteMask &= (~0U >> (32-ByteValues.size())); |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4164 | } |
| 4165 | |
| 4166 | if (OverallLeftShift >= (int)ByteValues.size()) return true; |
| 4167 | if (OverallLeftShift <= -(int)ByteValues.size()) return true; |
| 4168 | |
| 4169 | return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, |
| 4170 | ByteValues); |
| 4171 | } |
| 4172 | |
| 4173 | // If this is a logical 'and' with a mask that clears bytes, clear the |
| 4174 | // corresponding bytes in ByteMask. |
| 4175 | if (I->getOpcode() == Instruction::And && |
| 4176 | isa<ConstantInt>(I->getOperand(1))) { |
| 4177 | // Scan every byte of the and mask, seeing if the byte is either 0 or 255. |
| 4178 | unsigned NumBytes = ByteValues.size(); |
| 4179 | APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255); |
| 4180 | const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue(); |
| 4181 | |
| 4182 | for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) { |
| 4183 | // If this byte is masked out by a later operation, we don't care what |
| 4184 | // the and mask is. |
| 4185 | if ((ByteMask & (1 << i)) == 0) |
| 4186 | continue; |
| 4187 | |
| 4188 | // If the AndMask is all zeros for this byte, clear the bit. |
| 4189 | APInt MaskB = AndMask & Byte; |
| 4190 | if (MaskB == 0) { |
| 4191 | ByteMask &= ~(1U << i); |
| 4192 | continue; |
| 4193 | } |
| 4194 | |
| 4195 | // If the AndMask is not all ones for this byte, it's not a bytezap. |
| 4196 | if (MaskB != Byte) |
| 4197 | return true; |
| 4198 | |
| 4199 | // Otherwise, this byte is kept. |
| 4200 | } |
| 4201 | |
| 4202 | return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, |
| 4203 | ByteValues); |
| 4204 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4205 | } |
| 4206 | |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4207 | // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be |
| 4208 | // the input value to the bswap. Some observations: 1) if more than one byte |
| 4209 | // is demanded from this input, then it could not be successfully assembled |
| 4210 | // into a byteswap. At least one of the two bytes would not be aligned with |
| 4211 | // their ultimate destination. |
| 4212 | if (!isPowerOf2_32(ByteMask)) return true; |
| 4213 | unsigned InputByteNo = CountTrailingZeros_32(ByteMask); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4214 | |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4215 | // 2) The input and ultimate destinations must line up: if byte 3 of an i32 |
| 4216 | // is demanded, it needs to go into byte 0 of the result. This means that the |
| 4217 | // byte needs to be shifted until it lands in the right byte bucket. The |
| 4218 | // shift amount depends on the position: if the byte is coming from the high |
| 4219 | // part of the value (e.g. byte 3) then it must be shifted right. If from the |
| 4220 | // low part, it must be shifted left. |
| 4221 | unsigned DestByteNo = InputByteNo + OverallLeftShift; |
| 4222 | if (InputByteNo < ByteValues.size()/2) { |
| 4223 | if (ByteValues.size()-1-DestByteNo != InputByteNo) |
| 4224 | return true; |
| 4225 | } else { |
| 4226 | if (ByteValues.size()-1-DestByteNo != InputByteNo) |
| 4227 | return true; |
| 4228 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4229 | |
| 4230 | // If the destination byte value is already defined, the values are or'd |
| 4231 | // together, which isn't a bswap (unless it's an or of the same bits). |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4232 | if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4233 | return true; |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4234 | ByteValues[DestByteNo] = V; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4235 | return false; |
| 4236 | } |
| 4237 | |
| 4238 | /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom. |
| 4239 | /// If so, insert the new bswap intrinsic and return it. |
| 4240 | Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) { |
| 4241 | const IntegerType *ITy = dyn_cast<IntegerType>(I.getType()); |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4242 | if (!ITy || ITy->getBitWidth() % 16 || |
| 4243 | // ByteMask only allows up to 32-byte values. |
| 4244 | ITy->getBitWidth() > 32*8) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4245 | return 0; // Can only bswap pairs of bytes. Can't do vectors. |
| 4246 | |
| 4247 | /// ByteValues - For each byte of the result, we keep track of which value |
| 4248 | /// defines each byte. |
| 4249 | SmallVector<Value*, 8> ByteValues; |
| 4250 | ByteValues.resize(ITy->getBitWidth()/8); |
| 4251 | |
| 4252 | // Try to find all the pieces corresponding to the bswap. |
Chris Lattner | 567f511 | 2008-10-05 02:13:19 +0000 | [diff] [blame] | 4253 | uint32_t ByteMask = ~0U >> (32-ByteValues.size()); |
| 4254 | if (CollectBSwapParts(&I, 0, ByteMask, ByteValues)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4255 | return 0; |
| 4256 | |
| 4257 | // Check to see if all of the bytes come from the same value. |
| 4258 | Value *V = ByteValues[0]; |
| 4259 | if (V == 0) return 0; // Didn't find a byte? Must be zero. |
| 4260 | |
| 4261 | // Check to make sure that all of the bytes come from the same value. |
| 4262 | for (unsigned i = 1, e = ByteValues.size(); i != e; ++i) |
| 4263 | if (ByteValues[i] != V) |
| 4264 | return 0; |
Chandler Carruth | a228e39 | 2007-08-04 01:51:18 +0000 | [diff] [blame] | 4265 | const Type *Tys[] = { ITy }; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4266 | Module *M = I.getParent()->getParent()->getParent(); |
Chandler Carruth | a228e39 | 2007-08-04 01:51:18 +0000 | [diff] [blame] | 4267 | Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 4268 | return CallInst::Create(F, V); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4269 | } |
| 4270 | |
Chris Lattner | dd7772b | 2008-11-16 04:24:12 +0000 | [diff] [blame] | 4271 | /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check |
| 4272 | /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then |
| 4273 | /// we can simplify this expression to "cond ? C : D or B". |
| 4274 | static Instruction *MatchSelectFromAndOr(Value *A, Value *B, |
| 4275 | Value *C, Value *D) { |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4276 | // If A is not a select of -1/0, this cannot match. |
Chris Lattner | 641ea46 | 2008-11-16 04:46:19 +0000 | [diff] [blame] | 4277 | Value *Cond = 0; |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 4278 | if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)))) |
Chris Lattner | dd7772b | 2008-11-16 04:24:12 +0000 | [diff] [blame] | 4279 | return 0; |
| 4280 | |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4281 | // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B. |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 4282 | if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)))) |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4283 | return SelectInst::Create(Cond, C, B); |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 4284 | if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))))) |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4285 | return SelectInst::Create(Cond, C, B); |
| 4286 | // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D. |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 4287 | if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)))) |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4288 | return SelectInst::Create(Cond, C, D); |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 4289 | if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))))) |
Chris Lattner | d09b5ba | 2008-11-16 04:26:55 +0000 | [diff] [blame] | 4290 | return SelectInst::Create(Cond, C, D); |
Chris Lattner | dd7772b | 2008-11-16 04:24:12 +0000 | [diff] [blame] | 4291 | return 0; |
| 4292 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4293 | |
Chris Lattner | 0c678e5 | 2008-11-16 05:20:07 +0000 | [diff] [blame] | 4294 | /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible. |
| 4295 | Instruction *InstCombiner::FoldOrOfICmps(Instruction &I, |
| 4296 | ICmpInst *LHS, ICmpInst *RHS) { |
| 4297 | Value *Val, *Val2; |
| 4298 | ConstantInt *LHSCst, *RHSCst; |
| 4299 | ICmpInst::Predicate LHSCC, RHSCC; |
| 4300 | |
| 4301 | // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2). |
| 4302 | if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) || |
| 4303 | !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst)))) |
| 4304 | return 0; |
| 4305 | |
| 4306 | // From here on, we only handle: |
| 4307 | // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler. |
| 4308 | if (Val != Val2) return 0; |
| 4309 | |
| 4310 | // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere. |
| 4311 | if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE || |
| 4312 | RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE || |
| 4313 | LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE || |
| 4314 | RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE) |
| 4315 | return 0; |
| 4316 | |
| 4317 | // We can't fold (ugt x, C) | (sgt x, C2). |
| 4318 | if (!PredicatesFoldable(LHSCC, RHSCC)) |
| 4319 | return 0; |
| 4320 | |
| 4321 | // Ensure that the larger constant is on the RHS. |
| 4322 | bool ShouldSwap; |
| 4323 | if (ICmpInst::isSignedPredicate(LHSCC) || |
| 4324 | (ICmpInst::isEquality(LHSCC) && |
| 4325 | ICmpInst::isSignedPredicate(RHSCC))) |
| 4326 | ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue()); |
| 4327 | else |
| 4328 | ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue()); |
| 4329 | |
| 4330 | if (ShouldSwap) { |
| 4331 | std::swap(LHS, RHS); |
| 4332 | std::swap(LHSCst, RHSCst); |
| 4333 | std::swap(LHSCC, RHSCC); |
| 4334 | } |
| 4335 | |
| 4336 | // At this point, we know we have have two icmp instructions |
| 4337 | // comparing a value against two constants and or'ing the result |
| 4338 | // together. Because of the above check, we know that we only have |
| 4339 | // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the |
| 4340 | // FoldICmpLogical check above), that the two constants are not |
| 4341 | // equal. |
| 4342 | assert(LHSCst != RHSCst && "Compares not folded above?"); |
| 4343 | |
| 4344 | switch (LHSCC) { |
| 4345 | default: assert(0 && "Unknown integer condition code!"); |
| 4346 | case ICmpInst::ICMP_EQ: |
| 4347 | switch (RHSCC) { |
| 4348 | default: assert(0 && "Unknown integer condition code!"); |
| 4349 | case ICmpInst::ICMP_EQ: |
| 4350 | if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2 |
| 4351 | Constant *AddCST = ConstantExpr::getNeg(LHSCst); |
| 4352 | Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST, |
| 4353 | Val->getName()+".off"); |
| 4354 | InsertNewInstBefore(Add, I); |
| 4355 | AddCST = Subtract(AddOne(RHSCst), LHSCst); |
| 4356 | return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST); |
| 4357 | } |
| 4358 | break; // (X == 13 | X == 15) -> no change |
| 4359 | case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change |
| 4360 | case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change |
| 4361 | break; |
| 4362 | case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15 |
| 4363 | case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15 |
| 4364 | case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15 |
| 4365 | return ReplaceInstUsesWith(I, RHS); |
| 4366 | } |
| 4367 | break; |
| 4368 | case ICmpInst::ICMP_NE: |
| 4369 | switch (RHSCC) { |
| 4370 | default: assert(0 && "Unknown integer condition code!"); |
| 4371 | case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13 |
| 4372 | case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13 |
| 4373 | case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13 |
| 4374 | return ReplaceInstUsesWith(I, LHS); |
| 4375 | case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true |
| 4376 | case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true |
| 4377 | case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true |
| 4378 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 4379 | } |
| 4380 | break; |
| 4381 | case ICmpInst::ICMP_ULT: |
| 4382 | switch (RHSCC) { |
| 4383 | default: assert(0 && "Unknown integer condition code!"); |
| 4384 | case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change |
| 4385 | break; |
| 4386 | case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2 |
| 4387 | // If RHSCst is [us]MAXINT, it is always false. Not handling |
| 4388 | // this can cause overflow. |
| 4389 | if (RHSCst->isMaxValue(false)) |
| 4390 | return ReplaceInstUsesWith(I, LHS); |
| 4391 | return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I); |
| 4392 | case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change |
| 4393 | break; |
| 4394 | case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15 |
| 4395 | case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15 |
| 4396 | return ReplaceInstUsesWith(I, RHS); |
| 4397 | case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change |
| 4398 | break; |
| 4399 | } |
| 4400 | break; |
| 4401 | case ICmpInst::ICMP_SLT: |
| 4402 | switch (RHSCC) { |
| 4403 | default: assert(0 && "Unknown integer condition code!"); |
| 4404 | case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change |
| 4405 | break; |
| 4406 | case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2 |
| 4407 | // If RHSCst is [us]MAXINT, it is always false. Not handling |
| 4408 | // this can cause overflow. |
| 4409 | if (RHSCst->isMaxValue(true)) |
| 4410 | return ReplaceInstUsesWith(I, LHS); |
| 4411 | return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I); |
| 4412 | case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change |
| 4413 | break; |
| 4414 | case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15 |
| 4415 | case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15 |
| 4416 | return ReplaceInstUsesWith(I, RHS); |
| 4417 | case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change |
| 4418 | break; |
| 4419 | } |
| 4420 | break; |
| 4421 | case ICmpInst::ICMP_UGT: |
| 4422 | switch (RHSCC) { |
| 4423 | default: assert(0 && "Unknown integer condition code!"); |
| 4424 | case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13 |
| 4425 | case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13 |
| 4426 | return ReplaceInstUsesWith(I, LHS); |
| 4427 | case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change |
| 4428 | break; |
| 4429 | case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true |
| 4430 | case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true |
| 4431 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 4432 | case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change |
| 4433 | break; |
| 4434 | } |
| 4435 | break; |
| 4436 | case ICmpInst::ICMP_SGT: |
| 4437 | switch (RHSCC) { |
| 4438 | default: assert(0 && "Unknown integer condition code!"); |
| 4439 | case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13 |
| 4440 | case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13 |
| 4441 | return ReplaceInstUsesWith(I, LHS); |
| 4442 | case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change |
| 4443 | break; |
| 4444 | case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true |
| 4445 | case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true |
| 4446 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 4447 | case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change |
| 4448 | break; |
| 4449 | } |
| 4450 | break; |
| 4451 | } |
| 4452 | return 0; |
| 4453 | } |
| 4454 | |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4455 | /// FoldOrWithConstants - This helper function folds: |
| 4456 | /// |
Bill Wendling | 236a119 | 2008-12-02 05:09:00 +0000 | [diff] [blame] | 4457 | /// ((A | B) & C1) | (B & C2) |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4458 | /// |
| 4459 | /// into: |
| 4460 | /// |
Bill Wendling | 236a119 | 2008-12-02 05:09:00 +0000 | [diff] [blame] | 4461 | /// (A & C1) | B |
Bill Wendling | 9912f71 | 2008-12-01 08:32:40 +0000 | [diff] [blame] | 4462 | /// |
Bill Wendling | 236a119 | 2008-12-02 05:09:00 +0000 | [diff] [blame] | 4463 | /// when the XOR of the two constants is "all ones" (-1). |
Bill Wendling | 9912f71 | 2008-12-01 08:32:40 +0000 | [diff] [blame] | 4464 | Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op, |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4465 | Value *A, Value *B, Value *C) { |
Bill Wendling | fc5b8e6 | 2008-12-02 05:06:43 +0000 | [diff] [blame] | 4466 | ConstantInt *CI1 = dyn_cast<ConstantInt>(C); |
| 4467 | if (!CI1) return 0; |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4468 | |
Bill Wendling | 0a0dcaf | 2008-12-02 06:24:20 +0000 | [diff] [blame] | 4469 | Value *V1 = 0; |
| 4470 | ConstantInt *CI2 = 0; |
| 4471 | if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0; |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4472 | |
Bill Wendling | 86ee316 | 2008-12-02 06:18:11 +0000 | [diff] [blame] | 4473 | APInt Xor = CI1->getValue() ^ CI2->getValue(); |
| 4474 | if (!Xor.isAllOnesValue()) return 0; |
| 4475 | |
Bill Wendling | 0a0dcaf | 2008-12-02 06:24:20 +0000 | [diff] [blame] | 4476 | if (V1 == A || V1 == B) { |
Bill Wendling | 86ee316 | 2008-12-02 06:18:11 +0000 | [diff] [blame] | 4477 | Instruction *NewOp = |
Bill Wendling | 6c8ecbb | 2008-12-02 06:22:04 +0000 | [diff] [blame] | 4478 | InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I); |
| 4479 | return BinaryOperator::CreateOr(NewOp, V1); |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4480 | } |
| 4481 | |
| 4482 | return 0; |
| 4483 | } |
| 4484 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4485 | Instruction *InstCombiner::visitOr(BinaryOperator &I) { |
| 4486 | bool Changed = SimplifyCommutative(I); |
| 4487 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 4488 | |
| 4489 | if (isa<UndefValue>(Op1)) // X | undef -> -1 |
| 4490 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 4491 | |
| 4492 | // or X, X = X |
| 4493 | if (Op0 == Op1) |
| 4494 | return ReplaceInstUsesWith(I, Op0); |
| 4495 | |
| 4496 | // See if we can simplify any instructions used by the instruction whose sole |
| 4497 | // purpose is to compute bits we don't care about. |
| 4498 | if (!isa<VectorType>(I.getType())) { |
| 4499 | uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth(); |
| 4500 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 4501 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth), |
| 4502 | KnownZero, KnownOne)) |
| 4503 | return &I; |
| 4504 | } else if (isa<ConstantAggregateZero>(Op1)) { |
| 4505 | return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X |
| 4506 | } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) { |
| 4507 | if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1> |
| 4508 | return ReplaceInstUsesWith(I, I.getOperand(1)); |
| 4509 | } |
| 4510 | |
| 4511 | |
| 4512 | |
| 4513 | // or X, -1 == -1 |
| 4514 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
| 4515 | ConstantInt *C1 = 0; Value *X = 0; |
| 4516 | // (X & C1) | C2 --> (X | C2) & (C1|C2) |
| 4517 | if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4518 | Instruction *Or = BinaryOperator::CreateOr(X, RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4519 | InsertNewInstBefore(Or, I); |
| 4520 | Or->takeName(Op0); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4521 | return BinaryOperator::CreateAnd(Or, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4522 | ConstantInt::get(RHS->getValue() | C1->getValue())); |
| 4523 | } |
| 4524 | |
| 4525 | // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2) |
| 4526 | if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4527 | Instruction *Or = BinaryOperator::CreateOr(X, RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4528 | InsertNewInstBefore(Or, I); |
| 4529 | Or->takeName(Op0); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4530 | return BinaryOperator::CreateXor(Or, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4531 | ConstantInt::get(C1->getValue() & ~RHS->getValue())); |
| 4532 | } |
| 4533 | |
| 4534 | // Try to fold constant and into select arguments. |
| 4535 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 4536 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 4537 | return R; |
| 4538 | if (isa<PHINode>(Op0)) |
| 4539 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 4540 | return NV; |
| 4541 | } |
| 4542 | |
| 4543 | Value *A = 0, *B = 0; |
| 4544 | ConstantInt *C1 = 0, *C2 = 0; |
| 4545 | |
| 4546 | if (match(Op0, m_And(m_Value(A), m_Value(B)))) |
| 4547 | if (A == Op1 || B == Op1) // (A & ?) | A --> A |
| 4548 | return ReplaceInstUsesWith(I, Op1); |
| 4549 | if (match(Op1, m_And(m_Value(A), m_Value(B)))) |
| 4550 | if (A == Op0 || B == Op0) // A | (A & ?) --> A |
| 4551 | return ReplaceInstUsesWith(I, Op0); |
| 4552 | |
| 4553 | // (A | B) | C and A | (B | C) -> bswap if possible. |
| 4554 | // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible. |
| 4555 | if (match(Op0, m_Or(m_Value(), m_Value())) || |
| 4556 | match(Op1, m_Or(m_Value(), m_Value())) || |
| 4557 | (match(Op0, m_Shift(m_Value(), m_Value())) && |
| 4558 | match(Op1, m_Shift(m_Value(), m_Value())))) { |
| 4559 | if (Instruction *BSwap = MatchBSwap(I)) |
| 4560 | return BSwap; |
| 4561 | } |
| 4562 | |
| 4563 | // (X^C)|Y -> (X|Y)^C iff Y&C == 0 |
| 4564 | if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) && |
| 4565 | MaskedValueIsZero(Op1, C1->getValue())) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4566 | Instruction *NOr = BinaryOperator::CreateOr(A, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4567 | InsertNewInstBefore(NOr, I); |
| 4568 | NOr->takeName(Op0); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4569 | return BinaryOperator::CreateXor(NOr, C1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4570 | } |
| 4571 | |
| 4572 | // Y|(X^C) -> (X|Y)^C iff Y&C == 0 |
| 4573 | if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) && |
| 4574 | MaskedValueIsZero(Op0, C1->getValue())) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4575 | Instruction *NOr = BinaryOperator::CreateOr(A, Op0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4576 | InsertNewInstBefore(NOr, I); |
| 4577 | NOr->takeName(Op0); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4578 | return BinaryOperator::CreateXor(NOr, C1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4579 | } |
| 4580 | |
| 4581 | // (A & C)|(B & D) |
| 4582 | Value *C = 0, *D = 0; |
| 4583 | if (match(Op0, m_And(m_Value(A), m_Value(C))) && |
| 4584 | match(Op1, m_And(m_Value(B), m_Value(D)))) { |
| 4585 | Value *V1 = 0, *V2 = 0, *V3 = 0; |
| 4586 | C1 = dyn_cast<ConstantInt>(C); |
| 4587 | C2 = dyn_cast<ConstantInt>(D); |
| 4588 | if (C1 && C2) { // (A & C1)|(B & C2) |
| 4589 | // If we have: ((V + N) & C1) | (V & C2) |
| 4590 | // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 |
| 4591 | // replace with V+N. |
| 4592 | if (C1->getValue() == ~C2->getValue()) { |
| 4593 | if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+ |
| 4594 | match(A, m_Add(m_Value(V1), m_Value(V2)))) { |
| 4595 | // Add commutes, try both ways. |
| 4596 | if (V1 == B && MaskedValueIsZero(V2, C2->getValue())) |
| 4597 | return ReplaceInstUsesWith(I, A); |
| 4598 | if (V2 == B && MaskedValueIsZero(V1, C2->getValue())) |
| 4599 | return ReplaceInstUsesWith(I, A); |
| 4600 | } |
| 4601 | // Or commutes, try both ways. |
| 4602 | if ((C1->getValue() & (C1->getValue()+1)) == 0 && |
| 4603 | match(B, m_Add(m_Value(V1), m_Value(V2)))) { |
| 4604 | // Add commutes, try both ways. |
| 4605 | if (V1 == A && MaskedValueIsZero(V2, C1->getValue())) |
| 4606 | return ReplaceInstUsesWith(I, B); |
| 4607 | if (V2 == A && MaskedValueIsZero(V1, C1->getValue())) |
| 4608 | return ReplaceInstUsesWith(I, B); |
| 4609 | } |
| 4610 | } |
| 4611 | V1 = 0; V2 = 0; V3 = 0; |
| 4612 | } |
| 4613 | |
| 4614 | // Check to see if we have any common things being and'ed. If so, find the |
| 4615 | // terms for V1 & (V2|V3). |
| 4616 | if (isOnlyUse(Op0) || isOnlyUse(Op1)) { |
| 4617 | if (A == B) // (A & C)|(A & D) == A & (C|D) |
| 4618 | V1 = A, V2 = C, V3 = D; |
| 4619 | else if (A == D) // (A & C)|(B & A) == A & (B|C) |
| 4620 | V1 = A, V2 = B, V3 = C; |
| 4621 | else if (C == B) // (A & C)|(C & D) == C & (A|D) |
| 4622 | V1 = C, V2 = A, V3 = D; |
| 4623 | else if (C == D) // (A & C)|(B & C) == C & (A|B) |
| 4624 | V1 = C, V2 = A, V3 = B; |
| 4625 | |
| 4626 | if (V1) { |
| 4627 | Value *Or = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4628 | InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I); |
| 4629 | return BinaryOperator::CreateAnd(V1, Or); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4630 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4631 | } |
Dan Gohman | 279952c | 2008-10-28 22:38:57 +0000 | [diff] [blame] | 4632 | |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 4633 | // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants |
Chris Lattner | dd7772b | 2008-11-16 04:24:12 +0000 | [diff] [blame] | 4634 | if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D)) |
| 4635 | return Match; |
| 4636 | if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C)) |
| 4637 | return Match; |
| 4638 | if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D)) |
| 4639 | return Match; |
| 4640 | if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C)) |
| 4641 | return Match; |
Bill Wendling | 22ca835 | 2008-11-30 13:52:49 +0000 | [diff] [blame] | 4642 | |
Bill Wendling | 22ca835 | 2008-11-30 13:52:49 +0000 | [diff] [blame] | 4643 | // ((A&~B)|(~A&B)) -> A^B |
Bill Wendling | c1f3113 | 2008-12-01 08:09:47 +0000 | [diff] [blame] | 4644 | if ((match(C, m_Not(m_Specific(D))) && |
| 4645 | match(B, m_Not(m_Specific(A))))) |
| 4646 | return BinaryOperator::CreateXor(A, D); |
Bill Wendling | 22ca835 | 2008-11-30 13:52:49 +0000 | [diff] [blame] | 4647 | // ((~B&A)|(~A&B)) -> A^B |
Bill Wendling | c1f3113 | 2008-12-01 08:09:47 +0000 | [diff] [blame] | 4648 | if ((match(A, m_Not(m_Specific(D))) && |
| 4649 | match(B, m_Not(m_Specific(C))))) |
| 4650 | return BinaryOperator::CreateXor(C, D); |
Bill Wendling | 22ca835 | 2008-11-30 13:52:49 +0000 | [diff] [blame] | 4651 | // ((A&~B)|(B&~A)) -> A^B |
Bill Wendling | c1f3113 | 2008-12-01 08:09:47 +0000 | [diff] [blame] | 4652 | if ((match(C, m_Not(m_Specific(B))) && |
| 4653 | match(D, m_Not(m_Specific(A))))) |
| 4654 | return BinaryOperator::CreateXor(A, B); |
Bill Wendling | 22ca835 | 2008-11-30 13:52:49 +0000 | [diff] [blame] | 4655 | // ((~B&A)|(B&~A)) -> A^B |
Bill Wendling | c1f3113 | 2008-12-01 08:09:47 +0000 | [diff] [blame] | 4656 | if ((match(A, m_Not(m_Specific(B))) && |
| 4657 | match(D, m_Not(m_Specific(C))))) |
| 4658 | return BinaryOperator::CreateXor(C, B); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4659 | } |
| 4660 | |
| 4661 | // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts. |
| 4662 | if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) { |
| 4663 | if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0)) |
| 4664 | if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && |
| 4665 | SI0->getOperand(1) == SI1->getOperand(1) && |
| 4666 | (SI0->hasOneUse() || SI1->hasOneUse())) { |
| 4667 | Instruction *NewOp = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4668 | InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4669 | SI1->getOperand(0), |
| 4670 | SI0->getName()), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4671 | return BinaryOperator::Create(SI1->getOpcode(), NewOp, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4672 | SI1->getOperand(1)); |
| 4673 | } |
| 4674 | } |
| 4675 | |
Bill Wendling | d8ce237 | 2008-12-01 01:07:11 +0000 | [diff] [blame] | 4676 | // ((A|B)&1)|(B&-2) -> (A&1) | B |
| 4677 | if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) || |
| 4678 | match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) { |
Bill Wendling | 9912f71 | 2008-12-01 08:32:40 +0000 | [diff] [blame] | 4679 | Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C); |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4680 | if (Ret) return Ret; |
Bill Wendling | d8ce237 | 2008-12-01 01:07:11 +0000 | [diff] [blame] | 4681 | } |
| 4682 | // (B&-2)|((A|B)&1) -> (A&1) | B |
| 4683 | if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) || |
| 4684 | match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) { |
Bill Wendling | 9912f71 | 2008-12-01 08:32:40 +0000 | [diff] [blame] | 4685 | Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C); |
Bill Wendling | dae376a | 2008-12-01 08:23:25 +0000 | [diff] [blame] | 4686 | if (Ret) return Ret; |
Bill Wendling | d8ce237 | 2008-12-01 01:07:11 +0000 | [diff] [blame] | 4687 | } |
| 4688 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4689 | if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1 |
| 4690 | if (A == Op1) // ~A | A == -1 |
| 4691 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 4692 | } else { |
| 4693 | A = 0; |
| 4694 | } |
| 4695 | // Note, A is still live here! |
| 4696 | if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B |
| 4697 | if (Op0 == B) |
| 4698 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 4699 | |
| 4700 | // (~A | ~B) == (~(A & B)) - De Morgan's Law |
| 4701 | if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4702 | Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4703 | I.getName()+".demorgan"), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4704 | return BinaryOperator::CreateNot(And); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4705 | } |
| 4706 | } |
| 4707 | |
| 4708 | // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B) |
| 4709 | if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) { |
| 4710 | if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS))) |
| 4711 | return R; |
| 4712 | |
Chris Lattner | 0c678e5 | 2008-11-16 05:20:07 +0000 | [diff] [blame] | 4713 | if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0))) |
| 4714 | if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS)) |
| 4715 | return Res; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4716 | } |
| 4717 | |
| 4718 | // fold (or (cast A), (cast B)) -> (cast (or A, B)) |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4719 | if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4720 | if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) |
| 4721 | if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ? |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 4722 | if (!isa<ICmpInst>(Op0C->getOperand(0)) || |
| 4723 | !isa<ICmpInst>(Op1C->getOperand(0))) { |
| 4724 | const Type *SrcTy = Op0C->getOperand(0)->getType(); |
| 4725 | if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() && |
| 4726 | // Only do this if the casts both really cause code to be |
| 4727 | // generated. |
| 4728 | ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), |
| 4729 | I.getType(), TD) && |
| 4730 | ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), |
| 4731 | I.getType(), TD)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4732 | Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0), |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 4733 | Op1C->getOperand(0), |
| 4734 | I.getName()); |
| 4735 | InsertNewInstBefore(NewOp, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4736 | return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType()); |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 4737 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4738 | } |
| 4739 | } |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4740 | } |
| 4741 | |
| 4742 | |
| 4743 | // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y) |
| 4744 | if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) { |
| 4745 | if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) { |
| 4746 | if (LHS->getPredicate() == FCmpInst::FCMP_UNO && |
Chris Lattner | be9e63e | 2008-02-29 06:09:11 +0000 | [diff] [blame] | 4747 | RHS->getPredicate() == FCmpInst::FCMP_UNO && |
Evan Cheng | 7298805 | 2008-10-14 18:44:08 +0000 | [diff] [blame] | 4748 | LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) { |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4749 | if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1))) |
| 4750 | if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) { |
| 4751 | // If either of the constants are nans, then the whole thing returns |
| 4752 | // true. |
Chris Lattner | a6c7dce | 2007-10-24 18:54:45 +0000 | [diff] [blame] | 4753 | if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN()) |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4754 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 4755 | |
| 4756 | // Otherwise, no need to compare the two constants, compare the |
| 4757 | // rest. |
| 4758 | return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0), |
| 4759 | RHS->getOperand(0)); |
| 4760 | } |
Evan Cheng | 7298805 | 2008-10-14 18:44:08 +0000 | [diff] [blame] | 4761 | } else { |
| 4762 | Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS; |
| 4763 | FCmpInst::Predicate Op0CC, Op1CC; |
| 4764 | if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) && |
| 4765 | match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) { |
| 4766 | if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) { |
| 4767 | // Swap RHS operands to match LHS. |
| 4768 | Op1CC = FCmpInst::getSwappedPredicate(Op1CC); |
| 4769 | std::swap(Op1LHS, Op1RHS); |
| 4770 | } |
| 4771 | if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) { |
| 4772 | // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y). |
| 4773 | if (Op0CC == Op1CC) |
| 4774 | return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS); |
| 4775 | else if (Op0CC == FCmpInst::FCMP_TRUE || |
| 4776 | Op1CC == FCmpInst::FCMP_TRUE) |
| 4777 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 4778 | else if (Op0CC == FCmpInst::FCMP_FALSE) |
| 4779 | return ReplaceInstUsesWith(I, Op1); |
| 4780 | else if (Op1CC == FCmpInst::FCMP_FALSE) |
| 4781 | return ReplaceInstUsesWith(I, Op0); |
| 4782 | bool Op0Ordered; |
| 4783 | bool Op1Ordered; |
| 4784 | unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered); |
| 4785 | unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered); |
| 4786 | if (Op0Ordered == Op1Ordered) { |
| 4787 | // If both are ordered or unordered, return a new fcmp with |
| 4788 | // or'ed predicates. |
| 4789 | Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, |
| 4790 | Op0LHS, Op0RHS); |
| 4791 | if (Instruction *I = dyn_cast<Instruction>(RV)) |
| 4792 | return I; |
| 4793 | // Otherwise, it's a constant boolean value... |
| 4794 | return ReplaceInstUsesWith(I, RV); |
| 4795 | } |
| 4796 | } |
| 4797 | } |
| 4798 | } |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 4799 | } |
| 4800 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4801 | |
| 4802 | return Changed ? &I : 0; |
| 4803 | } |
| 4804 | |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 4805 | namespace { |
| 4806 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4807 | // XorSelf - Implements: X ^ X --> 0 |
| 4808 | struct XorSelf { |
| 4809 | Value *RHS; |
| 4810 | XorSelf(Value *rhs) : RHS(rhs) {} |
| 4811 | bool shouldApply(Value *LHS) const { return LHS == RHS; } |
| 4812 | Instruction *apply(BinaryOperator &Xor) const { |
| 4813 | return &Xor; |
| 4814 | } |
| 4815 | }; |
| 4816 | |
Dan Gohman | 089efff | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 4817 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4818 | |
| 4819 | Instruction *InstCombiner::visitXor(BinaryOperator &I) { |
| 4820 | bool Changed = SimplifyCommutative(I); |
| 4821 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 4822 | |
Evan Cheng | e5cd803 | 2008-03-25 20:07:13 +0000 | [diff] [blame] | 4823 | if (isa<UndefValue>(Op1)) { |
| 4824 | if (isa<UndefValue>(Op0)) |
| 4825 | // Handle undef ^ undef -> 0 special case. This is a common |
| 4826 | // idiom (misuse). |
| 4827 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4828 | return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef |
Evan Cheng | e5cd803 | 2008-03-25 20:07:13 +0000 | [diff] [blame] | 4829 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4830 | |
| 4831 | // xor X, X = 0, even if X is nested in a sequence of Xor's. |
| 4832 | if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) { |
Chris Lattner | b933ea6 | 2007-08-05 08:47:58 +0000 | [diff] [blame] | 4833 | assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4834 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 4835 | } |
| 4836 | |
| 4837 | // See if we can simplify any instructions used by the instruction whose sole |
| 4838 | // purpose is to compute bits we don't care about. |
| 4839 | if (!isa<VectorType>(I.getType())) { |
| 4840 | uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth(); |
| 4841 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 4842 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth), |
| 4843 | KnownZero, KnownOne)) |
| 4844 | return &I; |
| 4845 | } else if (isa<ConstantAggregateZero>(Op1)) { |
| 4846 | return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X |
| 4847 | } |
| 4848 | |
| 4849 | // Is this a ~ operation? |
| 4850 | if (Value *NotOp = dyn_castNotVal(&I)) { |
| 4851 | // ~(~X & Y) --> (X | ~Y) - De Morgan's Law |
| 4852 | // ~(~X | Y) === (X & ~Y) - De Morgan's Law |
| 4853 | if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) { |
| 4854 | if (Op0I->getOpcode() == Instruction::And || |
| 4855 | Op0I->getOpcode() == Instruction::Or) { |
| 4856 | if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands(); |
| 4857 | if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) { |
| 4858 | Instruction *NotY = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4859 | BinaryOperator::CreateNot(Op0I->getOperand(1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4860 | Op0I->getOperand(1)->getName()+".not"); |
| 4861 | InsertNewInstBefore(NotY, I); |
| 4862 | if (Op0I->getOpcode() == Instruction::And) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4863 | return BinaryOperator::CreateOr(Op0NotVal, NotY); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4864 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4865 | return BinaryOperator::CreateAnd(Op0NotVal, NotY); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4866 | } |
| 4867 | } |
| 4868 | } |
| 4869 | } |
| 4870 | |
| 4871 | |
| 4872 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) { |
Nick Lewycky | 1405e92 | 2007-08-06 20:04:16 +0000 | [diff] [blame] | 4873 | if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) { |
Bill Wendling | 6174195 | 2009-01-01 01:18:23 +0000 | [diff] [blame] | 4874 | // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B |
Nick Lewycky | 1405e92 | 2007-08-06 20:04:16 +0000 | [diff] [blame] | 4875 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4876 | return new ICmpInst(ICI->getInversePredicate(), |
| 4877 | ICI->getOperand(0), ICI->getOperand(1)); |
| 4878 | |
Nick Lewycky | 1405e92 | 2007-08-06 20:04:16 +0000 | [diff] [blame] | 4879 | if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0)) |
| 4880 | return new FCmpInst(FCI->getInversePredicate(), |
| 4881 | FCI->getOperand(0), FCI->getOperand(1)); |
| 4882 | } |
| 4883 | |
Nick Lewycky | 0aa63aa | 2008-05-31 19:01:33 +0000 | [diff] [blame] | 4884 | // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp). |
| 4885 | if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) { |
| 4886 | if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) { |
| 4887 | if (CI->hasOneUse() && Op0C->hasOneUse()) { |
| 4888 | Instruction::CastOps Opcode = Op0C->getOpcode(); |
| 4889 | if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) { |
| 4890 | if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(), |
| 4891 | Op0C->getDestTy())) { |
| 4892 | Instruction *NewCI = InsertNewInstBefore(CmpInst::Create( |
| 4893 | CI->getOpcode(), CI->getInversePredicate(), |
| 4894 | CI->getOperand(0), CI->getOperand(1)), I); |
| 4895 | NewCI->takeName(CI); |
| 4896 | return CastInst::Create(Opcode, NewCI, Op0C->getType()); |
| 4897 | } |
| 4898 | } |
| 4899 | } |
| 4900 | } |
| 4901 | } |
| 4902 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4903 | if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) { |
| 4904 | // ~(c-X) == X-c-1 == X+(-c-1) |
| 4905 | if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue()) |
| 4906 | if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) { |
| 4907 | Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C); |
| 4908 | Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C, |
| 4909 | ConstantInt::get(I.getType(), 1)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4910 | return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4911 | } |
| 4912 | |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 4913 | if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4914 | if (Op0I->getOpcode() == Instruction::Add) { |
| 4915 | // ~(X-c) --> (-c-1)-X |
| 4916 | if (RHS->isAllOnesValue()) { |
| 4917 | Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4918 | return BinaryOperator::CreateSub( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4919 | ConstantExpr::getSub(NegOp0CI, |
| 4920 | ConstantInt::get(I.getType(), 1)), |
| 4921 | Op0I->getOperand(0)); |
| 4922 | } else if (RHS->getValue().isSignBit()) { |
| 4923 | // (X + C) ^ signbit -> (X + C + signbit) |
| 4924 | Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue()); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 4925 | return BinaryOperator::CreateAdd(Op0I->getOperand(0), C); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4926 | |
| 4927 | } |
| 4928 | } else if (Op0I->getOpcode() == Instruction::Or) { |
| 4929 | // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0 |
| 4930 | if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) { |
| 4931 | Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS); |
| 4932 | // Anything in both C1 and C2 is known to be zero, remove it from |
| 4933 | // NewRHS. |
| 4934 | Constant *CommonBits = And(Op0CI, RHS); |
| 4935 | NewRHS = ConstantExpr::getAnd(NewRHS, |
| 4936 | ConstantExpr::getNot(CommonBits)); |
| 4937 | AddToWorkList(Op0I); |
| 4938 | I.setOperand(0, Op0I->getOperand(0)); |
| 4939 | I.setOperand(1, NewRHS); |
| 4940 | return &I; |
| 4941 | } |
| 4942 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 4943 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4944 | } |
| 4945 | |
| 4946 | // Try to fold constant and into select arguments. |
| 4947 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 4948 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 4949 | return R; |
| 4950 | if (isa<PHINode>(Op0)) |
| 4951 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 4952 | return NV; |
| 4953 | } |
| 4954 | |
| 4955 | if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1 |
| 4956 | if (X == Op1) |
| 4957 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 4958 | |
| 4959 | if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1 |
| 4960 | if (X == Op0) |
| 4961 | return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType())); |
| 4962 | |
| 4963 | |
| 4964 | BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1); |
| 4965 | if (Op1I) { |
| 4966 | Value *A, *B; |
| 4967 | if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) { |
| 4968 | if (A == Op0) { // B^(B|A) == (A|B)^B |
| 4969 | Op1I->swapOperands(); |
| 4970 | I.swapOperands(); |
| 4971 | std::swap(Op0, Op1); |
| 4972 | } else if (B == Op0) { // B^(A|B) == (A|B)^B |
| 4973 | I.swapOperands(); // Simplified below. |
| 4974 | std::swap(Op0, Op1); |
| 4975 | } |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 4976 | } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) { |
| 4977 | return ReplaceInstUsesWith(I, B); // A^(A^B) == B |
| 4978 | } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) { |
| 4979 | return ReplaceInstUsesWith(I, A); // A^(B^A) == B |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 4980 | } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){ |
| 4981 | if (A == Op0) { // A^(A&B) -> A^(B&A) |
| 4982 | Op1I->swapOperands(); |
| 4983 | std::swap(A, B); |
| 4984 | } |
| 4985 | if (B == Op0) { // A^(B&A) -> (B&A)^A |
| 4986 | I.swapOperands(); // Simplified below. |
| 4987 | std::swap(Op0, Op1); |
| 4988 | } |
| 4989 | } |
| 4990 | } |
| 4991 | |
| 4992 | BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0); |
| 4993 | if (Op0I) { |
| 4994 | Value *A, *B; |
| 4995 | if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) { |
| 4996 | if (A == Op1) // (B|A)^B == (A|B)^B |
| 4997 | std::swap(A, B); |
| 4998 | if (B == Op1) { // (A|B)^B == A & ~B |
| 4999 | Instruction *NotB = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5000 | InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I); |
| 5001 | return BinaryOperator::CreateAnd(A, NotB); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5002 | } |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 5003 | } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) { |
| 5004 | return ReplaceInstUsesWith(I, B); // (A^B)^A == B |
| 5005 | } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) { |
| 5006 | return ReplaceInstUsesWith(I, A); // (B^A)^A == B |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5007 | } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){ |
| 5008 | if (A == Op1) // (A&B)^A -> (B&A)^A |
| 5009 | std::swap(A, B); |
| 5010 | if (B == Op1 && // (B&A)^A == ~B & A |
| 5011 | !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C |
| 5012 | Instruction *N = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5013 | InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I); |
| 5014 | return BinaryOperator::CreateAnd(N, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5015 | } |
| 5016 | } |
| 5017 | } |
| 5018 | |
| 5019 | // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts. |
| 5020 | if (Op0I && Op1I && Op0I->isShift() && |
| 5021 | Op0I->getOpcode() == Op1I->getOpcode() && |
| 5022 | Op0I->getOperand(1) == Op1I->getOperand(1) && |
| 5023 | (Op1I->hasOneUse() || Op1I->hasOneUse())) { |
| 5024 | Instruction *NewOp = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5025 | InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5026 | Op1I->getOperand(0), |
| 5027 | Op0I->getName()), I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5028 | return BinaryOperator::Create(Op1I->getOpcode(), NewOp, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5029 | Op1I->getOperand(1)); |
| 5030 | } |
| 5031 | |
| 5032 | if (Op0I && Op1I) { |
| 5033 | Value *A, *B, *C, *D; |
| 5034 | // (A & B)^(A | B) -> A ^ B |
| 5035 | if (match(Op0I, m_And(m_Value(A), m_Value(B))) && |
| 5036 | match(Op1I, m_Or(m_Value(C), m_Value(D)))) { |
| 5037 | if ((A == C && B == D) || (A == D && B == C)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5038 | return BinaryOperator::CreateXor(A, B); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5039 | } |
| 5040 | // (A | B)^(A & B) -> A ^ B |
| 5041 | if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && |
| 5042 | match(Op1I, m_And(m_Value(C), m_Value(D)))) { |
| 5043 | if ((A == C && B == D) || (A == D && B == C)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5044 | return BinaryOperator::CreateXor(A, B); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5045 | } |
| 5046 | |
| 5047 | // (A & B)^(C & D) |
| 5048 | if ((Op0I->hasOneUse() || Op1I->hasOneUse()) && |
| 5049 | match(Op0I, m_And(m_Value(A), m_Value(B))) && |
| 5050 | match(Op1I, m_And(m_Value(C), m_Value(D)))) { |
| 5051 | // (X & Y)^(X & Y) -> (Y^Z) & X |
| 5052 | Value *X = 0, *Y = 0, *Z = 0; |
| 5053 | if (A == C) |
| 5054 | X = A, Y = B, Z = D; |
| 5055 | else if (A == D) |
| 5056 | X = A, Y = B, Z = C; |
| 5057 | else if (B == C) |
| 5058 | X = B, Y = A, Z = D; |
| 5059 | else if (B == D) |
| 5060 | X = B, Y = A, Z = C; |
| 5061 | |
| 5062 | if (X) { |
| 5063 | Instruction *NewOp = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5064 | InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I); |
| 5065 | return BinaryOperator::CreateAnd(NewOp, X); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5066 | } |
| 5067 | } |
| 5068 | } |
| 5069 | |
| 5070 | // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B) |
| 5071 | if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) |
| 5072 | if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS))) |
| 5073 | return R; |
| 5074 | |
| 5075 | // fold (xor (cast A), (cast B)) -> (cast (xor A, B)) |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 5076 | if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5077 | if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) |
| 5078 | if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind? |
| 5079 | const Type *SrcTy = Op0C->getOperand(0)->getType(); |
| 5080 | if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() && |
| 5081 | // Only do this if the casts both really cause code to be generated. |
| 5082 | ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), |
| 5083 | I.getType(), TD) && |
| 5084 | ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), |
| 5085 | I.getType(), TD)) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5086 | Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5087 | Op1C->getOperand(0), |
| 5088 | I.getName()); |
| 5089 | InsertNewInstBefore(NewOp, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5090 | return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5091 | } |
| 5092 | } |
Chris Lattner | 9188243 | 2007-10-24 05:38:08 +0000 | [diff] [blame] | 5093 | } |
Nick Lewycky | 0aa63aa | 2008-05-31 19:01:33 +0000 | [diff] [blame] | 5094 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5095 | return Changed ? &I : 0; |
| 5096 | } |
| 5097 | |
| 5098 | /// AddWithOverflow - Compute Result = In1+In2, returning true if the result |
| 5099 | /// overflowed for this type. |
| 5100 | static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1, |
| 5101 | ConstantInt *In2, bool IsSigned = false) { |
| 5102 | Result = cast<ConstantInt>(Add(In1, In2)); |
| 5103 | |
| 5104 | if (IsSigned) |
| 5105 | if (In2->getValue().isNegative()) |
| 5106 | return Result->getValue().sgt(In1->getValue()); |
| 5107 | else |
| 5108 | return Result->getValue().slt(In1->getValue()); |
| 5109 | else |
| 5110 | return Result->getValue().ult(In1->getValue()); |
| 5111 | } |
| 5112 | |
Dan Gohman | b80d561 | 2008-09-10 23:30:57 +0000 | [diff] [blame] | 5113 | /// SubWithOverflow - Compute Result = In1-In2, returning true if the result |
| 5114 | /// overflowed for this type. |
| 5115 | static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1, |
| 5116 | ConstantInt *In2, bool IsSigned = false) { |
Dan Gohman | 2c3b489 | 2008-09-11 18:53:02 +0000 | [diff] [blame] | 5117 | Result = cast<ConstantInt>(Subtract(In1, In2)); |
Dan Gohman | b80d561 | 2008-09-10 23:30:57 +0000 | [diff] [blame] | 5118 | |
| 5119 | if (IsSigned) |
| 5120 | if (In2->getValue().isNegative()) |
| 5121 | return Result->getValue().slt(In1->getValue()); |
| 5122 | else |
| 5123 | return Result->getValue().sgt(In1->getValue()); |
| 5124 | else |
| 5125 | return Result->getValue().ugt(In1->getValue()); |
| 5126 | } |
| 5127 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5128 | /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the |
| 5129 | /// code necessary to compute the offset from the base pointer (without adding |
| 5130 | /// in the base pointer). Return the result as a signed integer of intptr size. |
| 5131 | static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) { |
| 5132 | TargetData &TD = IC.getTargetData(); |
| 5133 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 5134 | const Type *IntPtrTy = TD.getIntPtrType(); |
| 5135 | Value *Result = Constant::getNullValue(IntPtrTy); |
| 5136 | |
| 5137 | // Build a mask for high order bits. |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5138 | unsigned IntPtrWidth = TD.getPointerSizeInBits(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5139 | uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); |
| 5140 | |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 5141 | for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e; |
| 5142 | ++i, ++GTI) { |
| 5143 | Value *Op = *i; |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 5144 | uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5145 | if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) { |
| 5146 | if (OpC->isZero()) continue; |
| 5147 | |
| 5148 | // Handle a struct index, which adds its field offset to the pointer. |
| 5149 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 5150 | Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); |
| 5151 | |
| 5152 | if (ConstantInt *RC = dyn_cast<ConstantInt>(Result)) |
| 5153 | Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size)); |
| 5154 | else |
| 5155 | Result = IC.InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5156 | BinaryOperator::CreateAdd(Result, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5157 | ConstantInt::get(IntPtrTy, Size), |
| 5158 | GEP->getName()+".offs"), I); |
| 5159 | continue; |
| 5160 | } |
| 5161 | |
| 5162 | Constant *Scale = ConstantInt::get(IntPtrTy, Size); |
| 5163 | Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/); |
| 5164 | Scale = ConstantExpr::getMul(OC, Scale); |
| 5165 | if (Constant *RC = dyn_cast<Constant>(Result)) |
| 5166 | Result = ConstantExpr::getAdd(RC, Scale); |
| 5167 | else { |
| 5168 | // Emit an add instruction. |
| 5169 | Result = IC.InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5170 | BinaryOperator::CreateAdd(Result, Scale, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5171 | GEP->getName()+".offs"), I); |
| 5172 | } |
| 5173 | continue; |
| 5174 | } |
| 5175 | // Convert to correct type. |
| 5176 | if (Op->getType() != IntPtrTy) { |
| 5177 | if (Constant *OpC = dyn_cast<Constant>(Op)) |
| 5178 | Op = ConstantExpr::getSExt(OpC, IntPtrTy); |
| 5179 | else |
| 5180 | Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy, |
| 5181 | Op->getName()+".c"), I); |
| 5182 | } |
| 5183 | if (Size != 1) { |
| 5184 | Constant *Scale = ConstantInt::get(IntPtrTy, Size); |
| 5185 | if (Constant *OpC = dyn_cast<Constant>(Op)) |
| 5186 | Op = ConstantExpr::getMul(OpC, Scale); |
| 5187 | else // We'll let instcombine(mul) convert this to a shl if possible. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5188 | Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5189 | GEP->getName()+".idx"), I); |
| 5190 | } |
| 5191 | |
| 5192 | // Emit an add instruction. |
| 5193 | if (isa<Constant>(Op) && isa<Constant>(Result)) |
| 5194 | Result = ConstantExpr::getAdd(cast<Constant>(Op), |
| 5195 | cast<Constant>(Result)); |
| 5196 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5197 | Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5198 | GEP->getName()+".offs"), I); |
| 5199 | } |
| 5200 | return Result; |
| 5201 | } |
| 5202 | |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5203 | |
| 5204 | /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of |
| 5205 | /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want |
| 5206 | /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be |
| 5207 | /// complex, and scales are involved. The above expression would also be legal |
| 5208 | /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This |
| 5209 | /// later form is less amenable to optimization though, and we are allowed to |
| 5210 | /// generate the first by knowing that pointer arithmetic doesn't overflow. |
| 5211 | /// |
| 5212 | /// If we can't emit an optimized form for this expression, this returns null. |
| 5213 | /// |
| 5214 | static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I, |
| 5215 | InstCombiner &IC) { |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5216 | TargetData &TD = IC.getTargetData(); |
| 5217 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 5218 | |
| 5219 | // Check to see if this gep only has a single variable index. If so, and if |
| 5220 | // any constant indices are a multiple of its scale, then we can compute this |
| 5221 | // in terms of the scale of the variable index. For example, if the GEP |
| 5222 | // implies an offset of "12 + i*4", then we can codegen this as "3 + i", |
| 5223 | // because the expression will cross zero at the same point. |
| 5224 | unsigned i, e = GEP->getNumOperands(); |
| 5225 | int64_t Offset = 0; |
| 5226 | for (i = 1; i != e; ++i, ++GTI) { |
| 5227 | if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { |
| 5228 | // Compute the aggregate offset of constant indices. |
| 5229 | if (CI->isZero()) continue; |
| 5230 | |
| 5231 | // Handle a struct index, which adds its field offset to the pointer. |
| 5232 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 5233 | Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); |
| 5234 | } else { |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 5235 | uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()); |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5236 | Offset += Size*CI->getSExtValue(); |
| 5237 | } |
| 5238 | } else { |
| 5239 | // Found our variable index. |
| 5240 | break; |
| 5241 | } |
| 5242 | } |
| 5243 | |
| 5244 | // If there are no variable indices, we must have a constant offset, just |
| 5245 | // evaluate it the general way. |
| 5246 | if (i == e) return 0; |
| 5247 | |
| 5248 | Value *VariableIdx = GEP->getOperand(i); |
| 5249 | // Determine the scale factor of the variable element. For example, this is |
| 5250 | // 4 if the variable index is into an array of i32. |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 5251 | uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType()); |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5252 | |
| 5253 | // Verify that there are no other variable indices. If so, emit the hard way. |
| 5254 | for (++i, ++GTI; i != e; ++i, ++GTI) { |
| 5255 | ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 5256 | if (!CI) return 0; |
| 5257 | |
| 5258 | // Compute the aggregate offset of constant indices. |
| 5259 | if (CI->isZero()) continue; |
| 5260 | |
| 5261 | // Handle a struct index, which adds its field offset to the pointer. |
| 5262 | if (const StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 5263 | Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); |
| 5264 | } else { |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 5265 | uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()); |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5266 | Offset += Size*CI->getSExtValue(); |
| 5267 | } |
| 5268 | } |
| 5269 | |
| 5270 | // Okay, we know we have a single variable index, which must be a |
| 5271 | // pointer/array/vector index. If there is no offset, life is simple, return |
| 5272 | // the index. |
| 5273 | unsigned IntPtrWidth = TD.getPointerSizeInBits(); |
| 5274 | if (Offset == 0) { |
| 5275 | // Cast to intptrty in case a truncation occurs. If an extension is needed, |
| 5276 | // we don't need to bother extending: the extension won't affect where the |
| 5277 | // computation crosses zero. |
| 5278 | if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) |
| 5279 | VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(), |
| 5280 | VariableIdx->getNameStart(), &I); |
| 5281 | return VariableIdx; |
| 5282 | } |
| 5283 | |
| 5284 | // Otherwise, there is an index. The computation we will do will be modulo |
| 5285 | // the pointer size, so get it. |
| 5286 | uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); |
| 5287 | |
| 5288 | Offset &= PtrSizeMask; |
| 5289 | VariableScale &= PtrSizeMask; |
| 5290 | |
| 5291 | // To do this transformation, any constant index must be a multiple of the |
| 5292 | // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", |
| 5293 | // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a |
| 5294 | // multiple of the variable scale. |
| 5295 | int64_t NewOffs = Offset / (int64_t)VariableScale; |
| 5296 | if (Offset != NewOffs*(int64_t)VariableScale) |
| 5297 | return 0; |
| 5298 | |
| 5299 | // Okay, we can do this evaluation. Start by converting the index to intptr. |
| 5300 | const Type *IntPtrTy = TD.getIntPtrType(); |
| 5301 | if (VariableIdx->getType() != IntPtrTy) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5302 | VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy, |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5303 | true /*SExt*/, |
| 5304 | VariableIdx->getNameStart(), &I); |
| 5305 | Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5306 | return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I); |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5307 | } |
| 5308 | |
| 5309 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5310 | /// FoldGEPICmp - Fold comparisons between a GEP instruction and something |
| 5311 | /// else. At this point we know that the GEP is on the LHS of the comparison. |
| 5312 | Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS, |
| 5313 | ICmpInst::Predicate Cond, |
| 5314 | Instruction &I) { |
| 5315 | assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!"); |
| 5316 | |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5317 | // Look through bitcasts. |
| 5318 | if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS)) |
| 5319 | RHS = BCI->getOperand(0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5320 | |
| 5321 | Value *PtrBase = GEPLHS->getOperand(0); |
| 5322 | if (PtrBase == RHS) { |
Chris Lattner | af97d02 | 2008-02-05 04:45:32 +0000 | [diff] [blame] | 5323 | // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). |
Chris Lattner | eba7586 | 2008-04-22 02:53:33 +0000 | [diff] [blame] | 5324 | // This transformation (ignoring the base and scales) is valid because we |
| 5325 | // know pointers can't overflow. See if we can output an optimized form. |
| 5326 | Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this); |
| 5327 | |
| 5328 | // If not, synthesize the offset the hard way. |
| 5329 | if (Offset == 0) |
| 5330 | Offset = EmitGEPOffset(GEPLHS, I, *this); |
Chris Lattner | af97d02 | 2008-02-05 04:45:32 +0000 | [diff] [blame] | 5331 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, |
| 5332 | Constant::getNullValue(Offset->getType())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5333 | } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) { |
| 5334 | // If the base pointers are different, but the indices are the same, just |
| 5335 | // compare the base pointer. |
| 5336 | if (PtrBase != GEPRHS->getOperand(0)) { |
| 5337 | bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); |
| 5338 | IndicesTheSame &= GEPLHS->getOperand(0)->getType() == |
| 5339 | GEPRHS->getOperand(0)->getType(); |
| 5340 | if (IndicesTheSame) |
| 5341 | for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) |
| 5342 | if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { |
| 5343 | IndicesTheSame = false; |
| 5344 | break; |
| 5345 | } |
| 5346 | |
| 5347 | // If all indices are the same, just compare the base pointers. |
| 5348 | if (IndicesTheSame) |
| 5349 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), |
| 5350 | GEPLHS->getOperand(0), GEPRHS->getOperand(0)); |
| 5351 | |
| 5352 | // Otherwise, the base pointers are different and the indices are |
| 5353 | // different, bail out. |
| 5354 | return 0; |
| 5355 | } |
| 5356 | |
| 5357 | // If one of the GEPs has all zero indices, recurse. |
| 5358 | bool AllZeros = true; |
| 5359 | for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) |
| 5360 | if (!isa<Constant>(GEPLHS->getOperand(i)) || |
| 5361 | !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) { |
| 5362 | AllZeros = false; |
| 5363 | break; |
| 5364 | } |
| 5365 | if (AllZeros) |
| 5366 | return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0), |
| 5367 | ICmpInst::getSwappedPredicate(Cond), I); |
| 5368 | |
| 5369 | // If the other GEP has all zero indices, recurse. |
| 5370 | AllZeros = true; |
| 5371 | for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) |
| 5372 | if (!isa<Constant>(GEPRHS->getOperand(i)) || |
| 5373 | !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) { |
| 5374 | AllZeros = false; |
| 5375 | break; |
| 5376 | } |
| 5377 | if (AllZeros) |
| 5378 | return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); |
| 5379 | |
| 5380 | if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { |
| 5381 | // If the GEPs only differ by one index, compare it. |
| 5382 | unsigned NumDifferences = 0; // Keep track of # differences. |
| 5383 | unsigned DiffOperand = 0; // The operand that differs. |
| 5384 | for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) |
| 5385 | if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { |
| 5386 | if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != |
| 5387 | GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { |
| 5388 | // Irreconcilable differences. |
| 5389 | NumDifferences = 2; |
| 5390 | break; |
| 5391 | } else { |
| 5392 | if (NumDifferences++) break; |
| 5393 | DiffOperand = i; |
| 5394 | } |
| 5395 | } |
| 5396 | |
| 5397 | if (NumDifferences == 0) // SAME GEP? |
| 5398 | return ReplaceInstUsesWith(I, // No comparison is needed here. |
Nick Lewycky | 2de09a9 | 2007-09-06 02:40:25 +0000 | [diff] [blame] | 5399 | ConstantInt::get(Type::Int1Ty, |
Nick Lewycky | 09284cf | 2008-05-17 07:33:39 +0000 | [diff] [blame] | 5400 | ICmpInst::isTrueWhenEqual(Cond))); |
Nick Lewycky | 2de09a9 | 2007-09-06 02:40:25 +0000 | [diff] [blame] | 5401 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5402 | else if (NumDifferences == 1) { |
| 5403 | Value *LHSV = GEPLHS->getOperand(DiffOperand); |
| 5404 | Value *RHSV = GEPRHS->getOperand(DiffOperand); |
| 5405 | // Make sure we do a signed comparison here. |
| 5406 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); |
| 5407 | } |
| 5408 | } |
| 5409 | |
| 5410 | // Only lower this if the icmp is the only user of the GEP or if we expect |
| 5411 | // the result to fold to a constant! |
| 5412 | if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && |
| 5413 | (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { |
| 5414 | // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) |
| 5415 | Value *L = EmitGEPOffset(GEPLHS, I, *this); |
| 5416 | Value *R = EmitGEPOffset(GEPRHS, I, *this); |
| 5417 | return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); |
| 5418 | } |
| 5419 | } |
| 5420 | return 0; |
| 5421 | } |
| 5422 | |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5423 | /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible. |
| 5424 | /// |
| 5425 | Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I, |
| 5426 | Instruction *LHSI, |
| 5427 | Constant *RHSC) { |
| 5428 | if (!isa<ConstantFP>(RHSC)) return 0; |
| 5429 | const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); |
| 5430 | |
| 5431 | // Get the width of the mantissa. We don't want to hack on conversions that |
| 5432 | // might lose information from the integer, e.g. "i64 -> float" |
Chris Lattner | 9ce836b | 2008-05-19 21:17:23 +0000 | [diff] [blame] | 5433 | int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5434 | if (MantissaWidth == -1) return 0; // Unknown. |
| 5435 | |
| 5436 | // Check to see that the input is converted from an integer type that is small |
| 5437 | // enough that preserves all bits. TODO: check here for "known" sign bits. |
| 5438 | // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. |
| 5439 | unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); |
| 5440 | |
| 5441 | // If this is a uitofp instruction, we need an extra bit to hold the sign. |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5442 | bool LHSUnsigned = isa<UIToFPInst>(LHSI); |
| 5443 | if (LHSUnsigned) |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5444 | ++InputSize; |
| 5445 | |
| 5446 | // If the conversion would lose info, don't hack on this. |
| 5447 | if ((int)InputSize > MantissaWidth) |
| 5448 | return 0; |
| 5449 | |
| 5450 | // Otherwise, we can potentially simplify the comparison. We know that it |
| 5451 | // will always come through as an integer value and we know the constant is |
| 5452 | // not a NAN (it would have been previously simplified). |
| 5453 | assert(!RHS.isNaN() && "NaN comparison not already folded!"); |
| 5454 | |
| 5455 | ICmpInst::Predicate Pred; |
| 5456 | switch (I.getPredicate()) { |
| 5457 | default: assert(0 && "Unexpected predicate!"); |
| 5458 | case FCmpInst::FCMP_UEQ: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5459 | case FCmpInst::FCMP_OEQ: |
| 5460 | Pred = ICmpInst::ICMP_EQ; |
| 5461 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5462 | case FCmpInst::FCMP_UGT: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5463 | case FCmpInst::FCMP_OGT: |
| 5464 | Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; |
| 5465 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5466 | case FCmpInst::FCMP_UGE: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5467 | case FCmpInst::FCMP_OGE: |
| 5468 | Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; |
| 5469 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5470 | case FCmpInst::FCMP_ULT: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5471 | case FCmpInst::FCMP_OLT: |
| 5472 | Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; |
| 5473 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5474 | case FCmpInst::FCMP_ULE: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5475 | case FCmpInst::FCMP_OLE: |
| 5476 | Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; |
| 5477 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5478 | case FCmpInst::FCMP_UNE: |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5479 | case FCmpInst::FCMP_ONE: |
| 5480 | Pred = ICmpInst::ICMP_NE; |
| 5481 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5482 | case FCmpInst::FCMP_ORD: |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5483 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5484 | case FCmpInst::FCMP_UNO: |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5485 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5486 | } |
| 5487 | |
| 5488 | const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); |
| 5489 | |
| 5490 | // Now we know that the APFloat is a normal number, zero or inf. |
| 5491 | |
Chris Lattner | f13ff49 | 2008-05-20 03:50:52 +0000 | [diff] [blame] | 5492 | // See if the FP constant is too large for the integer. For example, |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5493 | // comparing an i8 to 300.0. |
| 5494 | unsigned IntWidth = IntTy->getPrimitiveSizeInBits(); |
| 5495 | |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5496 | if (!LHSUnsigned) { |
| 5497 | // If the RHS value is > SignedMax, fold the comparison. This handles +INF |
| 5498 | // and large values. |
| 5499 | APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false); |
| 5500 | SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, |
| 5501 | APFloat::rmNearestTiesToEven); |
| 5502 | if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 |
| 5503 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || |
| 5504 | Pred == ICmpInst::ICMP_SLE) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5505 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5506 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5507 | } |
| 5508 | } else { |
| 5509 | // If the RHS value is > UnsignedMax, fold the comparison. This handles |
| 5510 | // +INF and large values. |
| 5511 | APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false); |
| 5512 | UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, |
| 5513 | APFloat::rmNearestTiesToEven); |
| 5514 | if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 |
| 5515 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || |
| 5516 | Pred == ICmpInst::ICMP_ULE) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5517 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5518 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5519 | } |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5520 | } |
| 5521 | |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5522 | if (!LHSUnsigned) { |
| 5523 | // See if the RHS value is < SignedMin. |
| 5524 | APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false); |
| 5525 | SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, |
| 5526 | APFloat::rmNearestTiesToEven); |
| 5527 | if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 |
| 5528 | if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || |
| 5529 | Pred == ICmpInst::ICMP_SGE) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5530 | return ReplaceInstUsesWith(I,ConstantInt::getTrue()); |
| 5531 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5532 | } |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5533 | } |
| 5534 | |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5535 | // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or |
| 5536 | // [0, UMAX], but it may still be fractional. See if it is fractional by |
| 5537 | // casting the FP value to the integer value and back, checking for equality. |
| 5538 | // Don't do this for zero, because -0.0 is not fractional. |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5539 | Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy); |
| 5540 | if (!RHS.isZero() && |
| 5541 | ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) { |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5542 | // If we had a comparison against a fractional value, we have to adjust the |
| 5543 | // compare predicate and sometimes the value. RHSC is rounded towards zero |
| 5544 | // at this point. |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5545 | switch (Pred) { |
| 5546 | default: assert(0 && "Unexpected integer comparison!"); |
| 5547 | case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5548 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5549 | case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5550 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5551 | case ICmpInst::ICMP_ULE: |
| 5552 | // (float)int <= 4.4 --> int <= 4 |
| 5553 | // (float)int <= -4.4 --> false |
| 5554 | if (RHS.isNegative()) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5555 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5556 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5557 | case ICmpInst::ICMP_SLE: |
| 5558 | // (float)int <= 4.4 --> int <= 4 |
| 5559 | // (float)int <= -4.4 --> int < -4 |
| 5560 | if (RHS.isNegative()) |
| 5561 | Pred = ICmpInst::ICMP_SLT; |
| 5562 | break; |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5563 | case ICmpInst::ICMP_ULT: |
| 5564 | // (float)int < -4.4 --> false |
| 5565 | // (float)int < 4.4 --> int <= 4 |
| 5566 | if (RHS.isNegative()) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5567 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5568 | Pred = ICmpInst::ICMP_ULE; |
| 5569 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5570 | case ICmpInst::ICMP_SLT: |
| 5571 | // (float)int < -4.4 --> int < -4 |
| 5572 | // (float)int < 4.4 --> int <= 4 |
| 5573 | if (!RHS.isNegative()) |
| 5574 | Pred = ICmpInst::ICMP_SLE; |
| 5575 | break; |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5576 | case ICmpInst::ICMP_UGT: |
| 5577 | // (float)int > 4.4 --> int > 4 |
| 5578 | // (float)int > -4.4 --> true |
| 5579 | if (RHS.isNegative()) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5580 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5581 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5582 | case ICmpInst::ICMP_SGT: |
| 5583 | // (float)int > 4.4 --> int > 4 |
| 5584 | // (float)int > -4.4 --> int >= -4 |
| 5585 | if (RHS.isNegative()) |
| 5586 | Pred = ICmpInst::ICMP_SGE; |
| 5587 | break; |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5588 | case ICmpInst::ICMP_UGE: |
| 5589 | // (float)int >= -4.4 --> true |
| 5590 | // (float)int >= 4.4 --> int > 4 |
| 5591 | if (!RHS.isNegative()) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5592 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Bill Wendling | 20636df | 2008-11-09 04:26:50 +0000 | [diff] [blame] | 5593 | Pred = ICmpInst::ICMP_UGT; |
| 5594 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5595 | case ICmpInst::ICMP_SGE: |
| 5596 | // (float)int >= -4.4 --> int >= -4 |
| 5597 | // (float)int >= 4.4 --> int > 4 |
| 5598 | if (!RHS.isNegative()) |
| 5599 | Pred = ICmpInst::ICMP_SGT; |
| 5600 | break; |
| 5601 | } |
| 5602 | } |
| 5603 | |
| 5604 | // Lower this FP comparison into an appropriate integer version of the |
| 5605 | // comparison. |
| 5606 | return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); |
| 5607 | } |
| 5608 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5609 | Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { |
| 5610 | bool Changed = SimplifyCompare(I); |
| 5611 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 5612 | |
| 5613 | // Fold trivial predicates. |
| 5614 | if (I.getPredicate() == FCmpInst::FCMP_FALSE) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5615 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5616 | if (I.getPredicate() == FCmpInst::FCMP_TRUE) |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5617 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5618 | |
| 5619 | // Simplify 'fcmp pred X, X' |
| 5620 | if (Op0 == Op1) { |
| 5621 | switch (I.getPredicate()) { |
| 5622 | default: assert(0 && "Unknown predicate!"); |
| 5623 | case FCmpInst::FCMP_UEQ: // True if unordered or equal |
| 5624 | case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal |
| 5625 | case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5626 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5627 | case FCmpInst::FCMP_OGT: // True if ordered and greater than |
| 5628 | case FCmpInst::FCMP_OLT: // True if ordered and less than |
| 5629 | case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5630 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5631 | |
| 5632 | case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) |
| 5633 | case FCmpInst::FCMP_ULT: // True if unordered or less than |
| 5634 | case FCmpInst::FCMP_UGT: // True if unordered or greater than |
| 5635 | case FCmpInst::FCMP_UNE: // True if unordered or not equal |
| 5636 | // Canonicalize these to be 'fcmp uno %X, 0.0'. |
| 5637 | I.setPredicate(FCmpInst::FCMP_UNO); |
| 5638 | I.setOperand(1, Constant::getNullValue(Op0->getType())); |
| 5639 | return &I; |
| 5640 | |
| 5641 | case FCmpInst::FCMP_ORD: // True if ordered (no nans) |
| 5642 | case FCmpInst::FCMP_OEQ: // True if ordered and equal |
| 5643 | case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal |
| 5644 | case FCmpInst::FCMP_OLE: // True if ordered and less than or equal |
| 5645 | // Canonicalize these to be 'fcmp ord %X, 0.0'. |
| 5646 | I.setPredicate(FCmpInst::FCMP_ORD); |
| 5647 | I.setOperand(1, Constant::getNullValue(Op0->getType())); |
| 5648 | return &I; |
| 5649 | } |
| 5650 | } |
| 5651 | |
| 5652 | if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef |
| 5653 | return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty)); |
| 5654 | |
| 5655 | // Handle fcmp with constant RHS |
| 5656 | if (Constant *RHSC = dyn_cast<Constant>(Op1)) { |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5657 | // If the constant is a nan, see if we can fold the comparison based on it. |
| 5658 | if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) { |
| 5659 | if (CFP->getValueAPF().isNaN()) { |
| 5660 | if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and... |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5661 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | f13ff49 | 2008-05-20 03:50:52 +0000 | [diff] [blame] | 5662 | assert(FCmpInst::isUnordered(I.getPredicate()) && |
| 5663 | "Comparison must be either ordered or unordered!"); |
| 5664 | // True if unordered. |
Eli Friedman | c9c9624 | 2008-11-30 22:48:49 +0000 | [diff] [blame] | 5665 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5666 | } |
| 5667 | } |
| 5668 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5669 | if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) |
| 5670 | switch (LHSI->getOpcode()) { |
| 5671 | case Instruction::PHI: |
Chris Lattner | a2417ba | 2008-06-08 20:52:11 +0000 | [diff] [blame] | 5672 | // Only fold fcmp into the PHI if the phi and fcmp are in the same |
| 5673 | // block. If in the same block, we're encouraging jump threading. If |
| 5674 | // not, we are just pessimizing the code by making an i1 phi. |
| 5675 | if (LHSI->getParent() == I.getParent()) |
| 5676 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 5677 | return NV; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5678 | break; |
Chris Lattner | e6b62d9 | 2008-05-19 20:18:56 +0000 | [diff] [blame] | 5679 | case Instruction::SIToFP: |
| 5680 | case Instruction::UIToFP: |
| 5681 | if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) |
| 5682 | return NV; |
| 5683 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5684 | case Instruction::Select: |
| 5685 | // If either operand of the select is a constant, we can fold the |
| 5686 | // comparison into the select arms, which will cause one to be |
| 5687 | // constant folded and the select turned into a bitwise or. |
| 5688 | Value *Op1 = 0, *Op2 = 0; |
| 5689 | if (LHSI->hasOneUse()) { |
| 5690 | if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { |
| 5691 | // Fold the known value into the constant operand. |
| 5692 | Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); |
| 5693 | // Insert a new FCmp of the other select operand. |
| 5694 | Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(), |
| 5695 | LHSI->getOperand(2), RHSC, |
| 5696 | I.getName()), I); |
| 5697 | } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { |
| 5698 | // Fold the known value into the constant operand. |
| 5699 | Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); |
| 5700 | // Insert a new FCmp of the other select operand. |
| 5701 | Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(), |
| 5702 | LHSI->getOperand(1), RHSC, |
| 5703 | I.getName()), I); |
| 5704 | } |
| 5705 | } |
| 5706 | |
| 5707 | if (Op1) |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 5708 | return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5709 | break; |
| 5710 | } |
| 5711 | } |
| 5712 | |
| 5713 | return Changed ? &I : 0; |
| 5714 | } |
| 5715 | |
| 5716 | Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { |
| 5717 | bool Changed = SimplifyCompare(I); |
| 5718 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 5719 | const Type *Ty = Op0->getType(); |
| 5720 | |
| 5721 | // icmp X, X |
| 5722 | if (Op0 == Op1) |
| 5723 | return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, |
Nick Lewycky | 09284cf | 2008-05-17 07:33:39 +0000 | [diff] [blame] | 5724 | I.isTrueWhenEqual())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5725 | |
| 5726 | if (isa<UndefValue>(Op1)) // X icmp undef -> undef |
| 5727 | return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty)); |
Christopher Lamb | f78cd32 | 2007-12-18 21:32:20 +0000 | [diff] [blame] | 5728 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5729 | // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value |
| 5730 | // addresses never equal each other! We already know that Op0 != Op1. |
| 5731 | if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || |
| 5732 | isa<ConstantPointerNull>(Op0)) && |
| 5733 | (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || |
| 5734 | isa<ConstantPointerNull>(Op1))) |
| 5735 | return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, |
Nick Lewycky | 09284cf | 2008-05-17 07:33:39 +0000 | [diff] [blame] | 5736 | !I.isTrueWhenEqual())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5737 | |
| 5738 | // icmp's with boolean values can always be turned into bitwise operations |
| 5739 | if (Ty == Type::Int1Ty) { |
| 5740 | switch (I.getPredicate()) { |
| 5741 | default: assert(0 && "Invalid icmp instruction!"); |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5742 | case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5743 | Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5744 | InsertNewInstBefore(Xor, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5745 | return BinaryOperator::CreateNot(Xor); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5746 | } |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5747 | case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5748 | return BinaryOperator::CreateXor(Op0, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5749 | |
| 5750 | case ICmpInst::ICMP_UGT: |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5751 | std::swap(Op0, Op1); // Change icmp ugt -> icmp ult |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5752 | // FALL THROUGH |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5753 | case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5754 | Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5755 | InsertNewInstBefore(Not, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5756 | return BinaryOperator::CreateAnd(Not, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5757 | } |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5758 | case ICmpInst::ICMP_SGT: |
| 5759 | std::swap(Op0, Op1); // Change icmp sgt -> icmp slt |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5760 | // FALL THROUGH |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5761 | case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B |
| 5762 | Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp"); |
| 5763 | InsertNewInstBefore(Not, I); |
| 5764 | return BinaryOperator::CreateAnd(Not, Op0); |
| 5765 | } |
| 5766 | case ICmpInst::ICMP_UGE: |
| 5767 | std::swap(Op0, Op1); // Change icmp uge -> icmp ule |
| 5768 | // FALL THROUGH |
| 5769 | case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5770 | Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5771 | InsertNewInstBefore(Not, I); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 5772 | return BinaryOperator::CreateOr(Not, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5773 | } |
Chris Lattner | a02893d | 2008-07-11 04:20:58 +0000 | [diff] [blame] | 5774 | case ICmpInst::ICMP_SGE: |
| 5775 | std::swap(Op0, Op1); // Change icmp sge -> icmp sle |
| 5776 | // FALL THROUGH |
| 5777 | case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B |
| 5778 | Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp"); |
| 5779 | InsertNewInstBefore(Not, I); |
| 5780 | return BinaryOperator::CreateOr(Not, Op0); |
| 5781 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5782 | } |
| 5783 | } |
| 5784 | |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 5785 | // See if we are doing a comparison with a constant. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5786 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { |
Chris Lattner | 3d81653 | 2008-07-11 04:09:09 +0000 | [diff] [blame] | 5787 | Value *A, *B; |
Christopher Lamb | fa6b310 | 2007-12-20 07:21:11 +0000 | [diff] [blame] | 5788 | |
Chris Lattner | be6c54a | 2008-01-05 01:18:20 +0000 | [diff] [blame] | 5789 | // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B) |
| 5790 | if (I.isEquality() && CI->isNullValue() && |
| 5791 | match(Op0, m_Sub(m_Value(A), m_Value(B)))) { |
| 5792 | // (icmp cond A B) if cond is equality |
| 5793 | return new ICmpInst(I.getPredicate(), A, B); |
Owen Anderson | 42f61ed | 2007-12-28 07:42:12 +0000 | [diff] [blame] | 5794 | } |
Christopher Lamb | fa6b310 | 2007-12-20 07:21:11 +0000 | [diff] [blame] | 5795 | |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 5796 | // If we have an icmp le or icmp ge instruction, turn it into the |
| 5797 | // appropriate icmp lt or icmp gt instruction. This allows us to rely on |
| 5798 | // them being folded in the code below. |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5799 | switch (I.getPredicate()) { |
| 5800 | default: break; |
| 5801 | case ICmpInst::ICMP_ULE: |
| 5802 | if (CI->isMaxValue(false)) // A <=u MAX -> TRUE |
| 5803 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5804 | return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI)); |
| 5805 | case ICmpInst::ICMP_SLE: |
| 5806 | if (CI->isMaxValue(true)) // A <=s MAX -> TRUE |
| 5807 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5808 | return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI)); |
| 5809 | case ICmpInst::ICMP_UGE: |
| 5810 | if (CI->isMinValue(false)) // A >=u MIN -> TRUE |
| 5811 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5812 | return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI)); |
| 5813 | case ICmpInst::ICMP_SGE: |
| 5814 | if (CI->isMinValue(true)) // A >=s MIN -> TRUE |
| 5815 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5816 | return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI)); |
| 5817 | } |
| 5818 | |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5819 | // See if we can fold the comparison based on range information we can get |
| 5820 | // by checking whether bits are known to be zero or one in the input. |
| 5821 | uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); |
| 5822 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 5823 | |
| 5824 | // If this comparison is a normal comparison, it demands all |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5825 | // bits, if it is a sign bit comparison, it only demands the sign bit. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5826 | bool UnusedBit; |
| 5827 | bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit); |
| 5828 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5829 | if (SimplifyDemandedBits(Op0, |
| 5830 | isSignBit ? APInt::getSignBit(BitWidth) |
| 5831 | : APInt::getAllOnesValue(BitWidth), |
| 5832 | KnownZero, KnownOne, 0)) |
| 5833 | return &I; |
| 5834 | |
| 5835 | // Given the known and unknown bits, compute a range that the LHS could be |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5836 | // in. Compute the Min, Max and RHS values based on the known bits. For the |
| 5837 | // EQ and NE we use unsigned values. |
| 5838 | APInt Min(BitWidth, 0), Max(BitWidth, 0); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5839 | if (ICmpInst::isSignedPredicate(I.getPredicate())) |
| 5840 | ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max); |
| 5841 | else |
| 5842 | ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max); |
| 5843 | |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5844 | // If Min and Max are known to be the same, then SimplifyDemandedBits |
| 5845 | // figured out that the LHS is a constant. Just constant fold this now so |
| 5846 | // that code below can assume that Min != Max. |
| 5847 | if (Min == Max) |
| 5848 | return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(), |
| 5849 | ConstantInt::get(Min), |
| 5850 | CI)); |
| 5851 | |
| 5852 | // Based on the range information we know about the LHS, see if we can |
| 5853 | // simplify this comparison. For example, (x&4) < 8 is always true. |
| 5854 | const APInt &RHSVal = CI->getValue(); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5855 | switch (I.getPredicate()) { // LE/GE have been folded already. |
| 5856 | default: assert(0 && "Unknown icmp opcode!"); |
| 5857 | case ICmpInst::ICMP_EQ: |
| 5858 | if (Max.ult(RHSVal) || Min.ugt(RHSVal)) |
| 5859 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
| 5860 | break; |
| 5861 | case ICmpInst::ICMP_NE: |
| 5862 | if (Max.ult(RHSVal) || Min.ugt(RHSVal)) |
| 5863 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
| 5864 | break; |
| 5865 | case ICmpInst::ICMP_ULT: |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5866 | if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5867 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5868 | if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5869 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5870 | if (RHSVal == Max) // A <u MAX -> A != MAX |
| 5871 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 5872 | if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN |
| 5873 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI)); |
| 5874 | |
| 5875 | // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear |
| 5876 | if (CI->isMinValue(true)) |
| 5877 | return new ICmpInst(ICmpInst::ICMP_SGT, Op0, |
| 5878 | ConstantInt::getAllOnesValue(Op0->getType())); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5879 | break; |
| 5880 | case ICmpInst::ICMP_UGT: |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5881 | if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5882 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5883 | if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5884 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5885 | |
| 5886 | if (RHSVal == Min) // A >u MIN -> A != MIN |
| 5887 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 5888 | if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX |
| 5889 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI)); |
| 5890 | |
| 5891 | // (x >u 2147483647) -> (x <s 0) -> true if sign bit set |
| 5892 | if (CI->isMaxValue(true)) |
| 5893 | return new ICmpInst(ICmpInst::ICMP_SLT, Op0, |
| 5894 | ConstantInt::getNullValue(Op0->getType())); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5895 | break; |
| 5896 | case ICmpInst::ICMP_SLT: |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5897 | if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5898 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | 611b43e | 2008-07-11 06:40:29 +0000 | [diff] [blame] | 5899 | if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5900 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5901 | if (RHSVal == Max) // A <s MAX -> A != MAX |
| 5902 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
Chris Lattner | 3496f3e | 2008-07-11 06:36:01 +0000 | [diff] [blame] | 5903 | if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN |
Chris Lattner | 55ab315 | 2008-07-11 06:38:16 +0000 | [diff] [blame] | 5904 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI)); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5905 | break; |
| 5906 | case ICmpInst::ICMP_SGT: |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5907 | if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5908 | return ReplaceInstUsesWith(I, ConstantInt::getTrue()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5909 | if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5910 | return ReplaceInstUsesWith(I, ConstantInt::getFalse()); |
Chris Lattner | a130865 | 2008-07-11 05:40:05 +0000 | [diff] [blame] | 5911 | |
| 5912 | if (RHSVal == Min) // A >s MIN -> A != MIN |
| 5913 | return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); |
| 5914 | if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX |
| 5915 | return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI)); |
Chris Lattner | 62d0f23 | 2008-07-11 05:08:55 +0000 | [diff] [blame] | 5916 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5917 | } |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 5918 | } |
| 5919 | |
| 5920 | // Test if the ICmpInst instruction is used exclusively by a select as |
| 5921 | // part of a minimum or maximum operation. If so, refrain from doing |
| 5922 | // any other folding. This helps out other analyses which understand |
| 5923 | // non-obfuscated minimum and maximum idioms, such as ScalarEvolution |
| 5924 | // and CodeGen. And in this case, at least one of the comparison |
| 5925 | // operands has at least one user besides the compare (the select), |
| 5926 | // which would often largely negate the benefit of folding anyway. |
| 5927 | if (I.hasOneUse()) |
| 5928 | if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin())) |
| 5929 | if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || |
| 5930 | (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) |
| 5931 | return 0; |
| 5932 | |
| 5933 | // See if we are doing a comparison between a constant and an instruction that |
| 5934 | // can be folded into the comparison. |
| 5935 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5936 | // Since the RHS is a ConstantInt (CI), if the left hand side is an |
| 5937 | // instruction, see if that instruction also has constants so that the |
| 5938 | // instruction can be folded into the icmp |
| 5939 | if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) |
| 5940 | if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI)) |
| 5941 | return Res; |
| 5942 | } |
| 5943 | |
| 5944 | // Handle icmp with constant (but not simple integer constant) RHS |
| 5945 | if (Constant *RHSC = dyn_cast<Constant>(Op1)) { |
| 5946 | if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) |
| 5947 | switch (LHSI->getOpcode()) { |
| 5948 | case Instruction::GetElementPtr: |
| 5949 | if (RHSC->isNullValue()) { |
| 5950 | // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null |
| 5951 | bool isAllZeros = true; |
| 5952 | for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i) |
| 5953 | if (!isa<Constant>(LHSI->getOperand(i)) || |
| 5954 | !cast<Constant>(LHSI->getOperand(i))->isNullValue()) { |
| 5955 | isAllZeros = false; |
| 5956 | break; |
| 5957 | } |
| 5958 | if (isAllZeros) |
| 5959 | return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), |
| 5960 | Constant::getNullValue(LHSI->getOperand(0)->getType())); |
| 5961 | } |
| 5962 | break; |
| 5963 | |
| 5964 | case Instruction::PHI: |
Chris Lattner | a2417ba | 2008-06-08 20:52:11 +0000 | [diff] [blame] | 5965 | // Only fold icmp into the PHI if the phi and fcmp are in the same |
| 5966 | // block. If in the same block, we're encouraging jump threading. If |
| 5967 | // not, we are just pessimizing the code by making an i1 phi. |
| 5968 | if (LHSI->getParent() == I.getParent()) |
| 5969 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 5970 | return NV; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5971 | break; |
| 5972 | case Instruction::Select: { |
| 5973 | // If either operand of the select is a constant, we can fold the |
| 5974 | // comparison into the select arms, which will cause one to be |
| 5975 | // constant folded and the select turned into a bitwise or. |
| 5976 | Value *Op1 = 0, *Op2 = 0; |
| 5977 | if (LHSI->hasOneUse()) { |
| 5978 | if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { |
| 5979 | // Fold the known value into the constant operand. |
| 5980 | Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); |
| 5981 | // Insert a new ICmp of the other select operand. |
| 5982 | Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(), |
| 5983 | LHSI->getOperand(2), RHSC, |
| 5984 | I.getName()), I); |
| 5985 | } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { |
| 5986 | // Fold the known value into the constant operand. |
| 5987 | Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); |
| 5988 | // Insert a new ICmp of the other select operand. |
| 5989 | Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(), |
| 5990 | LHSI->getOperand(1), RHSC, |
| 5991 | I.getName()), I); |
| 5992 | } |
| 5993 | } |
| 5994 | |
| 5995 | if (Op1) |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 5996 | return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 5997 | break; |
| 5998 | } |
| 5999 | case Instruction::Malloc: |
| 6000 | // If we have (malloc != null), and if the malloc has a single use, we |
| 6001 | // can assume it is successful and remove the malloc. |
| 6002 | if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) { |
| 6003 | AddToWorkList(LHSI); |
| 6004 | return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, |
Nick Lewycky | 09284cf | 2008-05-17 07:33:39 +0000 | [diff] [blame] | 6005 | !I.isTrueWhenEqual())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6006 | } |
| 6007 | break; |
| 6008 | } |
| 6009 | } |
| 6010 | |
| 6011 | // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. |
| 6012 | if (User *GEP = dyn_castGetElementPtr(Op0)) |
| 6013 | if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I)) |
| 6014 | return NI; |
| 6015 | if (User *GEP = dyn_castGetElementPtr(Op1)) |
| 6016 | if (Instruction *NI = FoldGEPICmp(GEP, Op0, |
| 6017 | ICmpInst::getSwappedPredicate(I.getPredicate()), I)) |
| 6018 | return NI; |
| 6019 | |
| 6020 | // Test to see if the operands of the icmp are casted versions of other |
| 6021 | // values. If the ptr->ptr cast can be stripped off both arguments, we do so |
| 6022 | // now. |
| 6023 | if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { |
| 6024 | if (isa<PointerType>(Op0->getType()) && |
| 6025 | (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { |
| 6026 | // We keep moving the cast from the left operand over to the right |
| 6027 | // operand, where it can often be eliminated completely. |
| 6028 | Op0 = CI->getOperand(0); |
| 6029 | |
| 6030 | // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast |
| 6031 | // so eliminate it as well. |
| 6032 | if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) |
| 6033 | Op1 = CI2->getOperand(0); |
| 6034 | |
| 6035 | // If Op1 is a constant, we can fold the cast into the constant. |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 6036 | if (Op0->getType() != Op1->getType()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6037 | if (Constant *Op1C = dyn_cast<Constant>(Op1)) { |
| 6038 | Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); |
| 6039 | } else { |
| 6040 | // Otherwise, cast the RHS right before the icmp |
Chris Lattner | 13c2d6e | 2008-01-13 22:23:22 +0000 | [diff] [blame] | 6041 | Op1 = InsertBitCastBefore(Op1, Op0->getType(), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6042 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 6043 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6044 | return new ICmpInst(I.getPredicate(), Op0, Op1); |
| 6045 | } |
| 6046 | } |
| 6047 | |
| 6048 | if (isa<CastInst>(Op0)) { |
| 6049 | // Handle the special case of: icmp (cast bool to X), <cst> |
| 6050 | // This comes up when you have code like |
| 6051 | // int X = A < B; |
| 6052 | // if (X) ... |
| 6053 | // For generality, we handle any zero-extension of any operand comparison |
| 6054 | // with a constant or another cast from the same type. |
| 6055 | if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1)) |
| 6056 | if (Instruction *R = visitICmpInstWithCastAndCast(I)) |
| 6057 | return R; |
| 6058 | } |
| 6059 | |
Nick Lewycky | d4c5ea0 | 2008-07-11 07:20:53 +0000 | [diff] [blame] | 6060 | // See if it's the same type of instruction on the left and right. |
| 6061 | if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) { |
| 6062 | if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) { |
Nick Lewycky | 58ecfb2 | 2008-08-21 05:56:10 +0000 | [diff] [blame] | 6063 | if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() && |
| 6064 | Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) && |
| 6065 | I.isEquality()) { |
Nick Lewycky | cfadfbd | 2008-09-03 06:24:21 +0000 | [diff] [blame] | 6066 | switch (Op0I->getOpcode()) { |
Nick Lewycky | d4c5ea0 | 2008-07-11 07:20:53 +0000 | [diff] [blame] | 6067 | default: break; |
| 6068 | case Instruction::Add: |
| 6069 | case Instruction::Sub: |
| 6070 | case Instruction::Xor: |
Nick Lewycky | 58ecfb2 | 2008-08-21 05:56:10 +0000 | [diff] [blame] | 6071 | // a+x icmp eq/ne b+x --> a icmp b |
| 6072 | return new ICmpInst(I.getPredicate(), Op0I->getOperand(0), |
| 6073 | Op1I->getOperand(0)); |
Nick Lewycky | d4c5ea0 | 2008-07-11 07:20:53 +0000 | [diff] [blame] | 6074 | break; |
| 6075 | case Instruction::Mul: |
Nick Lewycky | 58ecfb2 | 2008-08-21 05:56:10 +0000 | [diff] [blame] | 6076 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) { |
| 6077 | // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask |
| 6078 | // Mask = -1 >> count-trailing-zeros(Cst). |
| 6079 | if (!CI->isZero() && !CI->isOne()) { |
| 6080 | const APInt &AP = CI->getValue(); |
| 6081 | ConstantInt *Mask = ConstantInt::get( |
| 6082 | APInt::getLowBitsSet(AP.getBitWidth(), |
| 6083 | AP.getBitWidth() - |
Nick Lewycky | d4c5ea0 | 2008-07-11 07:20:53 +0000 | [diff] [blame] | 6084 | AP.countTrailingZeros())); |
Nick Lewycky | 58ecfb2 | 2008-08-21 05:56:10 +0000 | [diff] [blame] | 6085 | Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0), |
| 6086 | Mask); |
| 6087 | Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0), |
| 6088 | Mask); |
| 6089 | InsertNewInstBefore(And1, I); |
| 6090 | InsertNewInstBefore(And2, I); |
| 6091 | return new ICmpInst(I.getPredicate(), And1, And2); |
Nick Lewycky | d4c5ea0 | 2008-07-11 07:20:53 +0000 | [diff] [blame] | 6092 | } |
| 6093 | } |
| 6094 | break; |
| 6095 | } |
| 6096 | } |
| 6097 | } |
| 6098 | } |
| 6099 | |
Chris Lattner | a4e1eef | 2008-05-09 05:19:28 +0000 | [diff] [blame] | 6100 | // ~x < ~y --> y < x |
| 6101 | { Value *A, *B; |
| 6102 | if (match(Op0, m_Not(m_Value(A))) && |
| 6103 | match(Op1, m_Not(m_Value(B)))) |
| 6104 | return new ICmpInst(I.getPredicate(), B, A); |
| 6105 | } |
| 6106 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6107 | if (I.isEquality()) { |
| 6108 | Value *A, *B, *C, *D; |
Chris Lattner | a4e1eef | 2008-05-09 05:19:28 +0000 | [diff] [blame] | 6109 | |
| 6110 | // -x == -y --> x == y |
| 6111 | if (match(Op0, m_Neg(m_Value(A))) && |
| 6112 | match(Op1, m_Neg(m_Value(B)))) |
| 6113 | return new ICmpInst(I.getPredicate(), A, B); |
| 6114 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6115 | if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { |
| 6116 | if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 |
| 6117 | Value *OtherVal = A == Op1 ? B : A; |
| 6118 | return new ICmpInst(I.getPredicate(), OtherVal, |
| 6119 | Constant::getNullValue(A->getType())); |
| 6120 | } |
| 6121 | |
| 6122 | if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { |
| 6123 | // A^c1 == C^c2 --> A == C^(c1^c2) |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 6124 | ConstantInt *C1, *C2; |
| 6125 | if (match(B, m_ConstantInt(C1)) && |
| 6126 | match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) { |
| 6127 | Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue()); |
| 6128 | Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp"); |
| 6129 | return new ICmpInst(I.getPredicate(), A, |
| 6130 | InsertNewInstBefore(Xor, I)); |
| 6131 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6132 | |
| 6133 | // A^B == A^D -> B == D |
| 6134 | if (A == C) return new ICmpInst(I.getPredicate(), B, D); |
| 6135 | if (A == D) return new ICmpInst(I.getPredicate(), B, C); |
| 6136 | if (B == C) return new ICmpInst(I.getPredicate(), A, D); |
| 6137 | if (B == D) return new ICmpInst(I.getPredicate(), A, C); |
| 6138 | } |
| 6139 | } |
| 6140 | |
| 6141 | if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && |
| 6142 | (A == Op0 || B == Op0)) { |
| 6143 | // A == (A^B) -> B == 0 |
| 6144 | Value *OtherVal = A == Op0 ? B : A; |
| 6145 | return new ICmpInst(I.getPredicate(), OtherVal, |
| 6146 | Constant::getNullValue(A->getType())); |
| 6147 | } |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 6148 | |
| 6149 | // (A-B) == A -> B == 0 |
| 6150 | if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)))) |
| 6151 | return new ICmpInst(I.getPredicate(), B, |
| 6152 | Constant::getNullValue(B->getType())); |
| 6153 | |
| 6154 | // A == (A-B) -> B == 0 |
| 6155 | if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)))) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6156 | return new ICmpInst(I.getPredicate(), B, |
| 6157 | Constant::getNullValue(B->getType())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6158 | |
| 6159 | // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 |
| 6160 | if (Op0->hasOneUse() && Op1->hasOneUse() && |
| 6161 | match(Op0, m_And(m_Value(A), m_Value(B))) && |
| 6162 | match(Op1, m_And(m_Value(C), m_Value(D)))) { |
| 6163 | Value *X = 0, *Y = 0, *Z = 0; |
| 6164 | |
| 6165 | if (A == C) { |
| 6166 | X = B; Y = D; Z = A; |
| 6167 | } else if (A == D) { |
| 6168 | X = B; Y = C; Z = A; |
| 6169 | } else if (B == C) { |
| 6170 | X = A; Y = D; Z = B; |
| 6171 | } else if (B == D) { |
| 6172 | X = A; Y = C; Z = B; |
| 6173 | } |
| 6174 | |
| 6175 | if (X) { // Build (X^Y) & Z |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6176 | Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I); |
| 6177 | Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6178 | I.setOperand(0, Op1); |
| 6179 | I.setOperand(1, Constant::getNullValue(Op1->getType())); |
| 6180 | return &I; |
| 6181 | } |
| 6182 | } |
| 6183 | } |
| 6184 | return Changed ? &I : 0; |
| 6185 | } |
| 6186 | |
| 6187 | |
| 6188 | /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS |
| 6189 | /// and CmpRHS are both known to be integer constants. |
| 6190 | Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, |
| 6191 | ConstantInt *DivRHS) { |
| 6192 | ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1)); |
| 6193 | const APInt &CmpRHSV = CmpRHS->getValue(); |
| 6194 | |
| 6195 | // FIXME: If the operand types don't match the type of the divide |
| 6196 | // then don't attempt this transform. The code below doesn't have the |
| 6197 | // logic to deal with a signed divide and an unsigned compare (and |
| 6198 | // vice versa). This is because (x /s C1) <s C2 produces different |
| 6199 | // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even |
| 6200 | // (x /u C1) <u C2. Simply casting the operands and result won't |
| 6201 | // work. :( The if statement below tests that condition and bails |
| 6202 | // if it finds it. |
| 6203 | bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv; |
| 6204 | if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate()) |
| 6205 | return 0; |
| 6206 | if (DivRHS->isZero()) |
| 6207 | return 0; // The ProdOV computation fails on divide by zero. |
Chris Lattner | bd85a5f | 2008-10-11 22:55:00 +0000 | [diff] [blame] | 6208 | if (DivIsSigned && DivRHS->isAllOnesValue()) |
| 6209 | return 0; // The overflow computation also screws up here |
| 6210 | if (DivRHS->isOne()) |
| 6211 | return 0; // Not worth bothering, and eliminates some funny cases |
| 6212 | // with INT_MIN. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6213 | |
| 6214 | // Compute Prod = CI * DivRHS. We are essentially solving an equation |
| 6215 | // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and |
| 6216 | // C2 (CI). By solving for X we can turn this into a range check |
| 6217 | // instead of computing a divide. |
| 6218 | ConstantInt *Prod = Multiply(CmpRHS, DivRHS); |
| 6219 | |
| 6220 | // Determine if the product overflows by seeing if the product is |
| 6221 | // not equal to the divide. Make sure we do the same kind of divide |
| 6222 | // as in the LHS instruction that we're folding. |
| 6223 | bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) : |
| 6224 | ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; |
| 6225 | |
| 6226 | // Get the ICmp opcode |
| 6227 | ICmpInst::Predicate Pred = ICI.getPredicate(); |
| 6228 | |
| 6229 | // Figure out the interval that is being checked. For example, a comparison |
| 6230 | // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). |
| 6231 | // Compute this interval based on the constants involved and the signedness of |
| 6232 | // the compare/divide. This computes a half-open interval, keeping track of |
| 6233 | // whether either value in the interval overflows. After analysis each |
| 6234 | // overflow variable is set to 0 if it's corresponding bound variable is valid |
| 6235 | // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. |
| 6236 | int LoOverflow = 0, HiOverflow = 0; |
| 6237 | ConstantInt *LoBound = 0, *HiBound = 0; |
| 6238 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6239 | if (!DivIsSigned) { // udiv |
| 6240 | // e.g. X/5 op 3 --> [15, 20) |
| 6241 | LoBound = Prod; |
| 6242 | HiOverflow = LoOverflow = ProdOV; |
| 6243 | if (!HiOverflow) |
| 6244 | HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false); |
Dan Gohman | 5dceed1 | 2008-02-13 22:09:18 +0000 | [diff] [blame] | 6245 | } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6246 | if (CmpRHSV == 0) { // (X / pos) op 0 |
| 6247 | // Can't overflow. e.g. X/2 op 0 --> [-1, 2) |
| 6248 | LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS))); |
| 6249 | HiBound = DivRHS; |
Dan Gohman | 5dceed1 | 2008-02-13 22:09:18 +0000 | [diff] [blame] | 6250 | } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6251 | LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) |
| 6252 | HiOverflow = LoOverflow = ProdOV; |
| 6253 | if (!HiOverflow) |
| 6254 | HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true); |
| 6255 | } else { // (X / pos) op neg |
| 6256 | // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6257 | HiBound = AddOne(Prod); |
Chris Lattner | bd85a5f | 2008-10-11 22:55:00 +0000 | [diff] [blame] | 6258 | LoOverflow = HiOverflow = ProdOV ? -1 : 0; |
| 6259 | if (!LoOverflow) { |
| 6260 | ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS)); |
| 6261 | LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, |
| 6262 | true) ? -1 : 0; |
| 6263 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6264 | } |
Dan Gohman | 5dceed1 | 2008-02-13 22:09:18 +0000 | [diff] [blame] | 6265 | } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6266 | if (CmpRHSV == 0) { // (X / neg) op 0 |
| 6267 | // e.g. X/-5 op 0 --> [-4, 5) |
| 6268 | LoBound = AddOne(DivRHS); |
| 6269 | HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS)); |
| 6270 | if (HiBound == DivRHS) { // -INTMIN = INTMIN |
| 6271 | HiOverflow = 1; // [INTMIN+1, overflow) |
| 6272 | HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN |
| 6273 | } |
Dan Gohman | 5dceed1 | 2008-02-13 22:09:18 +0000 | [diff] [blame] | 6274 | } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6275 | // e.g. X/-5 op 3 --> [-19, -14) |
Chris Lattner | bd85a5f | 2008-10-11 22:55:00 +0000 | [diff] [blame] | 6276 | HiBound = AddOne(Prod); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6277 | HiOverflow = LoOverflow = ProdOV ? -1 : 0; |
| 6278 | if (!LoOverflow) |
Chris Lattner | bd85a5f | 2008-10-11 22:55:00 +0000 | [diff] [blame] | 6279 | LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6280 | } else { // (X / neg) op neg |
Chris Lattner | bd85a5f | 2008-10-11 22:55:00 +0000 | [diff] [blame] | 6281 | LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) |
| 6282 | LoOverflow = HiOverflow = ProdOV; |
Dan Gohman | 45408ea | 2008-09-11 00:25:00 +0000 | [diff] [blame] | 6283 | if (!HiOverflow) |
| 6284 | HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6285 | } |
| 6286 | |
| 6287 | // Dividing by a negative swaps the condition. LT <-> GT |
| 6288 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 6289 | } |
| 6290 | |
| 6291 | Value *X = DivI->getOperand(0); |
| 6292 | switch (Pred) { |
| 6293 | default: assert(0 && "Unhandled icmp opcode!"); |
| 6294 | case ICmpInst::ICMP_EQ: |
| 6295 | if (LoOverflow && HiOverflow) |
| 6296 | return ReplaceInstUsesWith(ICI, ConstantInt::getFalse()); |
| 6297 | else if (HiOverflow) |
| 6298 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : |
| 6299 | ICmpInst::ICMP_UGE, X, LoBound); |
| 6300 | else if (LoOverflow) |
| 6301 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : |
| 6302 | ICmpInst::ICMP_ULT, X, HiBound); |
| 6303 | else |
| 6304 | return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI); |
| 6305 | case ICmpInst::ICMP_NE: |
| 6306 | if (LoOverflow && HiOverflow) |
| 6307 | return ReplaceInstUsesWith(ICI, ConstantInt::getTrue()); |
| 6308 | else if (HiOverflow) |
| 6309 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : |
| 6310 | ICmpInst::ICMP_ULT, X, LoBound); |
| 6311 | else if (LoOverflow) |
| 6312 | return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : |
| 6313 | ICmpInst::ICMP_UGE, X, HiBound); |
| 6314 | else |
| 6315 | return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI); |
| 6316 | case ICmpInst::ICMP_ULT: |
| 6317 | case ICmpInst::ICMP_SLT: |
| 6318 | if (LoOverflow == +1) // Low bound is greater than input range. |
| 6319 | return ReplaceInstUsesWith(ICI, ConstantInt::getTrue()); |
| 6320 | if (LoOverflow == -1) // Low bound is less than input range. |
| 6321 | return ReplaceInstUsesWith(ICI, ConstantInt::getFalse()); |
| 6322 | return new ICmpInst(Pred, X, LoBound); |
| 6323 | case ICmpInst::ICMP_UGT: |
| 6324 | case ICmpInst::ICMP_SGT: |
| 6325 | if (HiOverflow == +1) // High bound greater than input range. |
| 6326 | return ReplaceInstUsesWith(ICI, ConstantInt::getFalse()); |
| 6327 | else if (HiOverflow == -1) // High bound less than input range. |
| 6328 | return ReplaceInstUsesWith(ICI, ConstantInt::getTrue()); |
| 6329 | if (Pred == ICmpInst::ICMP_UGT) |
| 6330 | return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); |
| 6331 | else |
| 6332 | return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); |
| 6333 | } |
| 6334 | } |
| 6335 | |
| 6336 | |
| 6337 | /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)". |
| 6338 | /// |
| 6339 | Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, |
| 6340 | Instruction *LHSI, |
| 6341 | ConstantInt *RHS) { |
| 6342 | const APInt &RHSV = RHS->getValue(); |
| 6343 | |
| 6344 | switch (LHSI->getOpcode()) { |
Chris Lattner | 56be123 | 2009-01-09 07:47:06 +0000 | [diff] [blame] | 6345 | case Instruction::Trunc: |
| 6346 | if (ICI.isEquality() && LHSI->hasOneUse()) { |
| 6347 | // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all |
| 6348 | // of the high bits truncated out of x are known. |
| 6349 | unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(), |
| 6350 | SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); |
| 6351 | APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits)); |
| 6352 | APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); |
| 6353 | ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne); |
| 6354 | |
| 6355 | // If all the high bits are known, we can do this xform. |
| 6356 | if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) { |
| 6357 | // Pull in the high bits from known-ones set. |
| 6358 | APInt NewRHS(RHS->getValue()); |
| 6359 | NewRHS.zext(SrcBits); |
| 6360 | NewRHS |= KnownOne; |
| 6361 | return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), |
| 6362 | ConstantInt::get(NewRHS)); |
| 6363 | } |
| 6364 | } |
| 6365 | break; |
| 6366 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6367 | case Instruction::Xor: // (icmp pred (xor X, XorCST), CI) |
| 6368 | if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) { |
| 6369 | // If this is a comparison that tests the signbit (X < 0) or (x > -1), |
| 6370 | // fold the xor. |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 6371 | if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) || |
| 6372 | (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6373 | Value *CompareVal = LHSI->getOperand(0); |
| 6374 | |
| 6375 | // If the sign bit of the XorCST is not set, there is no change to |
| 6376 | // the operation, just stop using the Xor. |
| 6377 | if (!XorCST->getValue().isNegative()) { |
| 6378 | ICI.setOperand(0, CompareVal); |
| 6379 | AddToWorkList(LHSI); |
| 6380 | return &ICI; |
| 6381 | } |
| 6382 | |
| 6383 | // Was the old condition true if the operand is positive? |
| 6384 | bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT; |
| 6385 | |
| 6386 | // If so, the new one isn't. |
| 6387 | isTrueIfPositive ^= true; |
| 6388 | |
| 6389 | if (isTrueIfPositive) |
| 6390 | return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS)); |
| 6391 | else |
| 6392 | return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS)); |
| 6393 | } |
| 6394 | } |
| 6395 | break; |
| 6396 | case Instruction::And: // (icmp pred (and X, AndCST), RHS) |
| 6397 | if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) && |
| 6398 | LHSI->getOperand(0)->hasOneUse()) { |
| 6399 | ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1)); |
| 6400 | |
| 6401 | // If the LHS is an AND of a truncating cast, we can widen the |
| 6402 | // and/compare to be the input width without changing the value |
| 6403 | // produced, eliminating a cast. |
| 6404 | if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) { |
| 6405 | // We can do this transformation if either the AND constant does not |
| 6406 | // have its sign bit set or if it is an equality comparison. |
| 6407 | // Extending a relational comparison when we're checking the sign |
| 6408 | // bit would not work. |
| 6409 | if (Cast->hasOneUse() && |
Anton Korobeynikov | 6a4a933 | 2008-02-20 12:07:57 +0000 | [diff] [blame] | 6410 | (ICI.isEquality() || |
| 6411 | (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6412 | uint32_t BitWidth = |
| 6413 | cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth(); |
| 6414 | APInt NewCST = AndCST->getValue(); |
| 6415 | NewCST.zext(BitWidth); |
| 6416 | APInt NewCI = RHSV; |
| 6417 | NewCI.zext(BitWidth); |
| 6418 | Instruction *NewAnd = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6419 | BinaryOperator::CreateAnd(Cast->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6420 | ConstantInt::get(NewCST),LHSI->getName()); |
| 6421 | InsertNewInstBefore(NewAnd, ICI); |
| 6422 | return new ICmpInst(ICI.getPredicate(), NewAnd, |
| 6423 | ConstantInt::get(NewCI)); |
| 6424 | } |
| 6425 | } |
| 6426 | |
| 6427 | // If this is: (X >> C1) & C2 != C3 (where any shift and any compare |
| 6428 | // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This |
| 6429 | // happens a LOT in code produced by the C front-end, for bitfield |
| 6430 | // access. |
| 6431 | BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0)); |
| 6432 | if (Shift && !Shift->isShift()) |
| 6433 | Shift = 0; |
| 6434 | |
| 6435 | ConstantInt *ShAmt; |
| 6436 | ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0; |
| 6437 | const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift. |
| 6438 | const Type *AndTy = AndCST->getType(); // Type of the and. |
| 6439 | |
| 6440 | // We can fold this as long as we can't shift unknown bits |
| 6441 | // into the mask. This can only happen with signed shift |
| 6442 | // rights, as they sign-extend. |
| 6443 | if (ShAmt) { |
| 6444 | bool CanFold = Shift->isLogicalShift(); |
| 6445 | if (!CanFold) { |
| 6446 | // To test for the bad case of the signed shr, see if any |
| 6447 | // of the bits shifted in could be tested after the mask. |
| 6448 | uint32_t TyBits = Ty->getPrimitiveSizeInBits(); |
| 6449 | int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits); |
| 6450 | |
| 6451 | uint32_t BitWidth = AndTy->getPrimitiveSizeInBits(); |
| 6452 | if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & |
| 6453 | AndCST->getValue()) == 0) |
| 6454 | CanFold = true; |
| 6455 | } |
| 6456 | |
| 6457 | if (CanFold) { |
| 6458 | Constant *NewCst; |
| 6459 | if (Shift->getOpcode() == Instruction::Shl) |
| 6460 | NewCst = ConstantExpr::getLShr(RHS, ShAmt); |
| 6461 | else |
| 6462 | NewCst = ConstantExpr::getShl(RHS, ShAmt); |
| 6463 | |
| 6464 | // Check to see if we are shifting out any of the bits being |
| 6465 | // compared. |
| 6466 | if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) { |
| 6467 | // If we shifted bits out, the fold is not going to work out. |
| 6468 | // As a special case, check to see if this means that the |
| 6469 | // result is always true or false now. |
| 6470 | if (ICI.getPredicate() == ICmpInst::ICMP_EQ) |
| 6471 | return ReplaceInstUsesWith(ICI, ConstantInt::getFalse()); |
| 6472 | if (ICI.getPredicate() == ICmpInst::ICMP_NE) |
| 6473 | return ReplaceInstUsesWith(ICI, ConstantInt::getTrue()); |
| 6474 | } else { |
| 6475 | ICI.setOperand(1, NewCst); |
| 6476 | Constant *NewAndCST; |
| 6477 | if (Shift->getOpcode() == Instruction::Shl) |
| 6478 | NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt); |
| 6479 | else |
| 6480 | NewAndCST = ConstantExpr::getShl(AndCST, ShAmt); |
| 6481 | LHSI->setOperand(1, NewAndCST); |
| 6482 | LHSI->setOperand(0, Shift->getOperand(0)); |
| 6483 | AddToWorkList(Shift); // Shift is dead. |
| 6484 | AddUsesToWorkList(ICI); |
| 6485 | return &ICI; |
| 6486 | } |
| 6487 | } |
| 6488 | } |
| 6489 | |
| 6490 | // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is |
| 6491 | // preferable because it allows the C<<Y expression to be hoisted out |
| 6492 | // of a loop if Y is invariant and X is not. |
| 6493 | if (Shift && Shift->hasOneUse() && RHSV == 0 && |
| 6494 | ICI.isEquality() && !Shift->isArithmeticShift() && |
| 6495 | isa<Instruction>(Shift->getOperand(0))) { |
| 6496 | // Compute C << Y. |
| 6497 | Value *NS; |
| 6498 | if (Shift->getOpcode() == Instruction::LShr) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6499 | NS = BinaryOperator::CreateShl(AndCST, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6500 | Shift->getOperand(1), "tmp"); |
| 6501 | } else { |
| 6502 | // Insert a logical shift. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6503 | NS = BinaryOperator::CreateLShr(AndCST, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6504 | Shift->getOperand(1), "tmp"); |
| 6505 | } |
| 6506 | InsertNewInstBefore(cast<Instruction>(NS), ICI); |
| 6507 | |
| 6508 | // Compute X & (C << Y). |
| 6509 | Instruction *NewAnd = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6510 | BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6511 | InsertNewInstBefore(NewAnd, ICI); |
| 6512 | |
| 6513 | ICI.setOperand(0, NewAnd); |
| 6514 | return &ICI; |
| 6515 | } |
| 6516 | } |
| 6517 | break; |
| 6518 | |
| 6519 | case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) |
| 6520 | ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); |
| 6521 | if (!ShAmt) break; |
| 6522 | |
| 6523 | uint32_t TypeBits = RHSV.getBitWidth(); |
| 6524 | |
| 6525 | // Check that the shift amount is in range. If not, don't perform |
| 6526 | // undefined shifts. When the shift is visited it will be |
| 6527 | // simplified. |
| 6528 | if (ShAmt->uge(TypeBits)) |
| 6529 | break; |
| 6530 | |
| 6531 | if (ICI.isEquality()) { |
| 6532 | // If we are comparing against bits always shifted out, the |
| 6533 | // comparison cannot succeed. |
| 6534 | Constant *Comp = |
| 6535 | ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt); |
| 6536 | if (Comp != RHS) {// Comparing against a bit that we know is zero. |
| 6537 | bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; |
| 6538 | Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE); |
| 6539 | return ReplaceInstUsesWith(ICI, Cst); |
| 6540 | } |
| 6541 | |
| 6542 | if (LHSI->hasOneUse()) { |
| 6543 | // Otherwise strength reduce the shift into an and. |
| 6544 | uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); |
| 6545 | Constant *Mask = |
| 6546 | ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal)); |
| 6547 | |
| 6548 | Instruction *AndI = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6549 | BinaryOperator::CreateAnd(LHSI->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6550 | Mask, LHSI->getName()+".mask"); |
| 6551 | Value *And = InsertNewInstBefore(AndI, ICI); |
| 6552 | return new ICmpInst(ICI.getPredicate(), And, |
| 6553 | ConstantInt::get(RHSV.lshr(ShAmtVal))); |
| 6554 | } |
| 6555 | } |
| 6556 | |
| 6557 | // Otherwise, if this is a comparison of the sign bit, simplify to and/test. |
| 6558 | bool TrueIfSigned = false; |
| 6559 | if (LHSI->hasOneUse() && |
| 6560 | isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) { |
| 6561 | // (X << 31) <s 0 --> (X&1) != 0 |
| 6562 | Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) << |
| 6563 | (TypeBits-ShAmt->getZExtValue()-1)); |
| 6564 | Instruction *AndI = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6565 | BinaryOperator::CreateAnd(LHSI->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6566 | Mask, LHSI->getName()+".mask"); |
| 6567 | Value *And = InsertNewInstBefore(AndI, ICI); |
| 6568 | |
| 6569 | return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, |
| 6570 | And, Constant::getNullValue(And->getType())); |
| 6571 | } |
| 6572 | break; |
| 6573 | } |
| 6574 | |
| 6575 | case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI) |
| 6576 | case Instruction::AShr: { |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6577 | // Only handle equality comparisons of shift-by-constant. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6578 | ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6579 | if (!ShAmt || !ICI.isEquality()) break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6580 | |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6581 | // Check that the shift amount is in range. If not, don't perform |
| 6582 | // undefined shifts. When the shift is visited it will be |
| 6583 | // simplified. |
| 6584 | uint32_t TypeBits = RHSV.getBitWidth(); |
| 6585 | if (ShAmt->uge(TypeBits)) |
| 6586 | break; |
| 6587 | |
| 6588 | uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6589 | |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6590 | // If we are comparing against bits always shifted out, the |
| 6591 | // comparison cannot succeed. |
| 6592 | APInt Comp = RHSV << ShAmtVal; |
| 6593 | if (LHSI->getOpcode() == Instruction::LShr) |
| 6594 | Comp = Comp.lshr(ShAmtVal); |
| 6595 | else |
| 6596 | Comp = Comp.ashr(ShAmtVal); |
| 6597 | |
| 6598 | if (Comp != RHSV) { // Comparing against a bit that we know is zero. |
| 6599 | bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; |
| 6600 | Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE); |
| 6601 | return ReplaceInstUsesWith(ICI, Cst); |
| 6602 | } |
| 6603 | |
| 6604 | // Otherwise, check to see if the bits shifted out are known to be zero. |
| 6605 | // If so, we can compare against the unshifted value: |
| 6606 | // (X & 4) >> 1 == 2 --> (X & 4) == 4. |
Evan Cheng | fb9292a | 2008-04-23 00:38:06 +0000 | [diff] [blame] | 6607 | if (LHSI->hasOneUse() && |
| 6608 | MaskedValueIsZero(LHSI->getOperand(0), |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6609 | APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) { |
| 6610 | return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), |
| 6611 | ConstantExpr::getShl(RHS, ShAmt)); |
| 6612 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6613 | |
Evan Cheng | fb9292a | 2008-04-23 00:38:06 +0000 | [diff] [blame] | 6614 | if (LHSI->hasOneUse()) { |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6615 | // Otherwise strength reduce the shift into an and. |
| 6616 | APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); |
| 6617 | Constant *Mask = ConstantInt::get(Val); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6618 | |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6619 | Instruction *AndI = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6620 | BinaryOperator::CreateAnd(LHSI->getOperand(0), |
Chris Lattner | 5ee84f8 | 2008-03-21 05:19:58 +0000 | [diff] [blame] | 6621 | Mask, LHSI->getName()+".mask"); |
| 6622 | Value *And = InsertNewInstBefore(AndI, ICI); |
| 6623 | return new ICmpInst(ICI.getPredicate(), And, |
| 6624 | ConstantExpr::getShl(RHS, ShAmt)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6625 | } |
| 6626 | break; |
| 6627 | } |
| 6628 | |
| 6629 | case Instruction::SDiv: |
| 6630 | case Instruction::UDiv: |
| 6631 | // Fold: icmp pred ([us]div X, C1), C2 -> range test |
| 6632 | // Fold this div into the comparison, producing a range check. |
| 6633 | // Determine, based on the divide type, what the range is being |
| 6634 | // checked. If there is an overflow on the low or high side, remember |
| 6635 | // it, otherwise compute the range [low, hi) bounding the new value. |
| 6636 | // See: InsertRangeTest above for the kinds of replacements possible. |
| 6637 | if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) |
| 6638 | if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI), |
| 6639 | DivRHS)) |
| 6640 | return R; |
| 6641 | break; |
Nick Lewycky | 0185bbf | 2008-02-03 16:33:09 +0000 | [diff] [blame] | 6642 | |
| 6643 | case Instruction::Add: |
| 6644 | // Fold: icmp pred (add, X, C1), C2 |
| 6645 | |
| 6646 | if (!ICI.isEquality()) { |
| 6647 | ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1)); |
| 6648 | if (!LHSC) break; |
| 6649 | const APInt &LHSV = LHSC->getValue(); |
| 6650 | |
| 6651 | ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) |
| 6652 | .subtract(LHSV); |
| 6653 | |
| 6654 | if (ICI.isSignedPredicate()) { |
| 6655 | if (CR.getLower().isSignBit()) { |
| 6656 | return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), |
| 6657 | ConstantInt::get(CR.getUpper())); |
| 6658 | } else if (CR.getUpper().isSignBit()) { |
| 6659 | return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), |
| 6660 | ConstantInt::get(CR.getLower())); |
| 6661 | } |
| 6662 | } else { |
| 6663 | if (CR.getLower().isMinValue()) { |
| 6664 | return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), |
| 6665 | ConstantInt::get(CR.getUpper())); |
| 6666 | } else if (CR.getUpper().isMinValue()) { |
| 6667 | return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), |
| 6668 | ConstantInt::get(CR.getLower())); |
| 6669 | } |
| 6670 | } |
| 6671 | } |
| 6672 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6673 | } |
| 6674 | |
| 6675 | // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. |
| 6676 | if (ICI.isEquality()) { |
| 6677 | bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; |
| 6678 | |
| 6679 | // If the first operand is (add|sub|and|or|xor|rem) with a constant, and |
| 6680 | // the second operand is a constant, simplify a bit. |
| 6681 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) { |
| 6682 | switch (BO->getOpcode()) { |
| 6683 | case Instruction::SRem: |
| 6684 | // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. |
| 6685 | if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){ |
| 6686 | const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue(); |
| 6687 | if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) { |
| 6688 | Instruction *NewRem = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6689 | BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6690 | BO->getName()); |
| 6691 | InsertNewInstBefore(NewRem, ICI); |
| 6692 | return new ICmpInst(ICI.getPredicate(), NewRem, |
| 6693 | Constant::getNullValue(BO->getType())); |
| 6694 | } |
| 6695 | } |
| 6696 | break; |
| 6697 | case Instruction::Add: |
| 6698 | // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. |
| 6699 | if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) { |
| 6700 | if (BO->hasOneUse()) |
| 6701 | return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), |
| 6702 | Subtract(RHS, BOp1C)); |
| 6703 | } else if (RHSV == 0) { |
| 6704 | // Replace ((add A, B) != 0) with (A != -B) if A or B is |
| 6705 | // efficiently invertible, or if the add has just this one use. |
| 6706 | Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); |
| 6707 | |
| 6708 | if (Value *NegVal = dyn_castNegVal(BOp1)) |
| 6709 | return new ICmpInst(ICI.getPredicate(), BOp0, NegVal); |
| 6710 | else if (Value *NegVal = dyn_castNegVal(BOp0)) |
| 6711 | return new ICmpInst(ICI.getPredicate(), NegVal, BOp1); |
| 6712 | else if (BO->hasOneUse()) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6713 | Instruction *Neg = BinaryOperator::CreateNeg(BOp1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6714 | InsertNewInstBefore(Neg, ICI); |
| 6715 | Neg->takeName(BO); |
| 6716 | return new ICmpInst(ICI.getPredicate(), BOp0, Neg); |
| 6717 | } |
| 6718 | } |
| 6719 | break; |
| 6720 | case Instruction::Xor: |
| 6721 | // For the xor case, we can xor two constants together, eliminating |
| 6722 | // the explicit xor. |
| 6723 | if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) |
| 6724 | return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), |
| 6725 | ConstantExpr::getXor(RHS, BOC)); |
| 6726 | |
| 6727 | // FALLTHROUGH |
| 6728 | case Instruction::Sub: |
| 6729 | // Replace (([sub|xor] A, B) != 0) with (A != B) |
| 6730 | if (RHSV == 0) |
| 6731 | return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), |
| 6732 | BO->getOperand(1)); |
| 6733 | break; |
| 6734 | |
| 6735 | case Instruction::Or: |
| 6736 | // If bits are being or'd in that are not present in the constant we |
| 6737 | // are comparing against, then the comparison could never succeed! |
| 6738 | if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) { |
| 6739 | Constant *NotCI = ConstantExpr::getNot(RHS); |
| 6740 | if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) |
| 6741 | return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, |
| 6742 | isICMP_NE)); |
| 6743 | } |
| 6744 | break; |
| 6745 | |
| 6746 | case Instruction::And: |
| 6747 | if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { |
| 6748 | // If bits are being compared against that are and'd out, then the |
| 6749 | // comparison can never succeed! |
| 6750 | if ((RHSV & ~BOC->getValue()) != 0) |
| 6751 | return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, |
| 6752 | isICMP_NE)); |
| 6753 | |
| 6754 | // If we have ((X & C) == C), turn it into ((X & C) != 0). |
| 6755 | if (RHS == BOC && RHSV.isPowerOf2()) |
| 6756 | return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : |
| 6757 | ICmpInst::ICMP_NE, LHSI, |
| 6758 | Constant::getNullValue(RHS->getType())); |
| 6759 | |
| 6760 | // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 |
Chris Lattner | 60813c2 | 2008-06-02 01:29:46 +0000 | [diff] [blame] | 6761 | if (BOC->getValue().isSignBit()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6762 | Value *X = BO->getOperand(0); |
| 6763 | Constant *Zero = Constant::getNullValue(X->getType()); |
| 6764 | ICmpInst::Predicate pred = isICMP_NE ? |
| 6765 | ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; |
| 6766 | return new ICmpInst(pred, X, Zero); |
| 6767 | } |
| 6768 | |
| 6769 | // ((X & ~7) == 0) --> X < 8 |
| 6770 | if (RHSV == 0 && isHighOnes(BOC)) { |
| 6771 | Value *X = BO->getOperand(0); |
| 6772 | Constant *NegX = ConstantExpr::getNeg(BOC); |
| 6773 | ICmpInst::Predicate pred = isICMP_NE ? |
| 6774 | ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; |
| 6775 | return new ICmpInst(pred, X, NegX); |
| 6776 | } |
| 6777 | } |
| 6778 | default: break; |
| 6779 | } |
| 6780 | } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) { |
| 6781 | // Handle icmp {eq|ne} <intrinsic>, intcst. |
| 6782 | if (II->getIntrinsicID() == Intrinsic::bswap) { |
| 6783 | AddToWorkList(II); |
| 6784 | ICI.setOperand(0, II->getOperand(1)); |
| 6785 | ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap())); |
| 6786 | return &ICI; |
| 6787 | } |
| 6788 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6789 | } |
| 6790 | return 0; |
| 6791 | } |
| 6792 | |
| 6793 | /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst). |
| 6794 | /// We only handle extending casts so far. |
| 6795 | /// |
| 6796 | Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) { |
| 6797 | const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0)); |
| 6798 | Value *LHSCIOp = LHSCI->getOperand(0); |
| 6799 | const Type *SrcTy = LHSCIOp->getType(); |
| 6800 | const Type *DestTy = LHSCI->getType(); |
| 6801 | Value *RHSCIOp; |
| 6802 | |
| 6803 | // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the |
| 6804 | // integer type is the same size as the pointer type. |
| 6805 | if (LHSCI->getOpcode() == Instruction::PtrToInt && |
| 6806 | getTargetData().getPointerSizeInBits() == |
| 6807 | cast<IntegerType>(DestTy)->getBitWidth()) { |
| 6808 | Value *RHSOp = 0; |
| 6809 | if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) { |
| 6810 | RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); |
| 6811 | } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) { |
| 6812 | RHSOp = RHSC->getOperand(0); |
| 6813 | // If the pointer types don't match, insert a bitcast. |
| 6814 | if (LHSCIOp->getType() != RHSOp->getType()) |
Chris Lattner | 13c2d6e | 2008-01-13 22:23:22 +0000 | [diff] [blame] | 6815 | RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6816 | } |
| 6817 | |
| 6818 | if (RHSOp) |
| 6819 | return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp); |
| 6820 | } |
| 6821 | |
| 6822 | // The code below only handles extension cast instructions, so far. |
| 6823 | // Enforce this. |
| 6824 | if (LHSCI->getOpcode() != Instruction::ZExt && |
| 6825 | LHSCI->getOpcode() != Instruction::SExt) |
| 6826 | return 0; |
| 6827 | |
| 6828 | bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; |
| 6829 | bool isSignedCmp = ICI.isSignedPredicate(); |
| 6830 | |
| 6831 | if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) { |
| 6832 | // Not an extension from the same type? |
| 6833 | RHSCIOp = CI->getOperand(0); |
| 6834 | if (RHSCIOp->getType() != LHSCIOp->getType()) |
| 6835 | return 0; |
| 6836 | |
Nick Lewycky | d4264dc | 2008-01-28 03:48:02 +0000 | [diff] [blame] | 6837 | // If the signedness of the two casts doesn't agree (i.e. one is a sext |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6838 | // and the other is a zext), then we can't handle this. |
| 6839 | if (CI->getOpcode() != LHSCI->getOpcode()) |
| 6840 | return 0; |
| 6841 | |
Nick Lewycky | d4264dc | 2008-01-28 03:48:02 +0000 | [diff] [blame] | 6842 | // Deal with equality cases early. |
| 6843 | if (ICI.isEquality()) |
| 6844 | return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); |
| 6845 | |
| 6846 | // A signed comparison of sign extended values simplifies into a |
| 6847 | // signed comparison. |
| 6848 | if (isSignedCmp && isSignedExt) |
| 6849 | return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); |
| 6850 | |
| 6851 | // The other three cases all fold into an unsigned comparison. |
| 6852 | return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6853 | } |
| 6854 | |
| 6855 | // If we aren't dealing with a constant on the RHS, exit early |
| 6856 | ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1)); |
| 6857 | if (!CI) |
| 6858 | return 0; |
| 6859 | |
| 6860 | // Compute the constant that would happen if we truncated to SrcTy then |
| 6861 | // reextended to DestTy. |
| 6862 | Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy); |
| 6863 | Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy); |
| 6864 | |
| 6865 | // If the re-extended constant didn't change... |
| 6866 | if (Res2 == CI) { |
| 6867 | // Make sure that sign of the Cmp and the sign of the Cast are the same. |
| 6868 | // For example, we might have: |
| 6869 | // %A = sext short %X to uint |
| 6870 | // %B = icmp ugt uint %A, 1330 |
| 6871 | // It is incorrect to transform this into |
| 6872 | // %B = icmp ugt short %X, 1330 |
| 6873 | // because %A may have negative value. |
| 6874 | // |
Chris Lattner | 3d81653 | 2008-07-11 04:09:09 +0000 | [diff] [blame] | 6875 | // However, we allow this when the compare is EQ/NE, because they are |
| 6876 | // signless. |
| 6877 | if (isSignedExt == isSignedCmp || ICI.isEquality()) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6878 | return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); |
Chris Lattner | 3d81653 | 2008-07-11 04:09:09 +0000 | [diff] [blame] | 6879 | return 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6880 | } |
| 6881 | |
| 6882 | // The re-extended constant changed so the constant cannot be represented |
| 6883 | // in the shorter type. Consequently, we cannot emit a simple comparison. |
| 6884 | |
| 6885 | // First, handle some easy cases. We know the result cannot be equal at this |
| 6886 | // point so handle the ICI.isEquality() cases |
| 6887 | if (ICI.getPredicate() == ICmpInst::ICMP_EQ) |
| 6888 | return ReplaceInstUsesWith(ICI, ConstantInt::getFalse()); |
| 6889 | if (ICI.getPredicate() == ICmpInst::ICMP_NE) |
| 6890 | return ReplaceInstUsesWith(ICI, ConstantInt::getTrue()); |
| 6891 | |
| 6892 | // Evaluate the comparison for LT (we invert for GT below). LE and GE cases |
| 6893 | // should have been folded away previously and not enter in here. |
| 6894 | Value *Result; |
| 6895 | if (isSignedCmp) { |
| 6896 | // We're performing a signed comparison. |
| 6897 | if (cast<ConstantInt>(CI)->getValue().isNegative()) |
| 6898 | Result = ConstantInt::getFalse(); // X < (small) --> false |
| 6899 | else |
| 6900 | Result = ConstantInt::getTrue(); // X < (large) --> true |
| 6901 | } else { |
| 6902 | // We're performing an unsigned comparison. |
| 6903 | if (isSignedExt) { |
| 6904 | // We're performing an unsigned comp with a sign extended value. |
| 6905 | // This is true if the input is >= 0. [aka >s -1] |
| 6906 | Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy); |
| 6907 | Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp, |
| 6908 | NegOne, ICI.getName()), ICI); |
| 6909 | } else { |
| 6910 | // Unsigned extend & unsigned compare -> always true. |
| 6911 | Result = ConstantInt::getTrue(); |
| 6912 | } |
| 6913 | } |
| 6914 | |
| 6915 | // Finally, return the value computed. |
| 6916 | if (ICI.getPredicate() == ICmpInst::ICMP_ULT || |
Chris Lattner | 3d81653 | 2008-07-11 04:09:09 +0000 | [diff] [blame] | 6917 | ICI.getPredicate() == ICmpInst::ICMP_SLT) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6918 | return ReplaceInstUsesWith(ICI, Result); |
Chris Lattner | 3d81653 | 2008-07-11 04:09:09 +0000 | [diff] [blame] | 6919 | |
| 6920 | assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || |
| 6921 | ICI.getPredicate()==ICmpInst::ICMP_SGT) && |
| 6922 | "ICmp should be folded!"); |
| 6923 | if (Constant *CI = dyn_cast<Constant>(Result)) |
| 6924 | return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI)); |
| 6925 | return BinaryOperator::CreateNot(Result); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6926 | } |
| 6927 | |
| 6928 | Instruction *InstCombiner::visitShl(BinaryOperator &I) { |
| 6929 | return commonShiftTransforms(I); |
| 6930 | } |
| 6931 | |
| 6932 | Instruction *InstCombiner::visitLShr(BinaryOperator &I) { |
| 6933 | return commonShiftTransforms(I); |
| 6934 | } |
| 6935 | |
| 6936 | Instruction *InstCombiner::visitAShr(BinaryOperator &I) { |
Chris Lattner | e3c504f | 2007-12-06 01:59:46 +0000 | [diff] [blame] | 6937 | if (Instruction *R = commonShiftTransforms(I)) |
| 6938 | return R; |
| 6939 | |
| 6940 | Value *Op0 = I.getOperand(0); |
| 6941 | |
| 6942 | // ashr int -1, X = -1 (for any arithmetic shift rights of ~0) |
| 6943 | if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) |
| 6944 | if (CSI->isAllOnesValue()) |
| 6945 | return ReplaceInstUsesWith(I, CSI); |
| 6946 | |
| 6947 | // See if we can turn a signed shr into an unsigned shr. |
Nate Begeman | bb1ce94 | 2008-07-29 15:49:41 +0000 | [diff] [blame] | 6948 | if (!isa<VectorType>(I.getType()) && |
| 6949 | MaskedValueIsZero(Op0, |
Chris Lattner | e3c504f | 2007-12-06 01:59:46 +0000 | [diff] [blame] | 6950 | APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 6951 | return BinaryOperator::CreateLShr(Op0, I.getOperand(1)); |
Chris Lattner | e3c504f | 2007-12-06 01:59:46 +0000 | [diff] [blame] | 6952 | |
| 6953 | return 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6954 | } |
| 6955 | |
| 6956 | Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) { |
| 6957 | assert(I.getOperand(1)->getType() == I.getOperand(0)->getType()); |
| 6958 | Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); |
| 6959 | |
| 6960 | // shl X, 0 == X and shr X, 0 == X |
| 6961 | // shl 0, X == 0 and shr 0, X == 0 |
| 6962 | if (Op1 == Constant::getNullValue(Op1->getType()) || |
| 6963 | Op0 == Constant::getNullValue(Op0->getType())) |
| 6964 | return ReplaceInstUsesWith(I, Op0); |
| 6965 | |
| 6966 | if (isa<UndefValue>(Op0)) { |
| 6967 | if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef |
| 6968 | return ReplaceInstUsesWith(I, Op0); |
| 6969 | else // undef << X -> 0, undef >>u X -> 0 |
| 6970 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 6971 | } |
| 6972 | if (isa<UndefValue>(Op1)) { |
| 6973 | if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X |
| 6974 | return ReplaceInstUsesWith(I, Op0); |
| 6975 | else // X << undef, X >>u undef -> 0 |
| 6976 | return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType())); |
| 6977 | } |
| 6978 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6979 | // Try to fold constant and into select arguments. |
| 6980 | if (isa<Constant>(Op0)) |
| 6981 | if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) |
| 6982 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 6983 | return R; |
| 6984 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 6985 | if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1)) |
| 6986 | if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I)) |
| 6987 | return Res; |
| 6988 | return 0; |
| 6989 | } |
| 6990 | |
| 6991 | Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1, |
| 6992 | BinaryOperator &I) { |
| 6993 | bool isLeftShift = I.getOpcode() == Instruction::Shl; |
| 6994 | |
| 6995 | // See if we can simplify any instructions used by the instruction whose sole |
| 6996 | // purpose is to compute bits we don't care about. |
| 6997 | uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits(); |
| 6998 | APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0); |
| 6999 | if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits), |
| 7000 | KnownZero, KnownOne)) |
| 7001 | return &I; |
| 7002 | |
| 7003 | // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr |
| 7004 | // of a signed value. |
| 7005 | // |
| 7006 | if (Op1->uge(TypeBits)) { |
| 7007 | if (I.getOpcode() != Instruction::AShr) |
| 7008 | return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType())); |
| 7009 | else { |
| 7010 | I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1)); |
| 7011 | return &I; |
| 7012 | } |
| 7013 | } |
| 7014 | |
| 7015 | // ((X*C1) << C2) == (X * (C1 << C2)) |
| 7016 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) |
| 7017 | if (BO->getOpcode() == Instruction::Mul && isLeftShift) |
| 7018 | if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1))) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7019 | return BinaryOperator::CreateMul(BO->getOperand(0), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7020 | ConstantExpr::getShl(BOOp, Op1)); |
| 7021 | |
| 7022 | // Try to fold constant and into select arguments. |
| 7023 | if (SelectInst *SI = dyn_cast<SelectInst>(Op0)) |
| 7024 | if (Instruction *R = FoldOpIntoSelect(I, SI, this)) |
| 7025 | return R; |
| 7026 | if (isa<PHINode>(Op0)) |
| 7027 | if (Instruction *NV = FoldOpIntoPhi(I)) |
| 7028 | return NV; |
| 7029 | |
Chris Lattner | c6d1f64 | 2007-12-22 09:07:47 +0000 | [diff] [blame] | 7030 | // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2)) |
| 7031 | if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) { |
| 7032 | Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0)); |
| 7033 | // If 'shift2' is an ashr, we would have to get the sign bit into a funny |
| 7034 | // place. Don't try to do this transformation in this case. Also, we |
| 7035 | // require that the input operand is a shift-by-constant so that we have |
| 7036 | // confidence that the shifts will get folded together. We could do this |
| 7037 | // xform in more cases, but it is unlikely to be profitable. |
| 7038 | if (TrOp && I.isLogicalShift() && TrOp->isShift() && |
| 7039 | isa<ConstantInt>(TrOp->getOperand(1))) { |
| 7040 | // Okay, we'll do this xform. Make the shift of shift. |
| 7041 | Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType()); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7042 | Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt, |
Chris Lattner | c6d1f64 | 2007-12-22 09:07:47 +0000 | [diff] [blame] | 7043 | I.getName()); |
| 7044 | InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2) |
| 7045 | |
| 7046 | // For logical shifts, the truncation has the effect of making the high |
| 7047 | // part of the register be zeros. Emulate this by inserting an AND to |
| 7048 | // clear the top bits as needed. This 'and' will usually be zapped by |
| 7049 | // other xforms later if dead. |
| 7050 | unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits(); |
| 7051 | unsigned DstSize = TI->getType()->getPrimitiveSizeInBits(); |
| 7052 | APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize)); |
| 7053 | |
| 7054 | // The mask we constructed says what the trunc would do if occurring |
| 7055 | // between the shifts. We want to know the effect *after* the second |
| 7056 | // shift. We know that it is a logical shift by a constant, so adjust the |
| 7057 | // mask as appropriate. |
| 7058 | if (I.getOpcode() == Instruction::Shl) |
| 7059 | MaskV <<= Op1->getZExtValue(); |
| 7060 | else { |
| 7061 | assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift"); |
| 7062 | MaskV = MaskV.lshr(Op1->getZExtValue()); |
| 7063 | } |
| 7064 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7065 | Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV), |
Chris Lattner | c6d1f64 | 2007-12-22 09:07:47 +0000 | [diff] [blame] | 7066 | TI->getName()); |
| 7067 | InsertNewInstBefore(And, I); // shift1 & 0x00FF |
| 7068 | |
| 7069 | // Return the value truncated to the interesting size. |
| 7070 | return new TruncInst(And, I.getType()); |
| 7071 | } |
| 7072 | } |
| 7073 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7074 | if (Op0->hasOneUse()) { |
| 7075 | if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) { |
| 7076 | // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) |
| 7077 | Value *V1, *V2; |
| 7078 | ConstantInt *CC; |
| 7079 | switch (Op0BO->getOpcode()) { |
| 7080 | default: break; |
| 7081 | case Instruction::Add: |
| 7082 | case Instruction::And: |
| 7083 | case Instruction::Or: |
| 7084 | case Instruction::Xor: { |
| 7085 | // These operators commute. |
| 7086 | // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C) |
| 7087 | if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() && |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 7088 | match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){ |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7089 | Instruction *YS = BinaryOperator::CreateShl( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7090 | Op0BO->getOperand(0), Op1, |
| 7091 | Op0BO->getName()); |
| 7092 | InsertNewInstBefore(YS, I); // (Y << C) |
| 7093 | Instruction *X = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7094 | BinaryOperator::Create(Op0BO->getOpcode(), YS, V1, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7095 | Op0BO->getOperand(1)->getName()); |
| 7096 | InsertNewInstBefore(X, I); // (X + (Y << C)) |
| 7097 | uint32_t Op1Val = Op1->getLimitedValue(TypeBits); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7098 | return BinaryOperator::CreateAnd(X, ConstantInt::get( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7099 | APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val))); |
| 7100 | } |
| 7101 | |
| 7102 | // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C)) |
| 7103 | Value *Op0BOOp1 = Op0BO->getOperand(1); |
| 7104 | if (isLeftShift && Op0BOOp1->hasOneUse() && |
| 7105 | match(Op0BOOp1, |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 7106 | m_And(m_Shr(m_Value(V1), m_Specific(Op1)), |
| 7107 | m_ConstantInt(CC))) && |
| 7108 | cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7109 | Instruction *YS = BinaryOperator::CreateShl( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7110 | Op0BO->getOperand(0), Op1, |
| 7111 | Op0BO->getName()); |
| 7112 | InsertNewInstBefore(YS, I); // (Y << C) |
| 7113 | Instruction *XM = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7114 | BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7115 | V1->getName()+".mask"); |
| 7116 | InsertNewInstBefore(XM, I); // X & (CC << C) |
| 7117 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7118 | return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7119 | } |
| 7120 | } |
| 7121 | |
| 7122 | // FALL THROUGH. |
| 7123 | case Instruction::Sub: { |
| 7124 | // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) |
| 7125 | if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 7126 | match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){ |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7127 | Instruction *YS = BinaryOperator::CreateShl( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7128 | Op0BO->getOperand(1), Op1, |
| 7129 | Op0BO->getName()); |
| 7130 | InsertNewInstBefore(YS, I); // (Y << C) |
| 7131 | Instruction *X = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7132 | BinaryOperator::Create(Op0BO->getOpcode(), V1, YS, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7133 | Op0BO->getOperand(0)->getName()); |
| 7134 | InsertNewInstBefore(X, I); // (X + (Y << C)) |
| 7135 | uint32_t Op1Val = Op1->getLimitedValue(TypeBits); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7136 | return BinaryOperator::CreateAnd(X, ConstantInt::get( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7137 | APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val))); |
| 7138 | } |
| 7139 | |
| 7140 | // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C) |
| 7141 | if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && |
| 7142 | match(Op0BO->getOperand(0), |
| 7143 | m_And(m_Shr(m_Value(V1), m_Value(V2)), |
| 7144 | m_ConstantInt(CC))) && V2 == Op1 && |
| 7145 | cast<BinaryOperator>(Op0BO->getOperand(0)) |
| 7146 | ->getOperand(0)->hasOneUse()) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7147 | Instruction *YS = BinaryOperator::CreateShl( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7148 | Op0BO->getOperand(1), Op1, |
| 7149 | Op0BO->getName()); |
| 7150 | InsertNewInstBefore(YS, I); // (Y << C) |
| 7151 | Instruction *XM = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7152 | BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7153 | V1->getName()+".mask"); |
| 7154 | InsertNewInstBefore(XM, I); // X & (CC << C) |
| 7155 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7156 | return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7157 | } |
| 7158 | |
| 7159 | break; |
| 7160 | } |
| 7161 | } |
| 7162 | |
| 7163 | |
| 7164 | // If the operand is an bitwise operator with a constant RHS, and the |
| 7165 | // shift is the only use, we can pull it out of the shift. |
| 7166 | if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) { |
| 7167 | bool isValid = true; // Valid only for And, Or, Xor |
| 7168 | bool highBitSet = false; // Transform if high bit of constant set? |
| 7169 | |
| 7170 | switch (Op0BO->getOpcode()) { |
| 7171 | default: isValid = false; break; // Do not perform transform! |
| 7172 | case Instruction::Add: |
| 7173 | isValid = isLeftShift; |
| 7174 | break; |
| 7175 | case Instruction::Or: |
| 7176 | case Instruction::Xor: |
| 7177 | highBitSet = false; |
| 7178 | break; |
| 7179 | case Instruction::And: |
| 7180 | highBitSet = true; |
| 7181 | break; |
| 7182 | } |
| 7183 | |
| 7184 | // If this is a signed shift right, and the high bit is modified |
| 7185 | // by the logical operation, do not perform the transformation. |
| 7186 | // The highBitSet boolean indicates the value of the high bit of |
| 7187 | // the constant which would cause it to be modified for this |
| 7188 | // operation. |
| 7189 | // |
Chris Lattner | 15b76e3 | 2007-12-06 06:25:04 +0000 | [diff] [blame] | 7190 | if (isValid && I.getOpcode() == Instruction::AShr) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7191 | isValid = Op0C->getValue()[TypeBits-1] == highBitSet; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7192 | |
| 7193 | if (isValid) { |
| 7194 | Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1); |
| 7195 | |
| 7196 | Instruction *NewShift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7197 | BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7198 | InsertNewInstBefore(NewShift, I); |
| 7199 | NewShift->takeName(Op0BO); |
| 7200 | |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7201 | return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7202 | NewRHS); |
| 7203 | } |
| 7204 | } |
| 7205 | } |
| 7206 | } |
| 7207 | |
| 7208 | // Find out if this is a shift of a shift by a constant. |
| 7209 | BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0); |
| 7210 | if (ShiftOp && !ShiftOp->isShift()) |
| 7211 | ShiftOp = 0; |
| 7212 | |
| 7213 | if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) { |
| 7214 | ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1)); |
| 7215 | uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits); |
| 7216 | uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits); |
| 7217 | assert(ShiftAmt2 != 0 && "Should have been simplified earlier"); |
| 7218 | if (ShiftAmt1 == 0) return 0; // Will be simplified in the future. |
| 7219 | Value *X = ShiftOp->getOperand(0); |
| 7220 | |
| 7221 | uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift. |
| 7222 | if (AmtSum > TypeBits) |
| 7223 | AmtSum = TypeBits; |
| 7224 | |
| 7225 | const IntegerType *Ty = cast<IntegerType>(I.getType()); |
| 7226 | |
| 7227 | // Check for (X << c1) << c2 and (X >> c1) >> c2 |
| 7228 | if (I.getOpcode() == ShiftOp->getOpcode()) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7229 | return BinaryOperator::Create(I.getOpcode(), X, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7230 | ConstantInt::get(Ty, AmtSum)); |
| 7231 | } else if (ShiftOp->getOpcode() == Instruction::LShr && |
| 7232 | I.getOpcode() == Instruction::AShr) { |
| 7233 | // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7234 | return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7235 | } else if (ShiftOp->getOpcode() == Instruction::AShr && |
| 7236 | I.getOpcode() == Instruction::LShr) { |
| 7237 | // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0. |
| 7238 | Instruction *Shift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7239 | BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7240 | InsertNewInstBefore(Shift, I); |
| 7241 | |
| 7242 | APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7243 | return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7244 | } |
| 7245 | |
| 7246 | // Okay, if we get here, one shift must be left, and the other shift must be |
| 7247 | // right. See if the amounts are equal. |
| 7248 | if (ShiftAmt1 == ShiftAmt2) { |
| 7249 | // If we have ((X >>? C) << C), turn this into X & (-1 << C). |
| 7250 | if (I.getOpcode() == Instruction::Shl) { |
| 7251 | APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7252 | return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7253 | } |
| 7254 | // If we have ((X << C) >>u C), turn this into X & (-1 >>u C). |
| 7255 | if (I.getOpcode() == Instruction::LShr) { |
| 7256 | APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7257 | return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7258 | } |
| 7259 | // We can simplify ((X << C) >>s C) into a trunc + sext. |
| 7260 | // NOTE: we could do this for any C, but that would make 'unusual' integer |
| 7261 | // types. For now, just stick to ones well-supported by the code |
| 7262 | // generators. |
| 7263 | const Type *SExtType = 0; |
| 7264 | switch (Ty->getBitWidth() - ShiftAmt1) { |
| 7265 | case 1 : |
| 7266 | case 8 : |
| 7267 | case 16 : |
| 7268 | case 32 : |
| 7269 | case 64 : |
| 7270 | case 128: |
| 7271 | SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1); |
| 7272 | break; |
| 7273 | default: break; |
| 7274 | } |
| 7275 | if (SExtType) { |
| 7276 | Instruction *NewTrunc = new TruncInst(X, SExtType, "sext"); |
| 7277 | InsertNewInstBefore(NewTrunc, I); |
| 7278 | return new SExtInst(NewTrunc, Ty); |
| 7279 | } |
| 7280 | // Otherwise, we can't handle it yet. |
| 7281 | } else if (ShiftAmt1 < ShiftAmt2) { |
| 7282 | uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1; |
| 7283 | |
| 7284 | // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2) |
| 7285 | if (I.getOpcode() == Instruction::Shl) { |
| 7286 | assert(ShiftOp->getOpcode() == Instruction::LShr || |
| 7287 | ShiftOp->getOpcode() == Instruction::AShr); |
| 7288 | Instruction *Shift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7289 | BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7290 | InsertNewInstBefore(Shift, I); |
| 7291 | |
| 7292 | APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7293 | return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7294 | } |
| 7295 | |
| 7296 | // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2) |
| 7297 | if (I.getOpcode() == Instruction::LShr) { |
| 7298 | assert(ShiftOp->getOpcode() == Instruction::Shl); |
| 7299 | Instruction *Shift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7300 | BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7301 | InsertNewInstBefore(Shift, I); |
| 7302 | |
| 7303 | APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7304 | return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7305 | } |
| 7306 | |
| 7307 | // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. |
| 7308 | } else { |
| 7309 | assert(ShiftAmt2 < ShiftAmt1); |
| 7310 | uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2; |
| 7311 | |
| 7312 | // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2) |
| 7313 | if (I.getOpcode() == Instruction::Shl) { |
| 7314 | assert(ShiftOp->getOpcode() == Instruction::LShr || |
| 7315 | ShiftOp->getOpcode() == Instruction::AShr); |
| 7316 | Instruction *Shift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7317 | BinaryOperator::Create(ShiftOp->getOpcode(), X, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7318 | ConstantInt::get(Ty, ShiftDiff)); |
| 7319 | InsertNewInstBefore(Shift, I); |
| 7320 | |
| 7321 | APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7322 | return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7323 | } |
| 7324 | |
| 7325 | // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2) |
| 7326 | if (I.getOpcode() == Instruction::LShr) { |
| 7327 | assert(ShiftOp->getOpcode() == Instruction::Shl); |
| 7328 | Instruction *Shift = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7329 | BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7330 | InsertNewInstBefore(Shift, I); |
| 7331 | |
| 7332 | APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7333 | return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7334 | } |
| 7335 | |
| 7336 | // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in. |
| 7337 | } |
| 7338 | } |
| 7339 | return 0; |
| 7340 | } |
| 7341 | |
| 7342 | |
| 7343 | /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear |
| 7344 | /// expression. If so, decompose it, returning some value X, such that Val is |
| 7345 | /// X*Scale+Offset. |
| 7346 | /// |
| 7347 | static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale, |
| 7348 | int &Offset) { |
| 7349 | assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!"); |
| 7350 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) { |
| 7351 | Offset = CI->getZExtValue(); |
Chris Lattner | c59171a | 2007-10-12 05:30:59 +0000 | [diff] [blame] | 7352 | Scale = 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7353 | return ConstantInt::get(Type::Int32Ty, 0); |
Chris Lattner | c59171a | 2007-10-12 05:30:59 +0000 | [diff] [blame] | 7354 | } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) { |
| 7355 | if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 7356 | if (I->getOpcode() == Instruction::Shl) { |
| 7357 | // This is a value scaled by '1 << the shift amt'. |
| 7358 | Scale = 1U << RHS->getZExtValue(); |
| 7359 | Offset = 0; |
| 7360 | return I->getOperand(0); |
| 7361 | } else if (I->getOpcode() == Instruction::Mul) { |
| 7362 | // This value is scaled by 'RHS'. |
| 7363 | Scale = RHS->getZExtValue(); |
| 7364 | Offset = 0; |
| 7365 | return I->getOperand(0); |
| 7366 | } else if (I->getOpcode() == Instruction::Add) { |
| 7367 | // We have X+C. Check to see if we really have (X*C2)+C1, |
| 7368 | // where C1 is divisible by C2. |
| 7369 | unsigned SubScale; |
| 7370 | Value *SubVal = |
| 7371 | DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset); |
| 7372 | Offset += RHS->getZExtValue(); |
| 7373 | Scale = SubScale; |
| 7374 | return SubVal; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7375 | } |
| 7376 | } |
| 7377 | } |
| 7378 | |
| 7379 | // Otherwise, we can't look past this. |
| 7380 | Scale = 1; |
| 7381 | Offset = 0; |
| 7382 | return Val; |
| 7383 | } |
| 7384 | |
| 7385 | |
| 7386 | /// PromoteCastOfAllocation - If we find a cast of an allocation instruction, |
| 7387 | /// try to eliminate the cast by moving the type information into the alloc. |
| 7388 | Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI, |
| 7389 | AllocationInst &AI) { |
| 7390 | const PointerType *PTy = cast<PointerType>(CI.getType()); |
| 7391 | |
| 7392 | // Remove any uses of AI that are dead. |
| 7393 | assert(!CI.use_empty() && "Dead instructions should be removed earlier!"); |
| 7394 | |
| 7395 | for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) { |
| 7396 | Instruction *User = cast<Instruction>(*UI++); |
| 7397 | if (isInstructionTriviallyDead(User)) { |
| 7398 | while (UI != E && *UI == User) |
| 7399 | ++UI; // If this instruction uses AI more than once, don't break UI. |
| 7400 | |
| 7401 | ++NumDeadInst; |
| 7402 | DOUT << "IC: DCE: " << *User; |
| 7403 | EraseInstFromFunction(*User); |
| 7404 | } |
| 7405 | } |
| 7406 | |
| 7407 | // Get the type really allocated and the type casted to. |
| 7408 | const Type *AllocElTy = AI.getAllocatedType(); |
| 7409 | const Type *CastElTy = PTy->getElementType(); |
| 7410 | if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0; |
| 7411 | |
| 7412 | unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy); |
| 7413 | unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy); |
| 7414 | if (CastElTyAlign < AllocElTyAlign) return 0; |
| 7415 | |
| 7416 | // If the allocation has multiple uses, only promote it if we are strictly |
| 7417 | // increasing the alignment of the resultant allocation. If we keep it the |
| 7418 | // same, we open the door to infinite loops of various kinds. |
| 7419 | if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0; |
| 7420 | |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 7421 | uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy); |
| 7422 | uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7423 | if (CastElTySize == 0 || AllocElTySize == 0) return 0; |
| 7424 | |
| 7425 | // See if we can satisfy the modulus by pulling a scale out of the array |
| 7426 | // size argument. |
| 7427 | unsigned ArraySizeScale; |
| 7428 | int ArrayOffset; |
| 7429 | Value *NumElements = // See if the array size is a decomposable linear expr. |
| 7430 | DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset); |
| 7431 | |
| 7432 | // If we can now satisfy the modulus, by using a non-1 scale, we really can |
| 7433 | // do the xform. |
| 7434 | if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 || |
| 7435 | (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0; |
| 7436 | |
| 7437 | unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize; |
| 7438 | Value *Amt = 0; |
| 7439 | if (Scale == 1) { |
| 7440 | Amt = NumElements; |
| 7441 | } else { |
| 7442 | // If the allocation size is constant, form a constant mul expression |
| 7443 | Amt = ConstantInt::get(Type::Int32Ty, Scale); |
| 7444 | if (isa<ConstantInt>(NumElements)) |
| 7445 | Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt)); |
| 7446 | // otherwise multiply the amount and the number of elements |
| 7447 | else if (Scale != 1) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7448 | Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7449 | Amt = InsertNewInstBefore(Tmp, AI); |
| 7450 | } |
| 7451 | } |
| 7452 | |
| 7453 | if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) { |
| 7454 | Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7455 | Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7456 | Amt = InsertNewInstBefore(Tmp, AI); |
| 7457 | } |
| 7458 | |
| 7459 | AllocationInst *New; |
| 7460 | if (isa<MallocInst>(AI)) |
| 7461 | New = new MallocInst(CastElTy, Amt, AI.getAlignment()); |
| 7462 | else |
| 7463 | New = new AllocaInst(CastElTy, Amt, AI.getAlignment()); |
| 7464 | InsertNewInstBefore(New, AI); |
| 7465 | New->takeName(&AI); |
| 7466 | |
| 7467 | // If the allocation has multiple uses, insert a cast and change all things |
| 7468 | // that used it to use the new cast. This will also hack on CI, but it will |
| 7469 | // die soon. |
| 7470 | if (!AI.hasOneUse()) { |
| 7471 | AddUsesToWorkList(AI); |
| 7472 | // New is the allocation instruction, pointer typed. AI is the original |
| 7473 | // allocation instruction, also pointer typed. Thus, cast to use is BitCast. |
| 7474 | CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast"); |
| 7475 | InsertNewInstBefore(NewCast, AI); |
| 7476 | AI.replaceAllUsesWith(NewCast); |
| 7477 | } |
| 7478 | return ReplaceInstUsesWith(CI, New); |
| 7479 | } |
| 7480 | |
| 7481 | /// CanEvaluateInDifferentType - Return true if we can take the specified value |
| 7482 | /// and return it as type Ty without inserting any new casts and without |
| 7483 | /// changing the computed value. This is used by code that tries to decide |
| 7484 | /// whether promoting or shrinking integer operations to wider or smaller types |
| 7485 | /// will allow us to eliminate a truncate or extend. |
| 7486 | /// |
| 7487 | /// This is a truncation operation if Ty is smaller than V->getType(), or an |
| 7488 | /// extension operation if Ty is larger. |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7489 | /// |
| 7490 | /// If CastOpc is a truncation, then Ty will be a type smaller than V. We |
| 7491 | /// should return true if trunc(V) can be computed by computing V in the smaller |
| 7492 | /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as |
| 7493 | /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be |
| 7494 | /// efficiently truncated. |
| 7495 | /// |
| 7496 | /// If CastOpc is a sext or zext, we are asking if the low bits of the value can |
| 7497 | /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get |
| 7498 | /// the final result. |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7499 | bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty, |
| 7500 | unsigned CastOpc, |
| 7501 | int &NumCastsRemoved){ |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7502 | // We can always evaluate constants in another type. |
| 7503 | if (isa<ConstantInt>(V)) |
| 7504 | return true; |
| 7505 | |
| 7506 | Instruction *I = dyn_cast<Instruction>(V); |
| 7507 | if (!I) return false; |
| 7508 | |
| 7509 | const IntegerType *OrigTy = cast<IntegerType>(V->getType()); |
| 7510 | |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7511 | // If this is an extension or truncate, we can often eliminate it. |
| 7512 | if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
| 7513 | // If this is a cast from the destination type, we can trivially eliminate |
| 7514 | // it, and this will remove a cast overall. |
| 7515 | if (I->getOperand(0)->getType() == Ty) { |
| 7516 | // If the first operand is itself a cast, and is eliminable, do not count |
| 7517 | // this as an eliminable cast. We would prefer to eliminate those two |
| 7518 | // casts first. |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7519 | if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse()) |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7520 | ++NumCastsRemoved; |
| 7521 | return true; |
| 7522 | } |
| 7523 | } |
| 7524 | |
| 7525 | // We can't extend or shrink something that has multiple uses: doing so would |
| 7526 | // require duplicating the instruction in general, which isn't profitable. |
| 7527 | if (!I->hasOneUse()) return false; |
| 7528 | |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7529 | unsigned Opc = I->getOpcode(); |
| 7530 | switch (Opc) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7531 | case Instruction::Add: |
| 7532 | case Instruction::Sub: |
Nick Lewycky | 1265a7d | 2008-07-05 21:19:34 +0000 | [diff] [blame] | 7533 | case Instruction::Mul: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7534 | case Instruction::And: |
| 7535 | case Instruction::Or: |
| 7536 | case Instruction::Xor: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7537 | // These operators can all arbitrarily be extended or truncated. |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7538 | return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7539 | NumCastsRemoved) && |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7540 | CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7541 | NumCastsRemoved); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7542 | |
| 7543 | case Instruction::Shl: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7544 | // If we are truncating the result of this SHL, and if it's a shift of a |
| 7545 | // constant amount, we can always perform a SHL in a smaller type. |
| 7546 | if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 7547 | uint32_t BitWidth = Ty->getBitWidth(); |
| 7548 | if (BitWidth < OrigTy->getBitWidth() && |
| 7549 | CI->getLimitedValue(BitWidth) < BitWidth) |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7550 | return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7551 | NumCastsRemoved); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7552 | } |
| 7553 | break; |
| 7554 | case Instruction::LShr: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7555 | // If this is a truncate of a logical shr, we can truncate it to a smaller |
| 7556 | // lshr iff we know that the bits we would otherwise be shifting in are |
| 7557 | // already zeros. |
| 7558 | if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 7559 | uint32_t OrigBitWidth = OrigTy->getBitWidth(); |
| 7560 | uint32_t BitWidth = Ty->getBitWidth(); |
| 7561 | if (BitWidth < OrigBitWidth && |
| 7562 | MaskedValueIsZero(I->getOperand(0), |
| 7563 | APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) && |
| 7564 | CI->getLimitedValue(BitWidth) < BitWidth) { |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7565 | return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7566 | NumCastsRemoved); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7567 | } |
| 7568 | } |
| 7569 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7570 | case Instruction::ZExt: |
| 7571 | case Instruction::SExt: |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7572 | case Instruction::Trunc: |
| 7573 | // If this is the same kind of case as our original (e.g. zext+zext), we |
Chris Lattner | 9c909d2 | 2007-08-02 17:23:38 +0000 | [diff] [blame] | 7574 | // can safely replace it. Note that replacing it does not reduce the number |
| 7575 | // of casts in the input. |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7576 | if (Opc == CastOpc) |
| 7577 | return true; |
| 7578 | |
| 7579 | // sext (zext ty1), ty2 -> zext ty2 |
Evan Cheng | 7bb0d95 | 2009-01-15 17:09:07 +0000 | [diff] [blame] | 7580 | if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7581 | return true; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7582 | break; |
Nick Lewycky | 1265a7d | 2008-07-05 21:19:34 +0000 | [diff] [blame] | 7583 | case Instruction::Select: { |
| 7584 | SelectInst *SI = cast<SelectInst>(I); |
| 7585 | return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7586 | NumCastsRemoved) && |
Nick Lewycky | 1265a7d | 2008-07-05 21:19:34 +0000 | [diff] [blame] | 7587 | CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7588 | NumCastsRemoved); |
Nick Lewycky | 1265a7d | 2008-07-05 21:19:34 +0000 | [diff] [blame] | 7589 | } |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7590 | case Instruction::PHI: { |
| 7591 | // We can change a phi if we can change all operands. |
| 7592 | PHINode *PN = cast<PHINode>(I); |
| 7593 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 7594 | if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc, |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7595 | NumCastsRemoved)) |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7596 | return false; |
| 7597 | return true; |
| 7598 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7599 | default: |
| 7600 | // TODO: Can handle more cases here. |
| 7601 | break; |
| 7602 | } |
| 7603 | |
| 7604 | return false; |
| 7605 | } |
| 7606 | |
| 7607 | /// EvaluateInDifferentType - Given an expression that |
| 7608 | /// CanEvaluateInDifferentType returns true for, actually insert the code to |
| 7609 | /// evaluate the expression. |
| 7610 | Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, |
| 7611 | bool isSigned) { |
| 7612 | if (Constant *C = dyn_cast<Constant>(V)) |
| 7613 | return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/); |
| 7614 | |
| 7615 | // Otherwise, it must be an instruction. |
| 7616 | Instruction *I = cast<Instruction>(V); |
| 7617 | Instruction *Res = 0; |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7618 | unsigned Opc = I->getOpcode(); |
| 7619 | switch (Opc) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7620 | case Instruction::Add: |
| 7621 | case Instruction::Sub: |
Nick Lewycky | c52646a | 2008-01-22 05:08:48 +0000 | [diff] [blame] | 7622 | case Instruction::Mul: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7623 | case Instruction::And: |
| 7624 | case Instruction::Or: |
| 7625 | case Instruction::Xor: |
| 7626 | case Instruction::AShr: |
| 7627 | case Instruction::LShr: |
| 7628 | case Instruction::Shl: { |
| 7629 | Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned); |
| 7630 | Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7631 | Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7632 | break; |
| 7633 | } |
| 7634 | case Instruction::Trunc: |
| 7635 | case Instruction::ZExt: |
| 7636 | case Instruction::SExt: |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7637 | // If the source type of the cast is the type we're trying for then we can |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7638 | // just return the source. There's no need to insert it because it is not |
| 7639 | // new. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7640 | if (I->getOperand(0)->getType() == Ty) |
| 7641 | return I->getOperand(0); |
| 7642 | |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7643 | // Otherwise, must be the same type of cast, so just reinsert a new one. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7644 | Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0), |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7645 | Ty); |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7646 | break; |
Nick Lewycky | 1265a7d | 2008-07-05 21:19:34 +0000 | [diff] [blame] | 7647 | case Instruction::Select: { |
| 7648 | Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned); |
| 7649 | Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned); |
| 7650 | Res = SelectInst::Create(I->getOperand(0), True, False); |
| 7651 | break; |
| 7652 | } |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7653 | case Instruction::PHI: { |
| 7654 | PHINode *OPN = cast<PHINode>(I); |
| 7655 | PHINode *NPN = PHINode::Create(Ty); |
| 7656 | for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) { |
| 7657 | Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned); |
| 7658 | NPN->addIncoming(V, OPN->getIncomingBlock(i)); |
| 7659 | } |
| 7660 | Res = NPN; |
| 7661 | break; |
| 7662 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7663 | default: |
| 7664 | // TODO: Can handle more cases here. |
| 7665 | assert(0 && "Unreachable!"); |
| 7666 | break; |
| 7667 | } |
| 7668 | |
Chris Lattner | 4200c206 | 2008-06-18 04:00:49 +0000 | [diff] [blame] | 7669 | Res->takeName(I); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7670 | return InsertNewInstBefore(Res, *I); |
| 7671 | } |
| 7672 | |
| 7673 | /// @brief Implement the transforms common to all CastInst visitors. |
| 7674 | Instruction *InstCombiner::commonCastTransforms(CastInst &CI) { |
| 7675 | Value *Src = CI.getOperand(0); |
| 7676 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7677 | // Many cases of "cast of a cast" are eliminable. If it's eliminable we just |
| 7678 | // eliminate it now. |
| 7679 | if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast |
| 7680 | if (Instruction::CastOps opc = |
| 7681 | isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) { |
| 7682 | // The first cast (CSrc) is eliminable so we need to fix up or replace |
| 7683 | // the second cast (CI). CSrc will then have a good chance of being dead. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7684 | return CastInst::Create(opc, CSrc->getOperand(0), CI.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7685 | } |
| 7686 | } |
| 7687 | |
| 7688 | // If we are casting a select then fold the cast into the select |
| 7689 | if (SelectInst *SI = dyn_cast<SelectInst>(Src)) |
| 7690 | if (Instruction *NV = FoldOpIntoSelect(CI, SI, this)) |
| 7691 | return NV; |
| 7692 | |
| 7693 | // If we are casting a PHI then fold the cast into the PHI |
| 7694 | if (isa<PHINode>(Src)) |
| 7695 | if (Instruction *NV = FoldOpIntoPhi(CI)) |
| 7696 | return NV; |
| 7697 | |
| 7698 | return 0; |
| 7699 | } |
| 7700 | |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7701 | /// FindElementAtOffset - Given a type and a constant offset, determine whether |
| 7702 | /// or not there is a sequence of GEP indices into the type that will land us at |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 7703 | /// the specified offset. If so, fill them into NewIndices and return the |
| 7704 | /// resultant element type, otherwise return null. |
| 7705 | static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, |
| 7706 | SmallVectorImpl<Value*> &NewIndices, |
| 7707 | const TargetData *TD) { |
| 7708 | if (!Ty->isSized()) return 0; |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7709 | |
| 7710 | // Start with the index over the outer type. Note that the type size |
| 7711 | // might be zero (even if the offset isn't zero) if the indexed type |
| 7712 | // is something like [0 x {int, int}] |
| 7713 | const Type *IntPtrTy = TD->getIntPtrType(); |
| 7714 | int64_t FirstIdx = 0; |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 7715 | if (int64_t TySize = TD->getTypePaddedSize(Ty)) { |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7716 | FirstIdx = Offset/TySize; |
Chris Lattner | 0bd6f2b | 2009-01-11 20:41:36 +0000 | [diff] [blame] | 7717 | Offset -= FirstIdx*TySize; |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7718 | |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7719 | // Handle hosts where % returns negative instead of values [0..TySize). |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7720 | if (Offset < 0) { |
| 7721 | --FirstIdx; |
| 7722 | Offset += TySize; |
| 7723 | assert(Offset >= 0); |
| 7724 | } |
| 7725 | assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); |
| 7726 | } |
| 7727 | |
| 7728 | NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx)); |
| 7729 | |
| 7730 | // Index into the types. If we fail, set OrigBase to null. |
| 7731 | while (Offset) { |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7732 | // Indexing into tail padding between struct/array elements. |
| 7733 | if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty)) |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 7734 | return 0; |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7735 | |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7736 | if (const StructType *STy = dyn_cast<StructType>(Ty)) { |
| 7737 | const StructLayout *SL = TD->getStructLayout(STy); |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7738 | assert(Offset < (int64_t)SL->getSizeInBytes() && |
| 7739 | "Offset must stay within the indexed type"); |
| 7740 | |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7741 | unsigned Elt = SL->getElementContainingOffset(Offset); |
| 7742 | NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt)); |
| 7743 | |
| 7744 | Offset -= SL->getElementOffset(Elt); |
| 7745 | Ty = STy->getElementType(Elt); |
Chris Lattner | d35ce6a | 2009-01-11 20:23:52 +0000 | [diff] [blame] | 7746 | } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 7747 | uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType()); |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7748 | assert(EltSize && "Cannot index into a zero-sized array"); |
| 7749 | NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize)); |
| 7750 | Offset %= EltSize; |
Chris Lattner | d35ce6a | 2009-01-11 20:23:52 +0000 | [diff] [blame] | 7751 | Ty = AT->getElementType(); |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7752 | } else { |
Chris Lattner | ce48c46 | 2009-01-11 20:15:20 +0000 | [diff] [blame] | 7753 | // Otherwise, we can't index into the middle of this atomic type, bail. |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 7754 | return 0; |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7755 | } |
| 7756 | } |
| 7757 | |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 7758 | return Ty; |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7759 | } |
| 7760 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7761 | /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint) |
| 7762 | Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) { |
| 7763 | Value *Src = CI.getOperand(0); |
| 7764 | |
| 7765 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) { |
| 7766 | // If casting the result of a getelementptr instruction with no offset, turn |
| 7767 | // this into a cast of the original pointer! |
| 7768 | if (GEP->hasAllZeroIndices()) { |
| 7769 | // Changing the cast operand is usually not a good idea but it is safe |
| 7770 | // here because the pointer operand is being replaced with another |
| 7771 | // pointer operand so the opcode doesn't need to change. |
| 7772 | AddToWorkList(GEP); |
| 7773 | CI.setOperand(0, GEP->getOperand(0)); |
| 7774 | return &CI; |
| 7775 | } |
| 7776 | |
| 7777 | // If the GEP has a single use, and the base pointer is a bitcast, and the |
| 7778 | // GEP computes a constant offset, see if we can convert these three |
| 7779 | // instructions into fewer. This typically happens with unions and other |
| 7780 | // non-type-safe code. |
| 7781 | if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) { |
| 7782 | if (GEP->hasAllConstantIndices()) { |
| 7783 | // We are guaranteed to get a constant from EmitGEPOffset. |
| 7784 | ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this)); |
| 7785 | int64_t Offset = OffsetV->getSExtValue(); |
| 7786 | |
| 7787 | // Get the base pointer input of the bitcast, and the type it points to. |
| 7788 | Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0); |
| 7789 | const Type *GEPIdxTy = |
| 7790 | cast<PointerType>(OrigBase->getType())->getElementType(); |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7791 | SmallVector<Value*, 8> NewIndices; |
| 7792 | if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) { |
| 7793 | // If we were able to index down into an element, create the GEP |
| 7794 | // and bitcast the result. This eliminates one bitcast, potentially |
| 7795 | // two. |
| 7796 | Instruction *NGEP = GetElementPtrInst::Create(OrigBase, |
| 7797 | NewIndices.begin(), |
| 7798 | NewIndices.end(), ""); |
| 7799 | InsertNewInstBefore(NGEP, CI); |
| 7800 | NGEP->takeName(GEP); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7801 | |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 7802 | if (isa<BitCastInst>(CI)) |
| 7803 | return new BitCastInst(NGEP, CI.getType()); |
| 7804 | assert(isa<PtrToIntInst>(CI)); |
| 7805 | return new PtrToIntInst(NGEP, CI.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7806 | } |
| 7807 | } |
| 7808 | } |
| 7809 | } |
| 7810 | |
| 7811 | return commonCastTransforms(CI); |
| 7812 | } |
| 7813 | |
| 7814 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7815 | /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as |
| 7816 | /// integer types. This function implements the common transforms for all those |
| 7817 | /// cases. |
| 7818 | /// @brief Implement the transforms common to CastInst with integer operands |
| 7819 | Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) { |
| 7820 | if (Instruction *Result = commonCastTransforms(CI)) |
| 7821 | return Result; |
| 7822 | |
| 7823 | Value *Src = CI.getOperand(0); |
| 7824 | const Type *SrcTy = Src->getType(); |
| 7825 | const Type *DestTy = CI.getType(); |
| 7826 | uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits(); |
| 7827 | uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits(); |
| 7828 | |
| 7829 | // See if we can simplify any instructions used by the LHS whose sole |
| 7830 | // purpose is to compute bits we don't care about. |
| 7831 | APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0); |
| 7832 | if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize), |
| 7833 | KnownZero, KnownOne)) |
| 7834 | return &CI; |
| 7835 | |
| 7836 | // If the source isn't an instruction or has more than one use then we |
| 7837 | // can't do anything more. |
| 7838 | Instruction *SrcI = dyn_cast<Instruction>(Src); |
| 7839 | if (!SrcI || !Src->hasOneUse()) |
| 7840 | return 0; |
| 7841 | |
| 7842 | // Attempt to propagate the cast into the instruction for int->int casts. |
| 7843 | int NumCastsRemoved = 0; |
| 7844 | if (!isa<BitCastInst>(CI) && |
| 7845 | CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy), |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7846 | CI.getOpcode(), NumCastsRemoved)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7847 | // If this cast is a truncate, evaluting in a different type always |
Chris Lattner | ef70bb8 | 2007-08-02 06:11:14 +0000 | [diff] [blame] | 7848 | // eliminates the cast, so it is always a win. If this is a zero-extension, |
| 7849 | // we need to do an AND to maintain the clear top-part of the computation, |
| 7850 | // so we require that the input have eliminated at least one cast. If this |
| 7851 | // is a sign extension, we insert two new casts (to do the extension) so we |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7852 | // require that two casts have been eliminated. |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7853 | bool DoXForm = false; |
| 7854 | bool JustReplace = false; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7855 | switch (CI.getOpcode()) { |
| 7856 | default: |
| 7857 | // All the others use floating point so we shouldn't actually |
| 7858 | // get here because of the check above. |
| 7859 | assert(0 && "Unknown cast type"); |
| 7860 | case Instruction::Trunc: |
| 7861 | DoXForm = true; |
| 7862 | break; |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7863 | case Instruction::ZExt: { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7864 | DoXForm = NumCastsRemoved >= 1; |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7865 | if (!DoXForm) { |
| 7866 | // If it's unnecessary to issue an AND to clear the high bits, it's |
| 7867 | // always profitable to do this xform. |
| 7868 | Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, |
| 7869 | CI.getOpcode() == Instruction::SExt); |
| 7870 | APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize)); |
| 7871 | if (MaskedValueIsZero(TryRes, Mask)) |
| 7872 | return ReplaceInstUsesWith(CI, TryRes); |
| 7873 | else if (Instruction *TryI = dyn_cast<Instruction>(TryRes)) |
| 7874 | if (TryI->use_empty()) |
| 7875 | EraseInstFromFunction(*TryI); |
| 7876 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7877 | break; |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7878 | } |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7879 | case Instruction::SExt: { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7880 | DoXForm = NumCastsRemoved >= 2; |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7881 | if (!DoXForm && !isa<TruncInst>(SrcI)) { |
| 7882 | // If we do not have to emit the truncate + sext pair, then it's always |
| 7883 | // profitable to do this xform. |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7884 | // |
| 7885 | // It's not safe to eliminate the trunc + sext pair if one of the |
| 7886 | // eliminated cast is a truncate. e.g. |
| 7887 | // t2 = trunc i32 t1 to i16 |
| 7888 | // t3 = sext i16 t2 to i32 |
| 7889 | // != |
| 7890 | // i32 t1 |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7891 | Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, |
| 7892 | CI.getOpcode() == Instruction::SExt); |
| 7893 | unsigned NumSignBits = ComputeNumSignBits(TryRes); |
| 7894 | if (NumSignBits > (DestBitSize - SrcBitSize)) |
| 7895 | return ReplaceInstUsesWith(CI, TryRes); |
| 7896 | else if (Instruction *TryI = dyn_cast<Instruction>(TryRes)) |
| 7897 | if (TryI->use_empty()) |
| 7898 | EraseInstFromFunction(*TryI); |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7899 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7900 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7901 | } |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7902 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7903 | |
| 7904 | if (DoXForm) { |
| 7905 | Value *Res = EvaluateInDifferentType(SrcI, DestTy, |
| 7906 | CI.getOpcode() == Instruction::SExt); |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7907 | if (JustReplace) |
| 7908 | // Just replace this cast with the result. |
| 7909 | return ReplaceInstUsesWith(CI, Res); |
| 7910 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7911 | assert(Res->getType() == DestTy); |
| 7912 | switch (CI.getOpcode()) { |
| 7913 | default: assert(0 && "Unknown cast type!"); |
| 7914 | case Instruction::Trunc: |
| 7915 | case Instruction::BitCast: |
| 7916 | // Just replace this cast with the result. |
| 7917 | return ReplaceInstUsesWith(CI, Res); |
| 7918 | case Instruction::ZExt: { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7919 | assert(SrcBitSize < DestBitSize && "Not a zext?"); |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7920 | |
| 7921 | // If the high bits are already zero, just replace this cast with the |
| 7922 | // result. |
| 7923 | APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize)); |
| 7924 | if (MaskedValueIsZero(Res, Mask)) |
| 7925 | return ReplaceInstUsesWith(CI, Res); |
| 7926 | |
| 7927 | // We need to emit an AND to clear the high bits. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7928 | Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize, |
| 7929 | SrcBitSize)); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7930 | return BinaryOperator::CreateAnd(Res, C); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7931 | } |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7932 | case Instruction::SExt: { |
| 7933 | // If the high bits are already filled with sign bit, just replace this |
| 7934 | // cast with the result. |
| 7935 | unsigned NumSignBits = ComputeNumSignBits(Res); |
| 7936 | if (NumSignBits > (DestBitSize - SrcBitSize)) |
Evan Cheng | 9ca34ab | 2009-01-15 17:01:23 +0000 | [diff] [blame] | 7937 | return ReplaceInstUsesWith(CI, Res); |
| 7938 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7939 | // We need to emit a cast to truncate, then a cast to sext. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7940 | return CastInst::Create(Instruction::SExt, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7941 | InsertCastBefore(Instruction::Trunc, Res, Src->getType(), |
| 7942 | CI), DestTy); |
| 7943 | } |
Evan Cheng | 814a00c | 2009-01-16 02:11:43 +0000 | [diff] [blame] | 7944 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7945 | } |
| 7946 | } |
| 7947 | |
| 7948 | Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0; |
| 7949 | Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0; |
| 7950 | |
| 7951 | switch (SrcI->getOpcode()) { |
| 7952 | case Instruction::Add: |
| 7953 | case Instruction::Mul: |
| 7954 | case Instruction::And: |
| 7955 | case Instruction::Or: |
| 7956 | case Instruction::Xor: |
| 7957 | // If we are discarding information, rewrite. |
| 7958 | if (DestBitSize <= SrcBitSize && DestBitSize != 1) { |
| 7959 | // Don't insert two casts if they cannot be eliminated. We allow |
| 7960 | // two casts to be inserted if the sizes are the same. This could |
| 7961 | // only be converting signedness, which is a noop. |
| 7962 | if (DestBitSize == SrcBitSize || |
| 7963 | !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) || |
| 7964 | !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) { |
| 7965 | Instruction::CastOps opcode = CI.getOpcode(); |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 7966 | Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI); |
| 7967 | Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7968 | return BinaryOperator::Create( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7969 | cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c); |
| 7970 | } |
| 7971 | } |
| 7972 | |
| 7973 | // cast (xor bool X, true) to int --> xor (cast bool X to int), 1 |
| 7974 | if (isa<ZExtInst>(CI) && SrcBitSize == 1 && |
| 7975 | SrcI->getOpcode() == Instruction::Xor && |
| 7976 | Op1 == ConstantInt::getTrue() && |
| 7977 | (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) { |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 7978 | Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7979 | return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7980 | } |
| 7981 | break; |
| 7982 | case Instruction::SDiv: |
| 7983 | case Instruction::UDiv: |
| 7984 | case Instruction::SRem: |
| 7985 | case Instruction::URem: |
| 7986 | // If we are just changing the sign, rewrite. |
| 7987 | if (DestBitSize == SrcBitSize) { |
| 7988 | // Don't insert two casts if they cannot be eliminated. We allow |
| 7989 | // two casts to be inserted if the sizes are the same. This could |
| 7990 | // only be converting signedness, which is a noop. |
| 7991 | if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || |
| 7992 | !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) { |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 7993 | Value *Op0c = InsertCastBefore(Instruction::BitCast, |
| 7994 | Op0, DestTy, *SrcI); |
| 7995 | Value *Op1c = InsertCastBefore(Instruction::BitCast, |
| 7996 | Op1, DestTy, *SrcI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 7997 | return BinaryOperator::Create( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 7998 | cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c); |
| 7999 | } |
| 8000 | } |
| 8001 | break; |
| 8002 | |
| 8003 | case Instruction::Shl: |
| 8004 | // Allow changing the sign of the source operand. Do not allow |
| 8005 | // changing the size of the shift, UNLESS the shift amount is a |
| 8006 | // constant. We must not change variable sized shifts to a smaller |
| 8007 | // size, because it is undefined to shift more bits out than exist |
| 8008 | // in the value. |
| 8009 | if (DestBitSize == SrcBitSize || |
| 8010 | (DestBitSize < SrcBitSize && isa<Constant>(Op1))) { |
| 8011 | Instruction::CastOps opcode = (DestBitSize == SrcBitSize ? |
| 8012 | Instruction::BitCast : Instruction::Trunc); |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 8013 | Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI); |
| 8014 | Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8015 | return BinaryOperator::CreateShl(Op0c, Op1c); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8016 | } |
| 8017 | break; |
| 8018 | case Instruction::AShr: |
| 8019 | // If this is a signed shr, and if all bits shifted in are about to be |
| 8020 | // truncated off, turn it into an unsigned shr to allow greater |
| 8021 | // simplifications. |
| 8022 | if (DestBitSize < SrcBitSize && |
| 8023 | isa<ConstantInt>(Op1)) { |
| 8024 | uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize); |
| 8025 | if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) { |
| 8026 | // Insert the new logical shift right. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8027 | return BinaryOperator::CreateLShr(Op0, Op1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8028 | } |
| 8029 | } |
| 8030 | break; |
| 8031 | } |
| 8032 | return 0; |
| 8033 | } |
| 8034 | |
| 8035 | Instruction *InstCombiner::visitTrunc(TruncInst &CI) { |
| 8036 | if (Instruction *Result = commonIntCastTransforms(CI)) |
| 8037 | return Result; |
| 8038 | |
| 8039 | Value *Src = CI.getOperand(0); |
| 8040 | const Type *Ty = CI.getType(); |
| 8041 | uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits(); |
| 8042 | uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth(); |
| 8043 | |
| 8044 | if (Instruction *SrcI = dyn_cast<Instruction>(Src)) { |
| 8045 | switch (SrcI->getOpcode()) { |
| 8046 | default: break; |
| 8047 | case Instruction::LShr: |
| 8048 | // We can shrink lshr to something smaller if we know the bits shifted in |
| 8049 | // are already zeros. |
| 8050 | if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) { |
| 8051 | uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth); |
| 8052 | |
| 8053 | // Get a mask for the bits shifting in. |
| 8054 | APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth)); |
| 8055 | Value* SrcIOp0 = SrcI->getOperand(0); |
| 8056 | if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) { |
| 8057 | if (ShAmt >= DestBitWidth) // All zeros. |
| 8058 | return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty)); |
| 8059 | |
| 8060 | // Okay, we can shrink this. Truncate the input, then return a new |
| 8061 | // shift. |
| 8062 | Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI); |
| 8063 | Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1), |
| 8064 | Ty, CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8065 | return BinaryOperator::CreateLShr(V1, V2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8066 | } |
| 8067 | } else { // This is a variable shr. |
| 8068 | |
| 8069 | // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is |
| 8070 | // more LLVM instructions, but allows '1 << Y' to be hoisted if |
| 8071 | // loop-invariant and CSE'd. |
| 8072 | if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) { |
| 8073 | Value *One = ConstantInt::get(SrcI->getType(), 1); |
| 8074 | |
| 8075 | Value *V = InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8076 | BinaryOperator::CreateShl(One, SrcI->getOperand(1), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8077 | "tmp"), CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8078 | V = InsertNewInstBefore(BinaryOperator::CreateAnd(V, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8079 | SrcI->getOperand(0), |
| 8080 | "tmp"), CI); |
| 8081 | Value *Zero = Constant::getNullValue(V->getType()); |
| 8082 | return new ICmpInst(ICmpInst::ICMP_NE, V, Zero); |
| 8083 | } |
| 8084 | } |
| 8085 | break; |
| 8086 | } |
| 8087 | } |
| 8088 | |
| 8089 | return 0; |
| 8090 | } |
| 8091 | |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8092 | /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations |
| 8093 | /// in order to eliminate the icmp. |
| 8094 | Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI, |
| 8095 | bool DoXform) { |
| 8096 | // If we are just checking for a icmp eq of a single bit and zext'ing it |
| 8097 | // to an integer, then shift the bit to the appropriate place and then |
| 8098 | // cast to integer to avoid the comparison. |
| 8099 | if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) { |
| 8100 | const APInt &Op1CV = Op1C->getValue(); |
| 8101 | |
| 8102 | // zext (x <s 0) to i32 --> x>>u31 true if signbit set. |
| 8103 | // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear. |
| 8104 | if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) || |
| 8105 | (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) { |
| 8106 | if (!DoXform) return ICI; |
| 8107 | |
| 8108 | Value *In = ICI->getOperand(0); |
| 8109 | Value *Sh = ConstantInt::get(In->getType(), |
| 8110 | In->getType()->getPrimitiveSizeInBits()-1); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8111 | In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh, |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8112 | In->getName()+".lobit"), |
| 8113 | CI); |
| 8114 | if (In->getType() != CI.getType()) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8115 | In = CastInst::CreateIntegerCast(In, CI.getType(), |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8116 | false/*ZExt*/, "tmp", &CI); |
| 8117 | |
| 8118 | if (ICI->getPredicate() == ICmpInst::ICMP_SGT) { |
| 8119 | Constant *One = ConstantInt::get(In->getType(), 1); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8120 | In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One, |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8121 | In->getName()+".not"), |
| 8122 | CI); |
| 8123 | } |
| 8124 | |
| 8125 | return ReplaceInstUsesWith(CI, In); |
| 8126 | } |
| 8127 | |
| 8128 | |
| 8129 | |
| 8130 | // zext (X == 0) to i32 --> X^1 iff X has only the low bit set. |
| 8131 | // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. |
| 8132 | // zext (X == 1) to i32 --> X iff X has only the low bit set. |
| 8133 | // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set. |
| 8134 | // zext (X != 0) to i32 --> X iff X has only the low bit set. |
| 8135 | // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set. |
| 8136 | // zext (X != 1) to i32 --> X^1 iff X has only the low bit set. |
| 8137 | // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set. |
| 8138 | if ((Op1CV == 0 || Op1CV.isPowerOf2()) && |
| 8139 | // This only works for EQ and NE |
| 8140 | ICI->isEquality()) { |
| 8141 | // If Op1C some other power of two, convert: |
| 8142 | uint32_t BitWidth = Op1C->getType()->getBitWidth(); |
| 8143 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 8144 | APInt TypeMask(APInt::getAllOnesValue(BitWidth)); |
| 8145 | ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne); |
| 8146 | |
| 8147 | APInt KnownZeroMask(~KnownZero); |
| 8148 | if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1? |
| 8149 | if (!DoXform) return ICI; |
| 8150 | |
| 8151 | bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE; |
| 8152 | if (Op1CV != 0 && (Op1CV != KnownZeroMask)) { |
| 8153 | // (X&4) == 2 --> false |
| 8154 | // (X&4) != 2 --> true |
| 8155 | Constant *Res = ConstantInt::get(Type::Int1Ty, isNE); |
| 8156 | Res = ConstantExpr::getZExt(Res, CI.getType()); |
| 8157 | return ReplaceInstUsesWith(CI, Res); |
| 8158 | } |
| 8159 | |
| 8160 | uint32_t ShiftAmt = KnownZeroMask.logBase2(); |
| 8161 | Value *In = ICI->getOperand(0); |
| 8162 | if (ShiftAmt) { |
| 8163 | // Perform a logical shr by shiftamt. |
| 8164 | // Insert the shift to put the result in the low bit. |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8165 | In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8166 | ConstantInt::get(In->getType(), ShiftAmt), |
| 8167 | In->getName()+".lobit"), CI); |
| 8168 | } |
| 8169 | |
| 8170 | if ((Op1CV != 0) == isNE) { // Toggle the low bit. |
| 8171 | Constant *One = ConstantInt::get(In->getType(), 1); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8172 | In = BinaryOperator::CreateXor(In, One, "tmp"); |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8173 | InsertNewInstBefore(cast<Instruction>(In), CI); |
| 8174 | } |
| 8175 | |
| 8176 | if (CI.getType() == In->getType()) |
| 8177 | return ReplaceInstUsesWith(CI, In); |
| 8178 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8179 | return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/); |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8180 | } |
| 8181 | } |
| 8182 | } |
| 8183 | |
| 8184 | return 0; |
| 8185 | } |
| 8186 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8187 | Instruction *InstCombiner::visitZExt(ZExtInst &CI) { |
| 8188 | // If one of the common conversion will work .. |
| 8189 | if (Instruction *Result = commonIntCastTransforms(CI)) |
| 8190 | return Result; |
| 8191 | |
| 8192 | Value *Src = CI.getOperand(0); |
| 8193 | |
| 8194 | // If this is a cast of a cast |
| 8195 | if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast |
| 8196 | // If this is a TRUNC followed by a ZEXT then we are dealing with integral |
| 8197 | // types and if the sizes are just right we can convert this into a logical |
| 8198 | // 'and' which will be much cheaper than the pair of casts. |
| 8199 | if (isa<TruncInst>(CSrc)) { |
| 8200 | // Get the sizes of the types involved |
| 8201 | Value *A = CSrc->getOperand(0); |
| 8202 | uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits(); |
| 8203 | uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits(); |
| 8204 | uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits(); |
| 8205 | // If we're actually extending zero bits and the trunc is a no-op |
| 8206 | if (MidSize < DstSize && SrcSize == DstSize) { |
| 8207 | // Replace both of the casts with an And of the type mask. |
| 8208 | APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize)); |
| 8209 | Constant *AndConst = ConstantInt::get(AndValue); |
| 8210 | Instruction *And = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8211 | BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8212 | // Unfortunately, if the type changed, we need to cast it back. |
| 8213 | if (And->getType() != CI.getType()) { |
| 8214 | And->setName(CSrc->getName()+".mask"); |
| 8215 | InsertNewInstBefore(And, CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8216 | And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8217 | } |
| 8218 | return And; |
| 8219 | } |
| 8220 | } |
| 8221 | } |
| 8222 | |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8223 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) |
| 8224 | return transformZExtICmp(ICI, CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8225 | |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8226 | BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src); |
| 8227 | if (SrcI && SrcI->getOpcode() == Instruction::Or) { |
| 8228 | // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one |
| 8229 | // of the (zext icmp) will be transformed. |
| 8230 | ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0)); |
| 8231 | ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1)); |
| 8232 | if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() && |
| 8233 | (transformZExtICmp(LHS, CI, false) || |
| 8234 | transformZExtICmp(RHS, CI, false))) { |
| 8235 | Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI); |
| 8236 | Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8237 | return BinaryOperator::Create(Instruction::Or, LCast, RCast); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8238 | } |
Evan Cheng | e3779cf | 2008-03-24 00:21:34 +0000 | [diff] [blame] | 8239 | } |
| 8240 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8241 | return 0; |
| 8242 | } |
| 8243 | |
| 8244 | Instruction *InstCombiner::visitSExt(SExtInst &CI) { |
| 8245 | if (Instruction *I = commonIntCastTransforms(CI)) |
| 8246 | return I; |
| 8247 | |
| 8248 | Value *Src = CI.getOperand(0); |
| 8249 | |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8250 | // Canonicalize sign-extend from i1 to a select. |
| 8251 | if (Src->getType() == Type::Int1Ty) |
| 8252 | return SelectInst::Create(Src, |
| 8253 | ConstantInt::getAllOnesValue(CI.getType()), |
| 8254 | Constant::getNullValue(CI.getType())); |
Dan Gohman | f0f1202 | 2008-05-20 21:01:12 +0000 | [diff] [blame] | 8255 | |
| 8256 | // See if the value being truncated is already sign extended. If so, just |
| 8257 | // eliminate the trunc/sext pair. |
| 8258 | if (getOpcode(Src) == Instruction::Trunc) { |
| 8259 | Value *Op = cast<User>(Src)->getOperand(0); |
| 8260 | unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth(); |
| 8261 | unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth(); |
| 8262 | unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth(); |
| 8263 | unsigned NumSignBits = ComputeNumSignBits(Op); |
| 8264 | |
| 8265 | if (OpBits == DestBits) { |
| 8266 | // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign |
| 8267 | // bits, it is already ready. |
| 8268 | if (NumSignBits > DestBits-MidBits) |
| 8269 | return ReplaceInstUsesWith(CI, Op); |
| 8270 | } else if (OpBits < DestBits) { |
| 8271 | // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign |
| 8272 | // bits, just sext from i32. |
| 8273 | if (NumSignBits > OpBits-MidBits) |
| 8274 | return new SExtInst(Op, CI.getType(), "tmp"); |
| 8275 | } else { |
| 8276 | // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign |
| 8277 | // bits, just truncate to i32. |
| 8278 | if (NumSignBits > OpBits-MidBits) |
| 8279 | return new TruncInst(Op, CI.getType(), "tmp"); |
| 8280 | } |
| 8281 | } |
Chris Lattner | 8a2d059 | 2008-08-06 07:35:52 +0000 | [diff] [blame] | 8282 | |
| 8283 | // If the input is a shl/ashr pair of a same constant, then this is a sign |
| 8284 | // extension from a smaller value. If we could trust arbitrary bitwidth |
| 8285 | // integers, we could turn this into a truncate to the smaller bit and then |
| 8286 | // use a sext for the whole extension. Since we don't, look deeper and check |
| 8287 | // for a truncate. If the source and dest are the same type, eliminate the |
| 8288 | // trunc and extend and just do shifts. For example, turn: |
| 8289 | // %a = trunc i32 %i to i8 |
| 8290 | // %b = shl i8 %a, 6 |
| 8291 | // %c = ashr i8 %b, 6 |
| 8292 | // %d = sext i8 %c to i32 |
| 8293 | // into: |
| 8294 | // %a = shl i32 %i, 30 |
| 8295 | // %d = ashr i32 %a, 30 |
| 8296 | Value *A = 0; |
| 8297 | ConstantInt *BA = 0, *CA = 0; |
| 8298 | if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)), |
| 8299 | m_ConstantInt(CA))) && |
| 8300 | BA == CA && isa<TruncInst>(A)) { |
| 8301 | Value *I = cast<TruncInst>(A)->getOperand(0); |
| 8302 | if (I->getType() == CI.getType()) { |
| 8303 | unsigned MidSize = Src->getType()->getPrimitiveSizeInBits(); |
| 8304 | unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits(); |
| 8305 | unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize; |
| 8306 | Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt); |
| 8307 | I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV, |
| 8308 | CI.getName()), CI); |
| 8309 | return BinaryOperator::CreateAShr(I, ShAmtV); |
| 8310 | } |
| 8311 | } |
| 8312 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8313 | return 0; |
| 8314 | } |
| 8315 | |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8316 | /// FitsInFPType - Return a Constant* for the specified FP constant if it fits |
| 8317 | /// in the specified FP type without changing its value. |
Chris Lattner | 5e0610f | 2008-04-20 00:41:09 +0000 | [diff] [blame] | 8318 | static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) { |
Dale Johannesen | 6e547b4 | 2008-10-09 23:00:39 +0000 | [diff] [blame] | 8319 | bool losesInfo; |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8320 | APFloat F = CFP->getValueAPF(); |
Dale Johannesen | 6e547b4 | 2008-10-09 23:00:39 +0000 | [diff] [blame] | 8321 | (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo); |
| 8322 | if (!losesInfo) |
Chris Lattner | 5e0610f | 2008-04-20 00:41:09 +0000 | [diff] [blame] | 8323 | return ConstantFP::get(F); |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8324 | return 0; |
| 8325 | } |
| 8326 | |
| 8327 | /// LookThroughFPExtensions - If this is an fp extension instruction, look |
| 8328 | /// through it until we get the source value. |
| 8329 | static Value *LookThroughFPExtensions(Value *V) { |
| 8330 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 8331 | if (I->getOpcode() == Instruction::FPExt) |
| 8332 | return LookThroughFPExtensions(I->getOperand(0)); |
| 8333 | |
| 8334 | // If this value is a constant, return the constant in the smallest FP type |
| 8335 | // that can accurately represent it. This allows us to turn |
| 8336 | // (float)((double)X+2.0) into x+2.0f. |
| 8337 | if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { |
| 8338 | if (CFP->getType() == Type::PPC_FP128Ty) |
| 8339 | return V; // No constant folding of this. |
| 8340 | // See if the value can be truncated to float and then reextended. |
Chris Lattner | 5e0610f | 2008-04-20 00:41:09 +0000 | [diff] [blame] | 8341 | if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle)) |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8342 | return V; |
| 8343 | if (CFP->getType() == Type::DoubleTy) |
| 8344 | return V; // Won't shrink. |
Chris Lattner | 5e0610f | 2008-04-20 00:41:09 +0000 | [diff] [blame] | 8345 | if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble)) |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8346 | return V; |
| 8347 | // Don't try to shrink to various long double types. |
| 8348 | } |
| 8349 | |
| 8350 | return V; |
| 8351 | } |
| 8352 | |
| 8353 | Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) { |
| 8354 | if (Instruction *I = commonCastTransforms(CI)) |
| 8355 | return I; |
| 8356 | |
| 8357 | // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are |
| 8358 | // smaller than the destination type, we can eliminate the truncate by doing |
| 8359 | // the add as the smaller type. This applies to add/sub/mul/div as well as |
| 8360 | // many builtins (sqrt, etc). |
| 8361 | BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0)); |
| 8362 | if (OpI && OpI->hasOneUse()) { |
| 8363 | switch (OpI->getOpcode()) { |
| 8364 | default: break; |
| 8365 | case Instruction::Add: |
| 8366 | case Instruction::Sub: |
| 8367 | case Instruction::Mul: |
| 8368 | case Instruction::FDiv: |
| 8369 | case Instruction::FRem: |
| 8370 | const Type *SrcTy = OpI->getType(); |
| 8371 | Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0)); |
| 8372 | Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1)); |
| 8373 | if (LHSTrunc->getType() != SrcTy && |
| 8374 | RHSTrunc->getType() != SrcTy) { |
| 8375 | unsigned DstSize = CI.getType()->getPrimitiveSizeInBits(); |
| 8376 | // If the source types were both smaller than the destination type of |
| 8377 | // the cast, do this xform. |
| 8378 | if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize && |
| 8379 | RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) { |
| 8380 | LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc, |
| 8381 | CI.getType(), CI); |
| 8382 | RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc, |
| 8383 | CI.getType(), CI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8384 | return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc); |
Chris Lattner | df7e840 | 2008-01-27 05:29:54 +0000 | [diff] [blame] | 8385 | } |
| 8386 | } |
| 8387 | break; |
| 8388 | } |
| 8389 | } |
| 8390 | return 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8391 | } |
| 8392 | |
| 8393 | Instruction *InstCombiner::visitFPExt(CastInst &CI) { |
| 8394 | return commonCastTransforms(CI); |
| 8395 | } |
| 8396 | |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 8397 | Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) { |
Chris Lattner | 5f4d691 | 2008-08-06 05:13:06 +0000 | [diff] [blame] | 8398 | Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); |
| 8399 | if (OpI == 0) |
| 8400 | return commonCastTransforms(FI); |
| 8401 | |
| 8402 | // fptoui(uitofp(X)) --> X |
| 8403 | // fptoui(sitofp(X)) --> X |
| 8404 | // This is safe if the intermediate type has enough bits in its mantissa to |
| 8405 | // accurately represent all values of X. For example, do not do this with |
| 8406 | // i64->float->i64. This is also safe for sitofp case, because any negative |
| 8407 | // 'X' value would cause an undefined result for the fptoui. |
| 8408 | if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) && |
| 8409 | OpI->getOperand(0)->getType() == FI.getType() && |
| 8410 | (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */ |
| 8411 | OpI->getType()->getFPMantissaWidth()) |
| 8412 | return ReplaceInstUsesWith(FI, OpI->getOperand(0)); |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 8413 | |
| 8414 | return commonCastTransforms(FI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8415 | } |
| 8416 | |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 8417 | Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) { |
Chris Lattner | 5f4d691 | 2008-08-06 05:13:06 +0000 | [diff] [blame] | 8418 | Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0)); |
| 8419 | if (OpI == 0) |
| 8420 | return commonCastTransforms(FI); |
| 8421 | |
| 8422 | // fptosi(sitofp(X)) --> X |
| 8423 | // fptosi(uitofp(X)) --> X |
| 8424 | // This is safe if the intermediate type has enough bits in its mantissa to |
| 8425 | // accurately represent all values of X. For example, do not do this with |
| 8426 | // i64->float->i64. This is also safe for sitofp case, because any negative |
| 8427 | // 'X' value would cause an undefined result for the fptoui. |
| 8428 | if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) && |
| 8429 | OpI->getOperand(0)->getType() == FI.getType() && |
| 8430 | (int)FI.getType()->getPrimitiveSizeInBits() <= |
| 8431 | OpI->getType()->getFPMantissaWidth()) |
| 8432 | return ReplaceInstUsesWith(FI, OpI->getOperand(0)); |
Chris Lattner | deef1a7 | 2008-05-19 20:25:04 +0000 | [diff] [blame] | 8433 | |
| 8434 | return commonCastTransforms(FI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8435 | } |
| 8436 | |
| 8437 | Instruction *InstCombiner::visitUIToFP(CastInst &CI) { |
| 8438 | return commonCastTransforms(CI); |
| 8439 | } |
| 8440 | |
| 8441 | Instruction *InstCombiner::visitSIToFP(CastInst &CI) { |
| 8442 | return commonCastTransforms(CI); |
| 8443 | } |
| 8444 | |
| 8445 | Instruction *InstCombiner::visitPtrToInt(CastInst &CI) { |
| 8446 | return commonPointerCastTransforms(CI); |
| 8447 | } |
| 8448 | |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 8449 | Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) { |
| 8450 | if (Instruction *I = commonCastTransforms(CI)) |
| 8451 | return I; |
| 8452 | |
| 8453 | const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType(); |
| 8454 | if (!DestPointee->isSized()) return 0; |
| 8455 | |
| 8456 | // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP. |
| 8457 | ConstantInt *Cst; |
| 8458 | Value *X; |
| 8459 | if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)), |
| 8460 | m_ConstantInt(Cst)))) { |
| 8461 | // If the source and destination operands have the same type, see if this |
| 8462 | // is a single-index GEP. |
| 8463 | if (X->getType() == CI.getType()) { |
| 8464 | // Get the size of the pointee type. |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 8465 | uint64_t Size = TD->getTypePaddedSize(DestPointee); |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 8466 | |
| 8467 | // Convert the constant to intptr type. |
| 8468 | APInt Offset = Cst->getValue(); |
| 8469 | Offset.sextOrTrunc(TD->getPointerSizeInBits()); |
| 8470 | |
| 8471 | // If Offset is evenly divisible by Size, we can do this xform. |
| 8472 | if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){ |
| 8473 | Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size)); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 8474 | return GetElementPtrInst::Create(X, ConstantInt::get(Offset)); |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 8475 | } |
| 8476 | } |
| 8477 | // TODO: Could handle other cases, e.g. where add is indexing into field of |
| 8478 | // struct etc. |
| 8479 | } else if (CI.getOperand(0)->hasOneUse() && |
| 8480 | match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) { |
| 8481 | // Otherwise, if this is inttoptr(add x, cst), try to turn this into an |
| 8482 | // "inttoptr+GEP" instead of "add+intptr". |
| 8483 | |
| 8484 | // Get the size of the pointee type. |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 8485 | uint64_t Size = TD->getTypePaddedSize(DestPointee); |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 8486 | |
| 8487 | // Convert the constant to intptr type. |
| 8488 | APInt Offset = Cst->getValue(); |
| 8489 | Offset.sextOrTrunc(TD->getPointerSizeInBits()); |
| 8490 | |
| 8491 | // If Offset is evenly divisible by Size, we can do this xform. |
| 8492 | if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){ |
| 8493 | Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size)); |
| 8494 | |
| 8495 | Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(), |
| 8496 | "tmp"), CI); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 8497 | return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp"); |
Chris Lattner | 7c162648 | 2008-01-08 07:23:51 +0000 | [diff] [blame] | 8498 | } |
| 8499 | } |
| 8500 | return 0; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8501 | } |
| 8502 | |
| 8503 | Instruction *InstCombiner::visitBitCast(BitCastInst &CI) { |
| 8504 | // If the operands are integer typed then apply the integer transforms, |
| 8505 | // otherwise just apply the common ones. |
| 8506 | Value *Src = CI.getOperand(0); |
| 8507 | const Type *SrcTy = Src->getType(); |
| 8508 | const Type *DestTy = CI.getType(); |
| 8509 | |
| 8510 | if (SrcTy->isInteger() && DestTy->isInteger()) { |
| 8511 | if (Instruction *Result = commonIntCastTransforms(CI)) |
| 8512 | return Result; |
| 8513 | } else if (isa<PointerType>(SrcTy)) { |
| 8514 | if (Instruction *I = commonPointerCastTransforms(CI)) |
| 8515 | return I; |
| 8516 | } else { |
| 8517 | if (Instruction *Result = commonCastTransforms(CI)) |
| 8518 | return Result; |
| 8519 | } |
| 8520 | |
| 8521 | |
| 8522 | // Get rid of casts from one type to the same type. These are useless and can |
| 8523 | // be replaced by the operand. |
| 8524 | if (DestTy == Src->getType()) |
| 8525 | return ReplaceInstUsesWith(CI, Src); |
| 8526 | |
| 8527 | if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) { |
| 8528 | const PointerType *SrcPTy = cast<PointerType>(SrcTy); |
| 8529 | const Type *DstElTy = DstPTy->getElementType(); |
| 8530 | const Type *SrcElTy = SrcPTy->getElementType(); |
| 8531 | |
Nate Begeman | df5b361 | 2008-03-31 00:22:16 +0000 | [diff] [blame] | 8532 | // If the address spaces don't match, don't eliminate the bitcast, which is |
| 8533 | // required for changing types. |
| 8534 | if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace()) |
| 8535 | return 0; |
| 8536 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8537 | // If we are casting a malloc or alloca to a pointer to a type of the same |
| 8538 | // size, rewrite the allocation instruction to allocate the "right" type. |
| 8539 | if (AllocationInst *AI = dyn_cast<AllocationInst>(Src)) |
| 8540 | if (Instruction *V = PromoteCastOfAllocation(CI, *AI)) |
| 8541 | return V; |
| 8542 | |
| 8543 | // If the source and destination are pointers, and this cast is equivalent |
| 8544 | // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep. |
| 8545 | // This can enhance SROA and other transforms that want type-safe pointers. |
| 8546 | Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty); |
| 8547 | unsigned NumZeros = 0; |
| 8548 | while (SrcElTy != DstElTy && |
| 8549 | isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) && |
| 8550 | SrcElTy->getNumContainedTypes() /* not "{}" */) { |
| 8551 | SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt); |
| 8552 | ++NumZeros; |
| 8553 | } |
| 8554 | |
| 8555 | // If we found a path from the src to dest, create the getelementptr now. |
| 8556 | if (SrcElTy == DstElTy) { |
| 8557 | SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 8558 | return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", |
| 8559 | ((Instruction*) NULL)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8560 | } |
| 8561 | } |
| 8562 | |
| 8563 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) { |
| 8564 | if (SVI->hasOneUse()) { |
| 8565 | // Okay, we have (bitconvert (shuffle ..)). Check to see if this is |
| 8566 | // a bitconvert to a vector with the same # elts. |
| 8567 | if (isa<VectorType>(DestTy) && |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 8568 | cast<VectorType>(DestTy)->getNumElements() == |
| 8569 | SVI->getType()->getNumElements() && |
| 8570 | SVI->getType()->getNumElements() == |
| 8571 | cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8572 | CastInst *Tmp; |
| 8573 | // If either of the operands is a cast from CI.getType(), then |
| 8574 | // evaluating the shuffle in the casted destination's type will allow |
| 8575 | // us to eliminate at least one cast. |
| 8576 | if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && |
| 8577 | Tmp->getOperand(0)->getType() == DestTy) || |
| 8578 | ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && |
| 8579 | Tmp->getOperand(0)->getType() == DestTy)) { |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 8580 | Value *LHS = InsertCastBefore(Instruction::BitCast, |
| 8581 | SVI->getOperand(0), DestTy, CI); |
| 8582 | Value *RHS = InsertCastBefore(Instruction::BitCast, |
| 8583 | SVI->getOperand(1), DestTy, CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8584 | // Return a new shuffle vector. Use the same element ID's, as we |
| 8585 | // know the vector types match #elts. |
| 8586 | return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2)); |
| 8587 | } |
| 8588 | } |
| 8589 | } |
| 8590 | } |
| 8591 | return 0; |
| 8592 | } |
| 8593 | |
| 8594 | /// GetSelectFoldableOperands - We want to turn code that looks like this: |
| 8595 | /// %C = or %A, %B |
| 8596 | /// %D = select %cond, %C, %A |
| 8597 | /// into: |
| 8598 | /// %C = select %cond, %B, 0 |
| 8599 | /// %D = or %A, %C |
| 8600 | /// |
| 8601 | /// Assuming that the specified instruction is an operand to the select, return |
| 8602 | /// a bitmask indicating which operands of this instruction are foldable if they |
| 8603 | /// equal the other incoming value of the select. |
| 8604 | /// |
| 8605 | static unsigned GetSelectFoldableOperands(Instruction *I) { |
| 8606 | switch (I->getOpcode()) { |
| 8607 | case Instruction::Add: |
| 8608 | case Instruction::Mul: |
| 8609 | case Instruction::And: |
| 8610 | case Instruction::Or: |
| 8611 | case Instruction::Xor: |
| 8612 | return 3; // Can fold through either operand. |
| 8613 | case Instruction::Sub: // Can only fold on the amount subtracted. |
| 8614 | case Instruction::Shl: // Can only fold on the shift amount. |
| 8615 | case Instruction::LShr: |
| 8616 | case Instruction::AShr: |
| 8617 | return 1; |
| 8618 | default: |
| 8619 | return 0; // Cannot fold |
| 8620 | } |
| 8621 | } |
| 8622 | |
| 8623 | /// GetSelectFoldableConstant - For the same transformation as the previous |
| 8624 | /// function, return the identity constant that goes into the select. |
| 8625 | static Constant *GetSelectFoldableConstant(Instruction *I) { |
| 8626 | switch (I->getOpcode()) { |
| 8627 | default: assert(0 && "This cannot happen!"); abort(); |
| 8628 | case Instruction::Add: |
| 8629 | case Instruction::Sub: |
| 8630 | case Instruction::Or: |
| 8631 | case Instruction::Xor: |
| 8632 | case Instruction::Shl: |
| 8633 | case Instruction::LShr: |
| 8634 | case Instruction::AShr: |
| 8635 | return Constant::getNullValue(I->getType()); |
| 8636 | case Instruction::And: |
| 8637 | return Constant::getAllOnesValue(I->getType()); |
| 8638 | case Instruction::Mul: |
| 8639 | return ConstantInt::get(I->getType(), 1); |
| 8640 | } |
| 8641 | } |
| 8642 | |
| 8643 | /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI |
| 8644 | /// have the same opcode and only one use each. Try to simplify this. |
| 8645 | Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI, |
| 8646 | Instruction *FI) { |
| 8647 | if (TI->getNumOperands() == 1) { |
| 8648 | // If this is a non-volatile load or a cast from the same type, |
| 8649 | // merge. |
| 8650 | if (TI->isCast()) { |
| 8651 | if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType()) |
| 8652 | return 0; |
| 8653 | } else { |
| 8654 | return 0; // unknown unary op. |
| 8655 | } |
| 8656 | |
| 8657 | // Fold this by inserting a select from the input values. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 8658 | SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0), |
| 8659 | FI->getOperand(0), SI.getName()+".v"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8660 | InsertNewInstBefore(NewSI, SI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8661 | return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8662 | TI->getType()); |
| 8663 | } |
| 8664 | |
| 8665 | // Only handle binary operators here. |
| 8666 | if (!isa<BinaryOperator>(TI)) |
| 8667 | return 0; |
| 8668 | |
| 8669 | // Figure out if the operations have any operands in common. |
| 8670 | Value *MatchOp, *OtherOpT, *OtherOpF; |
| 8671 | bool MatchIsOpZero; |
| 8672 | if (TI->getOperand(0) == FI->getOperand(0)) { |
| 8673 | MatchOp = TI->getOperand(0); |
| 8674 | OtherOpT = TI->getOperand(1); |
| 8675 | OtherOpF = FI->getOperand(1); |
| 8676 | MatchIsOpZero = true; |
| 8677 | } else if (TI->getOperand(1) == FI->getOperand(1)) { |
| 8678 | MatchOp = TI->getOperand(1); |
| 8679 | OtherOpT = TI->getOperand(0); |
| 8680 | OtherOpF = FI->getOperand(0); |
| 8681 | MatchIsOpZero = false; |
| 8682 | } else if (!TI->isCommutative()) { |
| 8683 | return 0; |
| 8684 | } else if (TI->getOperand(0) == FI->getOperand(1)) { |
| 8685 | MatchOp = TI->getOperand(0); |
| 8686 | OtherOpT = TI->getOperand(1); |
| 8687 | OtherOpF = FI->getOperand(0); |
| 8688 | MatchIsOpZero = true; |
| 8689 | } else if (TI->getOperand(1) == FI->getOperand(0)) { |
| 8690 | MatchOp = TI->getOperand(1); |
| 8691 | OtherOpT = TI->getOperand(0); |
| 8692 | OtherOpF = FI->getOperand(1); |
| 8693 | MatchIsOpZero = true; |
| 8694 | } else { |
| 8695 | return 0; |
| 8696 | } |
| 8697 | |
| 8698 | // If we reach here, they do have operations in common. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 8699 | SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT, |
| 8700 | OtherOpF, SI.getName()+".v"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8701 | InsertNewInstBefore(NewSI, SI); |
| 8702 | |
| 8703 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) { |
| 8704 | if (MatchIsOpZero) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8705 | return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8706 | else |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8707 | return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8708 | } |
| 8709 | assert(0 && "Shouldn't get here"); |
| 8710 | return 0; |
| 8711 | } |
| 8712 | |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8713 | /// visitSelectInstWithICmp - Visit a SelectInst that has an |
| 8714 | /// ICmpInst as its first operand. |
| 8715 | /// |
| 8716 | Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI, |
| 8717 | ICmpInst *ICI) { |
| 8718 | bool Changed = false; |
| 8719 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 8720 | Value *CmpLHS = ICI->getOperand(0); |
| 8721 | Value *CmpRHS = ICI->getOperand(1); |
| 8722 | Value *TrueVal = SI.getTrueValue(); |
| 8723 | Value *FalseVal = SI.getFalseValue(); |
| 8724 | |
| 8725 | // Check cases where the comparison is with a constant that |
| 8726 | // can be adjusted to fit the min/max idiom. We may edit ICI in |
| 8727 | // place here, so make sure the select is the only user. |
| 8728 | if (ICI->hasOneUse()) |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8729 | if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) { |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8730 | switch (Pred) { |
| 8731 | default: break; |
| 8732 | case ICmpInst::ICMP_ULT: |
| 8733 | case ICmpInst::ICMP_SLT: { |
| 8734 | // X < MIN ? T : F --> F |
| 8735 | if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT)) |
| 8736 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8737 | // X < C ? X : C-1 --> X > C-1 ? C-1 : X |
| 8738 | Constant *AdjustedRHS = SubOne(CI); |
| 8739 | if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || |
| 8740 | (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { |
| 8741 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8742 | CmpRHS = AdjustedRHS; |
| 8743 | std::swap(FalseVal, TrueVal); |
| 8744 | ICI->setPredicate(Pred); |
| 8745 | ICI->setOperand(1, CmpRHS); |
| 8746 | SI.setOperand(1, TrueVal); |
| 8747 | SI.setOperand(2, FalseVal); |
| 8748 | Changed = true; |
| 8749 | } |
| 8750 | break; |
| 8751 | } |
| 8752 | case ICmpInst::ICMP_UGT: |
| 8753 | case ICmpInst::ICMP_SGT: { |
| 8754 | // X > MAX ? T : F --> F |
| 8755 | if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT)) |
| 8756 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8757 | // X > C ? X : C+1 --> X < C+1 ? C+1 : X |
| 8758 | Constant *AdjustedRHS = AddOne(CI); |
| 8759 | if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || |
| 8760 | (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { |
| 8761 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 8762 | CmpRHS = AdjustedRHS; |
| 8763 | std::swap(FalseVal, TrueVal); |
| 8764 | ICI->setPredicate(Pred); |
| 8765 | ICI->setOperand(1, CmpRHS); |
| 8766 | SI.setOperand(1, TrueVal); |
| 8767 | SI.setOperand(2, FalseVal); |
| 8768 | Changed = true; |
| 8769 | } |
| 8770 | break; |
| 8771 | } |
| 8772 | } |
| 8773 | |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8774 | // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed |
| 8775 | // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 8776 | CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 8777 | if (match(TrueVal, m_ConstantInt<-1>()) && |
| 8778 | match(FalseVal, m_ConstantInt<0>())) |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 8779 | Pred = ICI->getPredicate(); |
Chris Lattner | 73c1ddb | 2009-01-05 23:53:12 +0000 | [diff] [blame] | 8780 | else if (match(TrueVal, m_ConstantInt<0>()) && |
| 8781 | match(FalseVal, m_ConstantInt<-1>())) |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 8782 | Pred = CmpInst::getInversePredicate(ICI->getPredicate()); |
| 8783 | |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8784 | if (Pred != CmpInst::BAD_ICMP_PREDICATE) { |
| 8785 | // If we are just checking for a icmp eq of a single bit and zext'ing it |
| 8786 | // to an integer, then shift the bit to the appropriate place and then |
| 8787 | // cast to integer to avoid the comparison. |
| 8788 | const APInt &Op1CV = CI->getValue(); |
| 8789 | |
| 8790 | // sext (x <s 0) to i32 --> x>>s31 true if signbit set. |
| 8791 | // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear. |
| 8792 | if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) || |
Chris Lattner | 3b87408 | 2008-11-16 05:38:51 +0000 | [diff] [blame] | 8793 | (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) { |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8794 | Value *In = ICI->getOperand(0); |
| 8795 | Value *Sh = ConstantInt::get(In->getType(), |
| 8796 | In->getType()->getPrimitiveSizeInBits()-1); |
| 8797 | In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh, |
| 8798 | In->getName()+".lobit"), |
| 8799 | *ICI); |
Dan Gohman | 47a6077 | 2008-11-02 00:17:33 +0000 | [diff] [blame] | 8800 | if (In->getType() != SI.getType()) |
| 8801 | In = CastInst::CreateIntegerCast(In, SI.getType(), |
Dan Gohman | 35b7616 | 2008-10-30 20:40:10 +0000 | [diff] [blame] | 8802 | true/*SExt*/, "tmp", ICI); |
| 8803 | |
| 8804 | if (Pred == ICmpInst::ICMP_SGT) |
| 8805 | In = InsertNewInstBefore(BinaryOperator::CreateNot(In, |
| 8806 | In->getName()+".not"), *ICI); |
| 8807 | |
| 8808 | return ReplaceInstUsesWith(SI, In); |
| 8809 | } |
| 8810 | } |
| 8811 | } |
| 8812 | |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8813 | if (CmpLHS == TrueVal && CmpRHS == FalseVal) { |
| 8814 | // Transform (X == Y) ? X : Y -> Y |
| 8815 | if (Pred == ICmpInst::ICMP_EQ) |
| 8816 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8817 | // Transform (X != Y) ? X : Y -> X |
| 8818 | if (Pred == ICmpInst::ICMP_NE) |
| 8819 | return ReplaceInstUsesWith(SI, TrueVal); |
| 8820 | /// NOTE: if we wanted to, this is where to detect integer MIN/MAX |
| 8821 | |
| 8822 | } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) { |
| 8823 | // Transform (X == Y) ? Y : X -> X |
| 8824 | if (Pred == ICmpInst::ICMP_EQ) |
| 8825 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8826 | // Transform (X != Y) ? Y : X -> Y |
| 8827 | if (Pred == ICmpInst::ICMP_NE) |
| 8828 | return ReplaceInstUsesWith(SI, TrueVal); |
| 8829 | /// NOTE: if we wanted to, this is where to detect integer MIN/MAX |
| 8830 | } |
| 8831 | |
| 8832 | /// NOTE: if we wanted to, this is where to detect integer ABS |
| 8833 | |
| 8834 | return Changed ? &SI : 0; |
| 8835 | } |
| 8836 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8837 | Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { |
| 8838 | Value *CondVal = SI.getCondition(); |
| 8839 | Value *TrueVal = SI.getTrueValue(); |
| 8840 | Value *FalseVal = SI.getFalseValue(); |
| 8841 | |
| 8842 | // select true, X, Y -> X |
| 8843 | // select false, X, Y -> Y |
| 8844 | if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal)) |
| 8845 | return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal); |
| 8846 | |
| 8847 | // select C, X, X -> X |
| 8848 | if (TrueVal == FalseVal) |
| 8849 | return ReplaceInstUsesWith(SI, TrueVal); |
| 8850 | |
| 8851 | if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X |
| 8852 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8853 | if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X |
| 8854 | return ReplaceInstUsesWith(SI, TrueVal); |
| 8855 | if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y |
| 8856 | if (isa<Constant>(TrueVal)) |
| 8857 | return ReplaceInstUsesWith(SI, TrueVal); |
| 8858 | else |
| 8859 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8860 | } |
| 8861 | |
| 8862 | if (SI.getType() == Type::Int1Ty) { |
| 8863 | if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) { |
| 8864 | if (C->getZExtValue()) { |
| 8865 | // Change: A = select B, true, C --> A = or B, C |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8866 | return BinaryOperator::CreateOr(CondVal, FalseVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8867 | } else { |
| 8868 | // Change: A = select B, false, C --> A = and !B, C |
| 8869 | Value *NotCond = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8870 | InsertNewInstBefore(BinaryOperator::CreateNot(CondVal, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8871 | "not."+CondVal->getName()), SI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8872 | return BinaryOperator::CreateAnd(NotCond, FalseVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8873 | } |
| 8874 | } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) { |
| 8875 | if (C->getZExtValue() == false) { |
| 8876 | // Change: A = select B, C, false --> A = and B, C |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8877 | return BinaryOperator::CreateAnd(CondVal, TrueVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8878 | } else { |
| 8879 | // Change: A = select B, C, true --> A = or !B, C |
| 8880 | Value *NotCond = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8881 | InsertNewInstBefore(BinaryOperator::CreateNot(CondVal, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8882 | "not."+CondVal->getName()), SI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8883 | return BinaryOperator::CreateOr(NotCond, TrueVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8884 | } |
| 8885 | } |
Chris Lattner | 53f85a7 | 2007-11-25 21:27:53 +0000 | [diff] [blame] | 8886 | |
| 8887 | // select a, b, a -> a&b |
| 8888 | // select a, a, b -> a|b |
| 8889 | if (CondVal == TrueVal) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8890 | return BinaryOperator::CreateOr(CondVal, FalseVal); |
Chris Lattner | 53f85a7 | 2007-11-25 21:27:53 +0000 | [diff] [blame] | 8891 | else if (CondVal == FalseVal) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8892 | return BinaryOperator::CreateAnd(CondVal, TrueVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8893 | } |
| 8894 | |
| 8895 | // Selecting between two integer constants? |
| 8896 | if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal)) |
| 8897 | if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) { |
| 8898 | // select C, 1, 0 -> zext C to int |
| 8899 | if (FalseValC->isZero() && TrueValC->getValue() == 1) { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8900 | return CastInst::Create(Instruction::ZExt, CondVal, SI.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8901 | } else if (TrueValC->isZero() && FalseValC->getValue() == 1) { |
| 8902 | // select C, 0, 1 -> zext !C to int |
| 8903 | Value *NotCond = |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8904 | InsertNewInstBefore(BinaryOperator::CreateNot(CondVal, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8905 | "not."+CondVal->getName()), SI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8906 | return CastInst::Create(Instruction::ZExt, NotCond, SI.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8907 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8908 | |
| 8909 | if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) { |
| 8910 | |
| 8911 | // (x <s 0) ? -1 : 0 -> ashr x, 31 |
| 8912 | if (TrueValC->isAllOnesValue() && FalseValC->isZero()) |
| 8913 | if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) { |
| 8914 | if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) { |
| 8915 | // The comparison constant and the result are not neccessarily the |
| 8916 | // same width. Make an all-ones value by inserting a AShr. |
| 8917 | Value *X = IC->getOperand(0); |
| 8918 | uint32_t Bits = X->getType()->getPrimitiveSizeInBits(); |
| 8919 | Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8920 | Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8921 | ShAmt, "ones"); |
| 8922 | InsertNewInstBefore(SRA, SI); |
Eli Friedman | 722b479 | 2008-11-30 21:09:11 +0000 | [diff] [blame] | 8923 | |
| 8924 | // Then cast to the appropriate width. |
| 8925 | return CastInst::CreateIntegerCast(SRA, SI.getType(), true); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8926 | } |
| 8927 | } |
| 8928 | |
| 8929 | |
| 8930 | // If one of the constants is zero (we know they can't both be) and we |
| 8931 | // have an icmp instruction with zero, and we have an 'and' with the |
| 8932 | // non-constant value, eliminate this whole mess. This corresponds to |
| 8933 | // cases like this: ((X & 27) ? 27 : 0) |
| 8934 | if (TrueValC->isZero() || FalseValC->isZero()) |
| 8935 | if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) && |
| 8936 | cast<Constant>(IC->getOperand(1))->isNullValue()) |
| 8937 | if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0))) |
| 8938 | if (ICA->getOpcode() == Instruction::And && |
| 8939 | isa<ConstantInt>(ICA->getOperand(1)) && |
| 8940 | (ICA->getOperand(1) == TrueValC || |
| 8941 | ICA->getOperand(1) == FalseValC) && |
| 8942 | isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) { |
| 8943 | // Okay, now we know that everything is set up, we just don't |
| 8944 | // know whether we have a icmp_ne or icmp_eq and whether the |
| 8945 | // true or false val is the zero. |
| 8946 | bool ShouldNotVal = !TrueValC->isZero(); |
| 8947 | ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE; |
| 8948 | Value *V = ICA; |
| 8949 | if (ShouldNotVal) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 8950 | V = InsertNewInstBefore(BinaryOperator::Create( |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8951 | Instruction::Xor, V, ICA->getOperand(1)), SI); |
| 8952 | return ReplaceInstUsesWith(SI, V); |
| 8953 | } |
| 8954 | } |
| 8955 | } |
| 8956 | |
| 8957 | // See if we are selecting two values based on a comparison of the two values. |
| 8958 | if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { |
| 8959 | if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { |
| 8960 | // Transform (X == Y) ? X : Y -> Y |
Dale Johannesen | 2e1b769 | 2007-10-03 17:45:27 +0000 | [diff] [blame] | 8961 | if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { |
| 8962 | // This is not safe in general for floating point: |
| 8963 | // consider X== -0, Y== +0. |
| 8964 | // It becomes safe if either operand is a nonzero constant. |
| 8965 | ConstantFP *CFPt, *CFPf; |
| 8966 | if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && |
| 8967 | !CFPt->getValueAPF().isZero()) || |
| 8968 | ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && |
| 8969 | !CFPf->getValueAPF().isZero())) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8970 | return ReplaceInstUsesWith(SI, FalseVal); |
Dale Johannesen | 2e1b769 | 2007-10-03 17:45:27 +0000 | [diff] [blame] | 8971 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8972 | // Transform (X != Y) ? X : Y -> X |
| 8973 | if (FCI->getPredicate() == FCmpInst::FCMP_ONE) |
| 8974 | return ReplaceInstUsesWith(SI, TrueVal); |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8975 | // NOTE: if we wanted to, this is where to detect MIN/MAX |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8976 | |
| 8977 | } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ |
| 8978 | // Transform (X == Y) ? Y : X -> X |
Dale Johannesen | 2e1b769 | 2007-10-03 17:45:27 +0000 | [diff] [blame] | 8979 | if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { |
| 8980 | // This is not safe in general for floating point: |
| 8981 | // consider X== -0, Y== +0. |
| 8982 | // It becomes safe if either operand is a nonzero constant. |
| 8983 | ConstantFP *CFPt, *CFPf; |
| 8984 | if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && |
| 8985 | !CFPt->getValueAPF().isZero()) || |
| 8986 | ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && |
| 8987 | !CFPf->getValueAPF().isZero())) |
| 8988 | return ReplaceInstUsesWith(SI, FalseVal); |
| 8989 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8990 | // Transform (X != Y) ? Y : X -> Y |
| 8991 | if (FCI->getPredicate() == FCmpInst::FCMP_ONE) |
| 8992 | return ReplaceInstUsesWith(SI, TrueVal); |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8993 | // NOTE: if we wanted to, this is where to detect MIN/MAX |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8994 | } |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8995 | // NOTE: if we wanted to, this is where to detect ABS |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 8996 | } |
| 8997 | |
| 8998 | // See if we are selecting two values based on a comparison of the two values. |
Dan Gohman | 58c0963 | 2008-09-16 18:46:06 +0000 | [diff] [blame] | 8999 | if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) |
| 9000 | if (Instruction *Result = visitSelectInstWithICmp(SI, ICI)) |
| 9001 | return Result; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9002 | |
| 9003 | if (Instruction *TI = dyn_cast<Instruction>(TrueVal)) |
| 9004 | if (Instruction *FI = dyn_cast<Instruction>(FalseVal)) |
| 9005 | if (TI->hasOneUse() && FI->hasOneUse()) { |
| 9006 | Instruction *AddOp = 0, *SubOp = 0; |
| 9007 | |
| 9008 | // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) |
| 9009 | if (TI->getOpcode() == FI->getOpcode()) |
| 9010 | if (Instruction *IV = FoldSelectOpOp(SI, TI, FI)) |
| 9011 | return IV; |
| 9012 | |
| 9013 | // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is |
| 9014 | // even legal for FP. |
| 9015 | if (TI->getOpcode() == Instruction::Sub && |
| 9016 | FI->getOpcode() == Instruction::Add) { |
| 9017 | AddOp = FI; SubOp = TI; |
| 9018 | } else if (FI->getOpcode() == Instruction::Sub && |
| 9019 | TI->getOpcode() == Instruction::Add) { |
| 9020 | AddOp = TI; SubOp = FI; |
| 9021 | } |
| 9022 | |
| 9023 | if (AddOp) { |
| 9024 | Value *OtherAddOp = 0; |
| 9025 | if (SubOp->getOperand(0) == AddOp->getOperand(0)) { |
| 9026 | OtherAddOp = AddOp->getOperand(1); |
| 9027 | } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { |
| 9028 | OtherAddOp = AddOp->getOperand(0); |
| 9029 | } |
| 9030 | |
| 9031 | if (OtherAddOp) { |
| 9032 | // So at this point we know we have (Y -> OtherAddOp): |
| 9033 | // select C, (add X, Y), (sub X, Z) |
| 9034 | Value *NegVal; // Compute -Z |
| 9035 | if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) { |
| 9036 | NegVal = ConstantExpr::getNeg(C); |
| 9037 | } else { |
| 9038 | NegVal = InsertNewInstBefore( |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9039 | BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9040 | } |
| 9041 | |
| 9042 | Value *NewTrueOp = OtherAddOp; |
| 9043 | Value *NewFalseOp = NegVal; |
| 9044 | if (AddOp != TI) |
| 9045 | std::swap(NewTrueOp, NewFalseOp); |
| 9046 | Instruction *NewSel = |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 9047 | SelectInst::Create(CondVal, NewTrueOp, |
| 9048 | NewFalseOp, SI.getName() + ".p"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9049 | |
| 9050 | NewSel = InsertNewInstBefore(NewSel, SI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9051 | return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9052 | } |
| 9053 | } |
| 9054 | } |
| 9055 | |
| 9056 | // See if we can fold the select into one of our operands. |
| 9057 | if (SI.getType()->isInteger()) { |
| 9058 | // See the comment above GetSelectFoldableOperands for a description of the |
| 9059 | // transformation we are doing here. |
| 9060 | if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) |
| 9061 | if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && |
| 9062 | !isa<Constant>(FalseVal)) |
| 9063 | if (unsigned SFO = GetSelectFoldableOperands(TVI)) { |
| 9064 | unsigned OpToFold = 0; |
| 9065 | if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { |
| 9066 | OpToFold = 1; |
| 9067 | } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { |
| 9068 | OpToFold = 2; |
| 9069 | } |
| 9070 | |
| 9071 | if (OpToFold) { |
| 9072 | Constant *C = GetSelectFoldableConstant(TVI); |
| 9073 | Instruction *NewSel = |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 9074 | SelectInst::Create(SI.getCondition(), |
| 9075 | TVI->getOperand(2-OpToFold), C); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9076 | InsertNewInstBefore(NewSel, SI); |
| 9077 | NewSel->takeName(TVI); |
| 9078 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9079 | return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9080 | else { |
| 9081 | assert(0 && "Unknown instruction!!"); |
| 9082 | } |
| 9083 | } |
| 9084 | } |
| 9085 | |
| 9086 | if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) |
| 9087 | if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && |
| 9088 | !isa<Constant>(TrueVal)) |
| 9089 | if (unsigned SFO = GetSelectFoldableOperands(FVI)) { |
| 9090 | unsigned OpToFold = 0; |
| 9091 | if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { |
| 9092 | OpToFold = 1; |
| 9093 | } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { |
| 9094 | OpToFold = 2; |
| 9095 | } |
| 9096 | |
| 9097 | if (OpToFold) { |
| 9098 | Constant *C = GetSelectFoldableConstant(FVI); |
| 9099 | Instruction *NewSel = |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 9100 | SelectInst::Create(SI.getCondition(), C, |
| 9101 | FVI->getOperand(2-OpToFold)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9102 | InsertNewInstBefore(NewSel, SI); |
| 9103 | NewSel->takeName(FVI); |
| 9104 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9105 | return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9106 | else |
| 9107 | assert(0 && "Unknown instruction!!"); |
| 9108 | } |
| 9109 | } |
| 9110 | } |
| 9111 | |
| 9112 | if (BinaryOperator::isNot(CondVal)) { |
| 9113 | SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); |
| 9114 | SI.setOperand(1, FalseVal); |
| 9115 | SI.setOperand(2, TrueVal); |
| 9116 | return &SI; |
| 9117 | } |
| 9118 | |
| 9119 | return 0; |
| 9120 | } |
| 9121 | |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9122 | /// EnforceKnownAlignment - If the specified pointer points to an object that |
| 9123 | /// we control, modify the object's alignment to PrefAlign. This isn't |
| 9124 | /// often possible though. If alignment is important, a more reliable approach |
| 9125 | /// is to simply align all global variables and allocation instructions to |
| 9126 | /// their preferred alignment from the beginning. |
| 9127 | /// |
| 9128 | static unsigned EnforceKnownAlignment(Value *V, |
| 9129 | unsigned Align, unsigned PrefAlign) { |
Chris Lattner | 47cf345 | 2007-08-09 19:05:49 +0000 | [diff] [blame] | 9130 | |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9131 | User *U = dyn_cast<User>(V); |
| 9132 | if (!U) return Align; |
| 9133 | |
| 9134 | switch (getOpcode(U)) { |
| 9135 | default: break; |
| 9136 | case Instruction::BitCast: |
| 9137 | return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign); |
| 9138 | case Instruction::GetElementPtr: { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9139 | // If all indexes are zero, it is just the alignment of the base pointer. |
| 9140 | bool AllZeroOperands = true; |
Gabor Greif | e92fbe2 | 2008-06-12 21:51:29 +0000 | [diff] [blame] | 9141 | for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i) |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 9142 | if (!isa<Constant>(*i) || |
| 9143 | !cast<Constant>(*i)->isNullValue()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9144 | AllZeroOperands = false; |
| 9145 | break; |
| 9146 | } |
Chris Lattner | 47cf345 | 2007-08-09 19:05:49 +0000 | [diff] [blame] | 9147 | |
| 9148 | if (AllZeroOperands) { |
| 9149 | // Treat this like a bitcast. |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9150 | return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign); |
Chris Lattner | 47cf345 | 2007-08-09 19:05:49 +0000 | [diff] [blame] | 9151 | } |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9152 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9153 | } |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9154 | } |
| 9155 | |
| 9156 | if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { |
| 9157 | // If there is a large requested alignment and we can, bump up the alignment |
| 9158 | // of the global. |
| 9159 | if (!GV->isDeclaration()) { |
| 9160 | GV->setAlignment(PrefAlign); |
| 9161 | Align = PrefAlign; |
| 9162 | } |
| 9163 | } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) { |
| 9164 | // If there is a requested alignment and if this is an alloca, round up. We |
| 9165 | // don't do this for malloc, because some systems can't respect the request. |
| 9166 | if (isa<AllocaInst>(AI)) { |
| 9167 | AI->setAlignment(PrefAlign); |
| 9168 | Align = PrefAlign; |
| 9169 | } |
| 9170 | } |
| 9171 | |
| 9172 | return Align; |
| 9173 | } |
| 9174 | |
| 9175 | /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that |
| 9176 | /// we can determine, return it, otherwise return 0. If PrefAlign is specified, |
| 9177 | /// and it is more than the alignment of the ultimate object, see if we can |
| 9178 | /// increase the alignment of the ultimate object, making this check succeed. |
| 9179 | unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V, |
| 9180 | unsigned PrefAlign) { |
| 9181 | unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) : |
| 9182 | sizeof(PrefAlign) * CHAR_BIT; |
| 9183 | APInt Mask = APInt::getAllOnesValue(BitWidth); |
| 9184 | APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); |
| 9185 | ComputeMaskedBits(V, Mask, KnownZero, KnownOne); |
| 9186 | unsigned TrailZ = KnownZero.countTrailingOnes(); |
| 9187 | unsigned Align = 1u << std::min(BitWidth - 1, TrailZ); |
| 9188 | |
| 9189 | if (PrefAlign > Align) |
| 9190 | Align = EnforceKnownAlignment(V, Align, PrefAlign); |
| 9191 | |
| 9192 | // We don't need to make any adjustment. |
| 9193 | return Align; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9194 | } |
| 9195 | |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9196 | Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) { |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 9197 | unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1)); |
| 9198 | unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2)); |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9199 | unsigned MinAlign = std::min(DstAlign, SrcAlign); |
| 9200 | unsigned CopyAlign = MI->getAlignment()->getZExtValue(); |
| 9201 | |
| 9202 | if (CopyAlign < MinAlign) { |
| 9203 | MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign)); |
| 9204 | return MI; |
| 9205 | } |
| 9206 | |
| 9207 | // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with |
| 9208 | // load/store. |
| 9209 | ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3)); |
| 9210 | if (MemOpLength == 0) return 0; |
| 9211 | |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9212 | // Source and destination pointer types are always "i8*" for intrinsic. See |
| 9213 | // if the size is something we can handle with a single primitive load/store. |
| 9214 | // A single load+store correctly handles overlapping memory in the memmove |
| 9215 | // case. |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9216 | unsigned Size = MemOpLength->getZExtValue(); |
Chris Lattner | 5af8a91 | 2008-04-30 06:39:11 +0000 | [diff] [blame] | 9217 | if (Size == 0) return MI; // Delete this mem transfer. |
| 9218 | |
| 9219 | if (Size > 8 || (Size&(Size-1))) |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9220 | return 0; // If not 1/2/4/8 bytes, exit. |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9221 | |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9222 | // Use an integer load+store unless we can find something better. |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9223 | Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3)); |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9224 | |
| 9225 | // Memcpy forces the use of i8* for the source and destination. That means |
| 9226 | // that if you're using memcpy to move one double around, you'll get a cast |
| 9227 | // from double* to i8*. We'd much rather use a double load+store rather than |
| 9228 | // an i64 load+store, here because this improves the odds that the source or |
| 9229 | // dest address will be promotable. See if we can find a better type than the |
| 9230 | // integer datatype. |
| 9231 | if (Value *Op = getBitCastOperand(MI->getOperand(1))) { |
| 9232 | const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType(); |
| 9233 | if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) { |
| 9234 | // The SrcETy might be something like {{{double}}} or [1 x double]. Rip |
| 9235 | // down through these levels if so. |
Dan Gohman | b8e94f6 | 2008-05-23 01:52:21 +0000 | [diff] [blame] | 9236 | while (!SrcETy->isSingleValueType()) { |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9237 | if (const StructType *STy = dyn_cast<StructType>(SrcETy)) { |
| 9238 | if (STy->getNumElements() == 1) |
| 9239 | SrcETy = STy->getElementType(0); |
| 9240 | else |
| 9241 | break; |
| 9242 | } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) { |
| 9243 | if (ATy->getNumElements() == 1) |
| 9244 | SrcETy = ATy->getElementType(); |
| 9245 | else |
| 9246 | break; |
| 9247 | } else |
| 9248 | break; |
| 9249 | } |
| 9250 | |
Dan Gohman | b8e94f6 | 2008-05-23 01:52:21 +0000 | [diff] [blame] | 9251 | if (SrcETy->isSingleValueType()) |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9252 | NewPtrTy = PointerType::getUnqual(SrcETy); |
| 9253 | } |
| 9254 | } |
| 9255 | |
| 9256 | |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9257 | // If the memcpy/memmove provides better alignment info than we can |
| 9258 | // infer, use it. |
| 9259 | SrcAlign = std::max(SrcAlign, CopyAlign); |
| 9260 | DstAlign = std::max(DstAlign, CopyAlign); |
| 9261 | |
| 9262 | Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI); |
| 9263 | Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI); |
Chris Lattner | c669fb6 | 2008-01-14 00:28:35 +0000 | [diff] [blame] | 9264 | Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign); |
| 9265 | InsertNewInstBefore(L, *MI); |
| 9266 | InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI); |
| 9267 | |
| 9268 | // Set the size of the copy to 0, it will be deleted on the next iteration. |
| 9269 | MI->setOperand(3, Constant::getNullValue(MemOpLength->getType())); |
| 9270 | return MI; |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9271 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9272 | |
Chris Lattner | 5af8a91 | 2008-04-30 06:39:11 +0000 | [diff] [blame] | 9273 | Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) { |
| 9274 | unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest()); |
| 9275 | if (MI->getAlignment()->getZExtValue() < Alignment) { |
| 9276 | MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment)); |
| 9277 | return MI; |
| 9278 | } |
| 9279 | |
| 9280 | // Extract the length and alignment and fill if they are constant. |
| 9281 | ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); |
| 9282 | ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); |
| 9283 | if (!LenC || !FillC || FillC->getType() != Type::Int8Ty) |
| 9284 | return 0; |
| 9285 | uint64_t Len = LenC->getZExtValue(); |
| 9286 | Alignment = MI->getAlignment()->getZExtValue(); |
| 9287 | |
| 9288 | // If the length is zero, this is a no-op |
| 9289 | if (Len == 0) return MI; // memset(d,c,0,a) -> noop |
| 9290 | |
| 9291 | // memset(s,c,n) -> store s, c (for n=1,2,4,8) |
| 9292 | if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { |
| 9293 | const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8. |
| 9294 | |
| 9295 | Value *Dest = MI->getDest(); |
| 9296 | Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI); |
| 9297 | |
| 9298 | // Alignment 0 is identity for alignment 1 for memset, but not store. |
| 9299 | if (Alignment == 0) Alignment = 1; |
| 9300 | |
| 9301 | // Extract the fill value and store. |
| 9302 | uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; |
| 9303 | InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false, |
| 9304 | Alignment), *MI); |
| 9305 | |
| 9306 | // Set the size of the copy to 0, it will be deleted on the next iteration. |
| 9307 | MI->setLength(Constant::getNullValue(LenC->getType())); |
| 9308 | return MI; |
| 9309 | } |
| 9310 | |
| 9311 | return 0; |
| 9312 | } |
| 9313 | |
| 9314 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9315 | /// visitCallInst - CallInst simplification. This mostly only handles folding |
| 9316 | /// of intrinsic instructions. For normal calls, it allows visitCallSite to do |
| 9317 | /// the heavy lifting. |
| 9318 | /// |
| 9319 | Instruction *InstCombiner::visitCallInst(CallInst &CI) { |
| 9320 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); |
| 9321 | if (!II) return visitCallSite(&CI); |
| 9322 | |
| 9323 | // Intrinsics cannot occur in an invoke, so handle them here instead of in |
| 9324 | // visitCallSite. |
| 9325 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) { |
| 9326 | bool Changed = false; |
| 9327 | |
| 9328 | // memmove/cpy/set of zero bytes is a noop. |
| 9329 | if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { |
| 9330 | if (NumBytes->isNullValue()) return EraseInstFromFunction(CI); |
| 9331 | |
| 9332 | if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) |
| 9333 | if (CI->getZExtValue() == 1) { |
| 9334 | // Replace the instruction with just byte operations. We would |
| 9335 | // transform other cases to loads/stores, but we don't know if |
| 9336 | // alignment is sufficient. |
| 9337 | } |
| 9338 | } |
| 9339 | |
| 9340 | // If we have a memmove and the source operation is a constant global, |
| 9341 | // then the source and dest pointers can't alias, so we can change this |
| 9342 | // into a call to memcpy. |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9343 | if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9344 | if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) |
| 9345 | if (GVSrc->isConstant()) { |
| 9346 | Module *M = CI.getParent()->getParent()->getParent(); |
Chris Lattner | 82c2e43 | 2008-11-21 16:42:48 +0000 | [diff] [blame] | 9347 | Intrinsic::ID MemCpyID = Intrinsic::memcpy; |
| 9348 | const Type *Tys[1]; |
| 9349 | Tys[0] = CI.getOperand(3)->getType(); |
| 9350 | CI.setOperand(0, |
| 9351 | Intrinsic::getDeclaration(M, MemCpyID, Tys, 1)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9352 | Changed = true; |
| 9353 | } |
Chris Lattner | 59b27d9 | 2008-05-28 05:30:41 +0000 | [diff] [blame] | 9354 | |
| 9355 | // memmove(x,x,size) -> noop. |
| 9356 | if (MMI->getSource() == MMI->getDest()) |
| 9357 | return EraseInstFromFunction(CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9358 | } |
| 9359 | |
| 9360 | // If we can determine a pointer alignment that is bigger than currently |
| 9361 | // set, update the alignment. |
| 9362 | if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) { |
Chris Lattner | 00ae513 | 2008-01-13 23:50:23 +0000 | [diff] [blame] | 9363 | if (Instruction *I = SimplifyMemTransfer(MI)) |
| 9364 | return I; |
Chris Lattner | 5af8a91 | 2008-04-30 06:39:11 +0000 | [diff] [blame] | 9365 | } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) { |
| 9366 | if (Instruction *I = SimplifyMemSet(MSI)) |
| 9367 | return I; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9368 | } |
| 9369 | |
| 9370 | if (Changed) return II; |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9371 | } |
| 9372 | |
| 9373 | switch (II->getIntrinsicID()) { |
| 9374 | default: break; |
| 9375 | case Intrinsic::bswap: |
| 9376 | // bswap(bswap(x)) -> x |
| 9377 | if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1))) |
| 9378 | if (Operand->getIntrinsicID() == Intrinsic::bswap) |
| 9379 | return ReplaceInstUsesWith(CI, Operand->getOperand(1)); |
| 9380 | break; |
| 9381 | case Intrinsic::ppc_altivec_lvx: |
| 9382 | case Intrinsic::ppc_altivec_lvxl: |
| 9383 | case Intrinsic::x86_sse_loadu_ps: |
| 9384 | case Intrinsic::x86_sse2_loadu_pd: |
| 9385 | case Intrinsic::x86_sse2_loadu_dq: |
| 9386 | // Turn PPC lvx -> load if the pointer is known aligned. |
| 9387 | // Turn X86 loadups -> load if the pointer is known aligned. |
| 9388 | if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) { |
| 9389 | Value *Ptr = InsertBitCastBefore(II->getOperand(1), |
| 9390 | PointerType::getUnqual(II->getType()), |
| 9391 | CI); |
| 9392 | return new LoadInst(Ptr); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9393 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9394 | break; |
| 9395 | case Intrinsic::ppc_altivec_stvx: |
| 9396 | case Intrinsic::ppc_altivec_stvxl: |
| 9397 | // Turn stvx -> store if the pointer is known aligned. |
| 9398 | if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) { |
| 9399 | const Type *OpPtrTy = |
| 9400 | PointerType::getUnqual(II->getOperand(1)->getType()); |
| 9401 | Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI); |
| 9402 | return new StoreInst(II->getOperand(1), Ptr); |
| 9403 | } |
| 9404 | break; |
| 9405 | case Intrinsic::x86_sse_storeu_ps: |
| 9406 | case Intrinsic::x86_sse2_storeu_pd: |
| 9407 | case Intrinsic::x86_sse2_storeu_dq: |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9408 | // Turn X86 storeu -> store if the pointer is known aligned. |
| 9409 | if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) { |
| 9410 | const Type *OpPtrTy = |
| 9411 | PointerType::getUnqual(II->getOperand(2)->getType()); |
| 9412 | Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI); |
| 9413 | return new StoreInst(II->getOperand(2), Ptr); |
| 9414 | } |
| 9415 | break; |
| 9416 | |
| 9417 | case Intrinsic::x86_sse_cvttss2si: { |
| 9418 | // These intrinsics only demands the 0th element of its input vector. If |
| 9419 | // we can simplify the input based on that, do so now. |
| 9420 | uint64_t UndefElts; |
| 9421 | if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, |
| 9422 | UndefElts)) { |
| 9423 | II->setOperand(1, V); |
| 9424 | return II; |
| 9425 | } |
| 9426 | break; |
| 9427 | } |
| 9428 | |
| 9429 | case Intrinsic::ppc_altivec_vperm: |
| 9430 | // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. |
| 9431 | if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) { |
| 9432 | assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9433 | |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9434 | // Check that all of the elements are integer constants or undefs. |
| 9435 | bool AllEltsOk = true; |
| 9436 | for (unsigned i = 0; i != 16; ++i) { |
| 9437 | if (!isa<ConstantInt>(Mask->getOperand(i)) && |
| 9438 | !isa<UndefValue>(Mask->getOperand(i))) { |
| 9439 | AllEltsOk = false; |
| 9440 | break; |
| 9441 | } |
| 9442 | } |
| 9443 | |
| 9444 | if (AllEltsOk) { |
| 9445 | // Cast the input vectors to byte vectors. |
| 9446 | Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI); |
| 9447 | Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI); |
| 9448 | Value *Result = UndefValue::get(Op0->getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9449 | |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9450 | // Only extract each element once. |
| 9451 | Value *ExtractedElts[32]; |
| 9452 | memset(ExtractedElts, 0, sizeof(ExtractedElts)); |
| 9453 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9454 | for (unsigned i = 0; i != 16; ++i) { |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9455 | if (isa<UndefValue>(Mask->getOperand(i))) |
| 9456 | continue; |
| 9457 | unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue(); |
| 9458 | Idx &= 31; // Match the hardware behavior. |
| 9459 | |
| 9460 | if (ExtractedElts[Idx] == 0) { |
| 9461 | Instruction *Elt = |
| 9462 | new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp"); |
| 9463 | InsertNewInstBefore(Elt, CI); |
| 9464 | ExtractedElts[Idx] = Elt; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9465 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9466 | |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9467 | // Insert this value into the result vector. |
| 9468 | Result = InsertElementInst::Create(Result, ExtractedElts[Idx], |
| 9469 | i, "tmp"); |
| 9470 | InsertNewInstBefore(cast<Instruction>(Result), CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9471 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9472 | return CastInst::Create(Instruction::BitCast, Result, CI.getType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9473 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9474 | } |
| 9475 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9476 | |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9477 | case Intrinsic::stackrestore: { |
| 9478 | // If the save is right next to the restore, remove the restore. This can |
| 9479 | // happen when variable allocas are DCE'd. |
| 9480 | if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) { |
| 9481 | if (SS->getIntrinsicID() == Intrinsic::stacksave) { |
| 9482 | BasicBlock::iterator BI = SS; |
| 9483 | if (&*++BI == II) |
| 9484 | return EraseInstFromFunction(CI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9485 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9486 | } |
| 9487 | |
| 9488 | // Scan down this block to see if there is another stack restore in the |
| 9489 | // same block without an intervening call/alloca. |
| 9490 | BasicBlock::iterator BI = II; |
| 9491 | TerminatorInst *TI = II->getParent()->getTerminator(); |
| 9492 | bool CannotRemove = false; |
| 9493 | for (++BI; &*BI != TI; ++BI) { |
| 9494 | if (isa<AllocaInst>(BI)) { |
| 9495 | CannotRemove = true; |
| 9496 | break; |
| 9497 | } |
Chris Lattner | a6b477c | 2008-06-25 05:59:28 +0000 | [diff] [blame] | 9498 | if (CallInst *BCI = dyn_cast<CallInst>(BI)) { |
| 9499 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { |
| 9500 | // If there is a stackrestore below this one, remove this one. |
| 9501 | if (II->getIntrinsicID() == Intrinsic::stackrestore) |
| 9502 | return EraseInstFromFunction(CI); |
| 9503 | // Otherwise, ignore the intrinsic. |
| 9504 | } else { |
| 9505 | // If we found a non-intrinsic call, we can't remove the stack |
| 9506 | // restore. |
Chris Lattner | 416d91c | 2008-02-18 06:12:38 +0000 | [diff] [blame] | 9507 | CannotRemove = true; |
| 9508 | break; |
| 9509 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9510 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9511 | } |
Chris Lattner | 989ba31 | 2008-06-18 04:33:20 +0000 | [diff] [blame] | 9512 | |
| 9513 | // If the stack restore is in a return/unwind block and if there are no |
| 9514 | // allocas or calls between the restore and the return, nuke the restore. |
| 9515 | if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI))) |
| 9516 | return EraseInstFromFunction(CI); |
| 9517 | break; |
| 9518 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9519 | } |
| 9520 | |
| 9521 | return visitCallSite(II); |
| 9522 | } |
| 9523 | |
| 9524 | // InvokeInst simplification |
| 9525 | // |
| 9526 | Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { |
| 9527 | return visitCallSite(&II); |
| 9528 | } |
| 9529 | |
Dale Johannesen | 9602183 | 2008-04-25 21:16:07 +0000 | [diff] [blame] | 9530 | /// isSafeToEliminateVarargsCast - If this cast does not affect the value |
| 9531 | /// passed through the varargs area, we can eliminate the use of the cast. |
Dale Johannesen | 3561546 | 2008-04-23 18:34:37 +0000 | [diff] [blame] | 9532 | static bool isSafeToEliminateVarargsCast(const CallSite CS, |
| 9533 | const CastInst * const CI, |
| 9534 | const TargetData * const TD, |
| 9535 | const int ix) { |
| 9536 | if (!CI->isLosslessCast()) |
| 9537 | return false; |
| 9538 | |
| 9539 | // The size of ByVal arguments is derived from the type, so we |
| 9540 | // can't change to a type with a different size. If the size were |
| 9541 | // passed explicitly we could avoid this check. |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9542 | if (!CS.paramHasAttr(ix, Attribute::ByVal)) |
Dale Johannesen | 3561546 | 2008-04-23 18:34:37 +0000 | [diff] [blame] | 9543 | return true; |
| 9544 | |
| 9545 | const Type* SrcTy = |
| 9546 | cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); |
| 9547 | const Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); |
| 9548 | if (!SrcTy->isSized() || !DstTy->isSized()) |
| 9549 | return false; |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 9550 | if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy)) |
Dale Johannesen | 3561546 | 2008-04-23 18:34:37 +0000 | [diff] [blame] | 9551 | return false; |
| 9552 | return true; |
| 9553 | } |
| 9554 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9555 | // visitCallSite - Improvements for call and invoke instructions. |
| 9556 | // |
| 9557 | Instruction *InstCombiner::visitCallSite(CallSite CS) { |
| 9558 | bool Changed = false; |
| 9559 | |
| 9560 | // If the callee is a constexpr cast of a function, attempt to move the cast |
| 9561 | // to the arguments of the call/invoke. |
| 9562 | if (transformConstExprCastCall(CS)) return 0; |
| 9563 | |
| 9564 | Value *Callee = CS.getCalledValue(); |
| 9565 | |
| 9566 | if (Function *CalleeF = dyn_cast<Function>(Callee)) |
| 9567 | if (CalleeF->getCallingConv() != CS.getCallingConv()) { |
| 9568 | Instruction *OldCall = CS.getInstruction(); |
| 9569 | // If the call and callee calling conventions don't match, this call must |
| 9570 | // be unreachable, as the call is undefined. |
| 9571 | new StoreInst(ConstantInt::getTrue(), |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 9572 | UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), |
| 9573 | OldCall); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9574 | if (!OldCall->use_empty()) |
| 9575 | OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType())); |
| 9576 | if (isa<CallInst>(OldCall)) // Not worth removing an invoke here. |
| 9577 | return EraseInstFromFunction(*OldCall); |
| 9578 | return 0; |
| 9579 | } |
| 9580 | |
| 9581 | if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { |
| 9582 | // This instruction is not reachable, just remove it. We insert a store to |
| 9583 | // undef so that we know that this code is not reachable, despite the fact |
| 9584 | // that we can't modify the CFG here. |
| 9585 | new StoreInst(ConstantInt::getTrue(), |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 9586 | UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9587 | CS.getInstruction()); |
| 9588 | |
| 9589 | if (!CS.getInstruction()->use_empty()) |
| 9590 | CS.getInstruction()-> |
| 9591 | replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType())); |
| 9592 | |
| 9593 | if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 9594 | // Don't break the CFG, insert a dummy cond branch. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 9595 | BranchInst::Create(II->getNormalDest(), II->getUnwindDest(), |
| 9596 | ConstantInt::getTrue(), II); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9597 | } |
| 9598 | return EraseInstFromFunction(*CS.getInstruction()); |
| 9599 | } |
| 9600 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9601 | if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee)) |
| 9602 | if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0))) |
| 9603 | if (In->getIntrinsicID() == Intrinsic::init_trampoline) |
| 9604 | return transformCallThroughTrampoline(CS); |
| 9605 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9606 | const PointerType *PTy = cast<PointerType>(Callee->getType()); |
| 9607 | const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); |
| 9608 | if (FTy->isVarArg()) { |
Dale Johannesen | 502336c | 2008-04-23 01:03:05 +0000 | [diff] [blame] | 9609 | int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9610 | // See if we can optimize any arguments passed through the varargs area of |
| 9611 | // the call. |
| 9612 | for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(), |
Dale Johannesen | 3561546 | 2008-04-23 18:34:37 +0000 | [diff] [blame] | 9613 | E = CS.arg_end(); I != E; ++I, ++ix) { |
| 9614 | CastInst *CI = dyn_cast<CastInst>(*I); |
| 9615 | if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) { |
| 9616 | *I = CI->getOperand(0); |
| 9617 | Changed = true; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9618 | } |
Dale Johannesen | 3561546 | 2008-04-23 18:34:37 +0000 | [diff] [blame] | 9619 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9620 | } |
| 9621 | |
Duncan Sands | 2937e35 | 2007-12-19 21:13:37 +0000 | [diff] [blame] | 9622 | if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) { |
Duncan Sands | 7868f3c | 2007-12-16 15:51:49 +0000 | [diff] [blame] | 9623 | // Inline asm calls cannot throw - mark them 'nounwind'. |
Duncan Sands | 2937e35 | 2007-12-19 21:13:37 +0000 | [diff] [blame] | 9624 | CS.setDoesNotThrow(); |
Duncan Sands | 7868f3c | 2007-12-16 15:51:49 +0000 | [diff] [blame] | 9625 | Changed = true; |
| 9626 | } |
| 9627 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9628 | return Changed ? CS.getInstruction() : 0; |
| 9629 | } |
| 9630 | |
| 9631 | // transformConstExprCastCall - If the callee is a constexpr cast of a function, |
| 9632 | // attempt to move the cast to the arguments of the call/invoke. |
| 9633 | // |
| 9634 | bool InstCombiner::transformConstExprCastCall(CallSite CS) { |
| 9635 | if (!isa<ConstantExpr>(CS.getCalledValue())) return false; |
| 9636 | ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue()); |
| 9637 | if (CE->getOpcode() != Instruction::BitCast || |
| 9638 | !isa<Function>(CE->getOperand(0))) |
| 9639 | return false; |
| 9640 | Function *Callee = cast<Function>(CE->getOperand(0)); |
| 9641 | Instruction *Caller = CS.getInstruction(); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9642 | const AttrListPtr &CallerPAL = CS.getAttributes(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9643 | |
| 9644 | // Okay, this is a cast from a function to a different type. Unless doing so |
| 9645 | // would cause a type conversion of one of our arguments, change this call to |
| 9646 | // be a direct call with arguments casted to the appropriate types. |
| 9647 | // |
| 9648 | const FunctionType *FT = Callee->getFunctionType(); |
| 9649 | const Type *OldRetTy = Caller->getType(); |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9650 | const Type *NewRetTy = FT->getReturnType(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9651 | |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9652 | if (isa<StructType>(NewRetTy)) |
Devang Patel | d091d32 | 2008-03-11 18:04:06 +0000 | [diff] [blame] | 9653 | return false; // TODO: Handle multiple return values. |
| 9654 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9655 | // Check to see if we are changing the return type... |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9656 | if (OldRetTy != NewRetTy) { |
Bill Wendling | d9644a4 | 2008-05-14 22:45:20 +0000 | [diff] [blame] | 9657 | if (Callee->isDeclaration() && |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9658 | // Conversion is ok if changing from one pointer type to another or from |
| 9659 | // a pointer to an integer of the same size. |
| 9660 | !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) && |
Duncan Sands | 886cadb | 2008-06-17 15:55:30 +0000 | [diff] [blame] | 9661 | (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9662 | return false; // Cannot transform this return value. |
| 9663 | |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9664 | if (!Caller->use_empty() && |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9665 | // void -> non-void is handled specially |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9666 | NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy)) |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9667 | return false; // Cannot transform this return value. |
| 9668 | |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9669 | if (!CallerPAL.isEmpty() && !Caller->use_empty()) { |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9670 | Attributes RAttrs = CallerPAL.getRetAttributes(); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9671 | if (RAttrs & Attribute::typeIncompatible(NewRetTy)) |
Duncan Sands | dbe97dc | 2008-01-07 17:16:06 +0000 | [diff] [blame] | 9672 | return false; // Attribute not compatible with transformed value. |
| 9673 | } |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9674 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9675 | // If the callsite is an invoke instruction, and the return value is used by |
| 9676 | // a PHI node in a successor, we cannot change the return type of the call |
| 9677 | // because there is no place to put the cast instruction (without breaking |
| 9678 | // the critical edge). Bail out in this case. |
| 9679 | if (!Caller->use_empty()) |
| 9680 | if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) |
| 9681 | for (Value::use_iterator UI = II->use_begin(), E = II->use_end(); |
| 9682 | UI != E; ++UI) |
| 9683 | if (PHINode *PN = dyn_cast<PHINode>(*UI)) |
| 9684 | if (PN->getParent() == II->getNormalDest() || |
| 9685 | PN->getParent() == II->getUnwindDest()) |
| 9686 | return false; |
| 9687 | } |
| 9688 | |
| 9689 | unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin()); |
| 9690 | unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); |
| 9691 | |
| 9692 | CallSite::arg_iterator AI = CS.arg_begin(); |
| 9693 | for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { |
| 9694 | const Type *ParamTy = FT->getParamType(i); |
| 9695 | const Type *ActTy = (*AI)->getType(); |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9696 | |
| 9697 | if (!CastInst::isCastable(ActTy, ParamTy)) |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9698 | return false; // Cannot transform this parameter value. |
| 9699 | |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9700 | if (CallerPAL.getParamAttributes(i + 1) |
| 9701 | & Attribute::typeIncompatible(ParamTy)) |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9702 | return false; // Attribute not compatible with transformed value. |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9703 | |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9704 | // Converting from one pointer type to another or between a pointer and an |
| 9705 | // integer of the same size is safe even if we do not have a body. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9706 | bool isConvertible = ActTy == ParamTy || |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9707 | ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) && |
| 9708 | (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9709 | if (Callee->isDeclaration() && !isConvertible) return false; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9710 | } |
| 9711 | |
| 9712 | if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() && |
| 9713 | Callee->isDeclaration()) |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9714 | return false; // Do not delete arguments unless we have a function body. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9715 | |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9716 | if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && |
| 9717 | !CallerPAL.isEmpty()) |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9718 | // In this case we have more arguments than the new function type, but we |
Duncan Sands | 4ced1f8 | 2008-01-13 08:02:44 +0000 | [diff] [blame] | 9719 | // won't be dropping them. Check that these extra arguments have attributes |
| 9720 | // that are compatible with being a vararg call argument. |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9721 | for (unsigned i = CallerPAL.getNumSlots(); i; --i) { |
| 9722 | if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams()) |
Duncan Sands | 4ced1f8 | 2008-01-13 08:02:44 +0000 | [diff] [blame] | 9723 | break; |
Devang Patel | e480dfa | 2008-09-23 23:03:40 +0000 | [diff] [blame] | 9724 | Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs; |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9725 | if (PAttrs & Attribute::VarArgsIncompatible) |
Duncan Sands | 4ced1f8 | 2008-01-13 08:02:44 +0000 | [diff] [blame] | 9726 | return false; |
| 9727 | } |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9728 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9729 | // Okay, we decided that this is a safe thing to do: go ahead and start |
| 9730 | // inserting cast instructions as necessary... |
| 9731 | std::vector<Value*> Args; |
| 9732 | Args.reserve(NumActualArgs); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9733 | SmallVector<AttributeWithIndex, 8> attrVec; |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9734 | attrVec.reserve(NumCommonArgs); |
| 9735 | |
| 9736 | // Get any return attributes. |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9737 | Attributes RAttrs = CallerPAL.getRetAttributes(); |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9738 | |
| 9739 | // If the return value is not being used, the type may not be compatible |
| 9740 | // with the existing attributes. Wipe out any problematic attributes. |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9741 | RAttrs &= ~Attribute::typeIncompatible(NewRetTy); |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9742 | |
| 9743 | // Add the new return attributes. |
| 9744 | if (RAttrs) |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9745 | attrVec.push_back(AttributeWithIndex::get(0, RAttrs)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9746 | |
| 9747 | AI = CS.arg_begin(); |
| 9748 | for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { |
| 9749 | const Type *ParamTy = FT->getParamType(i); |
| 9750 | if ((*AI)->getType() == ParamTy) { |
| 9751 | Args.push_back(*AI); |
| 9752 | } else { |
| 9753 | Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, |
| 9754 | false, ParamTy, false); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9755 | CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9756 | Args.push_back(InsertNewInstBefore(NewCast, *Caller)); |
| 9757 | } |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9758 | |
| 9759 | // Add any parameter attributes. |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9760 | if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1)) |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9761 | attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9762 | } |
| 9763 | |
| 9764 | // If the function takes more arguments than the call was taking, add them |
| 9765 | // now... |
| 9766 | for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) |
| 9767 | Args.push_back(Constant::getNullValue(FT->getParamType(i))); |
| 9768 | |
| 9769 | // If we are removing arguments to the function, emit an obnoxious warning... |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 9770 | if (FT->getNumParams() < NumActualArgs) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9771 | if (!FT->isVarArg()) { |
| 9772 | cerr << "WARNING: While resolving call to function '" |
| 9773 | << Callee->getName() << "' arguments were dropped!\n"; |
| 9774 | } else { |
| 9775 | // Add all of the arguments in their promoted form to the arg list... |
| 9776 | for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { |
| 9777 | const Type *PTy = getPromotedType((*AI)->getType()); |
| 9778 | if (PTy != (*AI)->getType()) { |
| 9779 | // Must promote to pass through va_arg area! |
| 9780 | Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, |
| 9781 | PTy, false); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9782 | Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9783 | InsertNewInstBefore(Cast, *Caller); |
| 9784 | Args.push_back(Cast); |
| 9785 | } else { |
| 9786 | Args.push_back(*AI); |
| 9787 | } |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9788 | |
Duncan Sands | 4ced1f8 | 2008-01-13 08:02:44 +0000 | [diff] [blame] | 9789 | // Add any parameter attributes. |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9790 | if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1)) |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9791 | attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs)); |
Duncan Sands | 4ced1f8 | 2008-01-13 08:02:44 +0000 | [diff] [blame] | 9792 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9793 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 9794 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9795 | |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9796 | if (Attributes FnAttrs = CallerPAL.getFnAttributes()) |
| 9797 | attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs)); |
| 9798 | |
Duncan Sands | 7901ce1 | 2008-06-01 07:38:42 +0000 | [diff] [blame] | 9799 | if (NewRetTy == Type::VoidTy) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9800 | Caller->setName(""); // Void type should not have a name. |
| 9801 | |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9802 | const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end()); |
Duncan Sands | c849e66 | 2008-01-06 18:27:01 +0000 | [diff] [blame] | 9803 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9804 | Instruction *NC; |
| 9805 | if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 9806 | NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(), |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 9807 | Args.begin(), Args.end(), |
| 9808 | Caller->getName(), Caller); |
Reid Spencer | 6b0b09a | 2007-07-30 19:53:57 +0000 | [diff] [blame] | 9809 | cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv()); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9810 | cast<InvokeInst>(NC)->setAttributes(NewCallerPAL); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9811 | } else { |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 9812 | NC = CallInst::Create(Callee, Args.begin(), Args.end(), |
| 9813 | Caller->getName(), Caller); |
Duncan Sands | f5588dc | 2007-11-27 13:23:08 +0000 | [diff] [blame] | 9814 | CallInst *CI = cast<CallInst>(Caller); |
| 9815 | if (CI->isTailCall()) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9816 | cast<CallInst>(NC)->setTailCall(); |
Duncan Sands | f5588dc | 2007-11-27 13:23:08 +0000 | [diff] [blame] | 9817 | cast<CallInst>(NC)->setCallingConv(CI->getCallingConv()); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9818 | cast<CallInst>(NC)->setAttributes(NewCallerPAL); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9819 | } |
| 9820 | |
| 9821 | // Insert a cast of the return type as necessary. |
| 9822 | Value *NV = NC; |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9823 | if (OldRetTy != NV->getType() && !Caller->use_empty()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9824 | if (NV->getType() != Type::VoidTy) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9825 | Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, |
Duncan Sands | 5c48958 | 2008-01-06 10:12:28 +0000 | [diff] [blame] | 9826 | OldRetTy, false); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 9827 | NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9828 | |
| 9829 | // If this is an invoke instruction, we should insert it after the first |
| 9830 | // non-phi, instruction in the normal successor block. |
| 9831 | if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { |
Dan Gohman | 514277c | 2008-05-23 21:05:58 +0000 | [diff] [blame] | 9832 | BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 9833 | InsertNewInstBefore(NC, *I); |
| 9834 | } else { |
| 9835 | // Otherwise, it's a call, just insert cast right after the call instr |
| 9836 | InsertNewInstBefore(NC, *Caller); |
| 9837 | } |
| 9838 | AddUsersToWorkList(*Caller); |
| 9839 | } else { |
| 9840 | NV = UndefValue::get(Caller->getType()); |
| 9841 | } |
| 9842 | } |
| 9843 | |
| 9844 | if (Caller->getType() != Type::VoidTy && !Caller->use_empty()) |
| 9845 | Caller->replaceAllUsesWith(NV); |
| 9846 | Caller->eraseFromParent(); |
| 9847 | RemoveFromWorkList(Caller); |
| 9848 | return true; |
| 9849 | } |
| 9850 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9851 | // transformCallThroughTrampoline - Turn a call to a function created by the |
| 9852 | // init_trampoline intrinsic into a direct call to the underlying function. |
| 9853 | // |
| 9854 | Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) { |
| 9855 | Value *Callee = CS.getCalledValue(); |
| 9856 | const PointerType *PTy = cast<PointerType>(Callee->getType()); |
| 9857 | const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9858 | const AttrListPtr &Attrs = CS.getAttributes(); |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9859 | |
| 9860 | // If the call already has the 'nest' attribute somewhere then give up - |
| 9861 | // otherwise 'nest' would occur twice after splicing in the chain. |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9862 | if (Attrs.hasAttrSomewhere(Attribute::Nest)) |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9863 | return 0; |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9864 | |
| 9865 | IntrinsicInst *Tramp = |
| 9866 | cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0)); |
| 9867 | |
Anton Korobeynikov | 48fc88f | 2008-05-07 22:54:15 +0000 | [diff] [blame] | 9868 | Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts()); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9869 | const PointerType *NestFPTy = cast<PointerType>(NestF->getType()); |
| 9870 | const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType()); |
| 9871 | |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9872 | const AttrListPtr &NestAttrs = NestF->getAttributes(); |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9873 | if (!NestAttrs.isEmpty()) { |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9874 | unsigned NestIdx = 1; |
| 9875 | const Type *NestTy = 0; |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9876 | Attributes NestAttr = Attribute::None; |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9877 | |
| 9878 | // Look for a parameter marked with the 'nest' attribute. |
| 9879 | for (FunctionType::param_iterator I = NestFTy->param_begin(), |
| 9880 | E = NestFTy->param_end(); I != E; ++NestIdx, ++I) |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9881 | if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) { |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9882 | // Record the parameter type and any other attributes. |
| 9883 | NestTy = *I; |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9884 | NestAttr = NestAttrs.getParamAttributes(NestIdx); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9885 | break; |
| 9886 | } |
| 9887 | |
| 9888 | if (NestTy) { |
| 9889 | Instruction *Caller = CS.getInstruction(); |
| 9890 | std::vector<Value*> NewArgs; |
| 9891 | NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1); |
| 9892 | |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9893 | SmallVector<AttributeWithIndex, 8> NewAttrs; |
Chris Lattner | 1c8733e | 2008-03-12 17:45:29 +0000 | [diff] [blame] | 9894 | NewAttrs.reserve(Attrs.getNumSlots() + 1); |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9895 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9896 | // Insert the nest argument into the call argument list, which may |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9897 | // mean appending it. Likewise for attributes. |
| 9898 | |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9899 | // Add any result attributes. |
| 9900 | if (Attributes Attr = Attrs.getRetAttributes()) |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9901 | NewAttrs.push_back(AttributeWithIndex::get(0, Attr)); |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9902 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9903 | { |
| 9904 | unsigned Idx = 1; |
| 9905 | CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); |
| 9906 | do { |
| 9907 | if (Idx == NestIdx) { |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9908 | // Add the chain argument and attributes. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9909 | Value *NestVal = Tramp->getOperand(3); |
| 9910 | if (NestVal->getType() != NestTy) |
| 9911 | NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller); |
| 9912 | NewArgs.push_back(NestVal); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9913 | NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr)); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9914 | } |
| 9915 | |
| 9916 | if (I == E) |
| 9917 | break; |
| 9918 | |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9919 | // Add the original argument and attributes. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9920 | NewArgs.push_back(*I); |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9921 | if (Attributes Attr = Attrs.getParamAttributes(Idx)) |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9922 | NewAttrs.push_back |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9923 | (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr)); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9924 | |
| 9925 | ++Idx, ++I; |
| 9926 | } while (1); |
| 9927 | } |
| 9928 | |
Devang Patel | f2a4a92 | 2008-09-26 22:53:05 +0000 | [diff] [blame] | 9929 | // Add any function attributes. |
| 9930 | if (Attributes Attr = Attrs.getFnAttributes()) |
| 9931 | NewAttrs.push_back(AttributeWithIndex::get(~0, Attr)); |
| 9932 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9933 | // The trampoline may have been bitcast to a bogus type (FTy). |
| 9934 | // Handle this by synthesizing a new function type, equal to FTy |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9935 | // with the chain parameter inserted. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9936 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9937 | std::vector<const Type*> NewTypes; |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9938 | NewTypes.reserve(FTy->getNumParams()+1); |
| 9939 | |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9940 | // Insert the chain's type into the list of parameter types, which may |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9941 | // mean appending it. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9942 | { |
| 9943 | unsigned Idx = 1; |
| 9944 | FunctionType::param_iterator I = FTy->param_begin(), |
| 9945 | E = FTy->param_end(); |
| 9946 | |
| 9947 | do { |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9948 | if (Idx == NestIdx) |
| 9949 | // Add the chain's type. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9950 | NewTypes.push_back(NestTy); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9951 | |
| 9952 | if (I == E) |
| 9953 | break; |
| 9954 | |
Duncan Sands | 48b8111 | 2008-01-14 19:52:09 +0000 | [diff] [blame] | 9955 | // Add the original type. |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9956 | NewTypes.push_back(*I); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9957 | |
| 9958 | ++Idx, ++I; |
| 9959 | } while (1); |
| 9960 | } |
| 9961 | |
| 9962 | // Replace the trampoline call with a direct call. Let the generic |
| 9963 | // code sort out any function type mismatches. |
| 9964 | FunctionType *NewFTy = |
Duncan Sands | f5588dc | 2007-11-27 13:23:08 +0000 | [diff] [blame] | 9965 | FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg()); |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 9966 | Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ? |
| 9967 | NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy)); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9968 | const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end()); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9969 | |
| 9970 | Instruction *NewCaller; |
| 9971 | if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 9972 | NewCaller = InvokeInst::Create(NewCallee, |
| 9973 | II->getNormalDest(), II->getUnwindDest(), |
| 9974 | NewArgs.begin(), NewArgs.end(), |
| 9975 | Caller->getName(), Caller); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9976 | cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9977 | cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9978 | } else { |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 9979 | NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(), |
| 9980 | Caller->getName(), Caller); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9981 | if (cast<CallInst>(Caller)->isTailCall()) |
| 9982 | cast<CallInst>(NewCaller)->setTailCall(); |
| 9983 | cast<CallInst>(NewCaller)-> |
| 9984 | setCallingConv(cast<CallInst>(Caller)->getCallingConv()); |
Devang Patel | d222f86 | 2008-09-25 21:00:45 +0000 | [diff] [blame] | 9985 | cast<CallInst>(NewCaller)->setAttributes(NewPAL); |
Duncan Sands | 74833f2 | 2007-09-17 10:26:40 +0000 | [diff] [blame] | 9986 | } |
| 9987 | if (Caller->getType() != Type::VoidTy && !Caller->use_empty()) |
| 9988 | Caller->replaceAllUsesWith(NewCaller); |
| 9989 | Caller->eraseFromParent(); |
| 9990 | RemoveFromWorkList(Caller); |
| 9991 | return 0; |
| 9992 | } |
| 9993 | } |
| 9994 | |
| 9995 | // Replace the trampoline call with a direct call. Since there is no 'nest' |
| 9996 | // parameter, there is no need to adjust the argument list. Let the generic |
| 9997 | // code sort out any function type mismatches. |
| 9998 | Constant *NewCallee = |
| 9999 | NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy); |
| 10000 | CS.setCalledFunction(NewCallee); |
| 10001 | return CS.getInstruction(); |
| 10002 | } |
| 10003 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10004 | /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)] |
| 10005 | /// and if a/b/c/d and the add's all have a single use, turn this into two phi's |
| 10006 | /// and a single binop. |
| 10007 | Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) { |
| 10008 | Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); |
Chris Lattner | 3007801 | 2008-12-01 03:42:51 +0000 | [diff] [blame] | 10009 | assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10010 | unsigned Opc = FirstInst->getOpcode(); |
| 10011 | Value *LHSVal = FirstInst->getOperand(0); |
| 10012 | Value *RHSVal = FirstInst->getOperand(1); |
| 10013 | |
| 10014 | const Type *LHSType = LHSVal->getType(); |
| 10015 | const Type *RHSType = RHSVal->getType(); |
| 10016 | |
| 10017 | // Scan to see if all operands are the same opcode, all have one use, and all |
| 10018 | // kill their operands (i.e. the operands have one use). |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 10019 | for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10020 | Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i)); |
| 10021 | if (!I || I->getOpcode() != Opc || !I->hasOneUse() || |
| 10022 | // Verify type of the LHS matches so we don't fold cmp's of different |
| 10023 | // types or GEP's with different index types. |
| 10024 | I->getOperand(0)->getType() != LHSType || |
| 10025 | I->getOperand(1)->getType() != RHSType) |
| 10026 | return 0; |
| 10027 | |
| 10028 | // If they are CmpInst instructions, check their predicates |
| 10029 | if (Opc == Instruction::ICmp || Opc == Instruction::FCmp) |
| 10030 | if (cast<CmpInst>(I)->getPredicate() != |
| 10031 | cast<CmpInst>(FirstInst)->getPredicate()) |
| 10032 | return 0; |
| 10033 | |
| 10034 | // Keep track of which operand needs a phi node. |
| 10035 | if (I->getOperand(0) != LHSVal) LHSVal = 0; |
| 10036 | if (I->getOperand(1) != RHSVal) RHSVal = 0; |
| 10037 | } |
| 10038 | |
Chris Lattner | 3007801 | 2008-12-01 03:42:51 +0000 | [diff] [blame] | 10039 | // Otherwise, this is safe to transform! |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10040 | |
| 10041 | Value *InLHS = FirstInst->getOperand(0); |
| 10042 | Value *InRHS = FirstInst->getOperand(1); |
| 10043 | PHINode *NewLHS = 0, *NewRHS = 0; |
| 10044 | if (LHSVal == 0) { |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 10045 | NewLHS = PHINode::Create(LHSType, |
| 10046 | FirstInst->getOperand(0)->getName() + ".pn"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10047 | NewLHS->reserveOperandSpace(PN.getNumOperands()/2); |
| 10048 | NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0)); |
| 10049 | InsertNewInstBefore(NewLHS, PN); |
| 10050 | LHSVal = NewLHS; |
| 10051 | } |
| 10052 | |
| 10053 | if (RHSVal == 0) { |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 10054 | NewRHS = PHINode::Create(RHSType, |
| 10055 | FirstInst->getOperand(1)->getName() + ".pn"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10056 | NewRHS->reserveOperandSpace(PN.getNumOperands()/2); |
| 10057 | NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0)); |
| 10058 | InsertNewInstBefore(NewRHS, PN); |
| 10059 | RHSVal = NewRHS; |
| 10060 | } |
| 10061 | |
| 10062 | // Add all operands to the new PHIs. |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 10063 | if (NewLHS || NewRHS) { |
| 10064 | for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { |
| 10065 | Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i)); |
| 10066 | if (NewLHS) { |
| 10067 | Value *NewInLHS = InInst->getOperand(0); |
| 10068 | NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i)); |
| 10069 | } |
| 10070 | if (NewRHS) { |
| 10071 | Value *NewInRHS = InInst->getOperand(1); |
| 10072 | NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i)); |
| 10073 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10074 | } |
| 10075 | } |
| 10076 | |
| 10077 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10078 | return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal); |
Chris Lattner | 3007801 | 2008-12-01 03:42:51 +0000 | [diff] [blame] | 10079 | CmpInst *CIOp = cast<CmpInst>(FirstInst); |
| 10080 | return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, |
| 10081 | RHSVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10082 | } |
| 10083 | |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 10084 | Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) { |
| 10085 | GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0)); |
| 10086 | |
| 10087 | SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), |
| 10088 | FirstInst->op_end()); |
| 10089 | |
| 10090 | // Scan to see if all operands are the same opcode, all have one use, and all |
| 10091 | // kill their operands (i.e. the operands have one use). |
| 10092 | for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) { |
| 10093 | GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i)); |
| 10094 | if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() || |
| 10095 | GEP->getNumOperands() != FirstInst->getNumOperands()) |
| 10096 | return 0; |
| 10097 | |
| 10098 | // Compare the operand lists. |
| 10099 | for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) { |
| 10100 | if (FirstInst->getOperand(op) == GEP->getOperand(op)) |
| 10101 | continue; |
| 10102 | |
| 10103 | // Don't merge two GEPs when two operands differ (introducing phi nodes) |
| 10104 | // if one of the PHIs has a constant for the index. The index may be |
| 10105 | // substantially cheaper to compute for the constants, so making it a |
| 10106 | // variable index could pessimize the path. This also handles the case |
| 10107 | // for struct indices, which must always be constant. |
| 10108 | if (isa<ConstantInt>(FirstInst->getOperand(op)) || |
| 10109 | isa<ConstantInt>(GEP->getOperand(op))) |
| 10110 | return 0; |
| 10111 | |
| 10112 | if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType()) |
| 10113 | return 0; |
| 10114 | FixedOperands[op] = 0; // Needs a PHI. |
| 10115 | } |
| 10116 | } |
| 10117 | |
| 10118 | // Otherwise, this is safe to transform. Insert PHI nodes for each operand |
| 10119 | // that is variable. |
| 10120 | SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size()); |
| 10121 | |
| 10122 | bool HasAnyPHIs = false; |
| 10123 | for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) { |
| 10124 | if (FixedOperands[i]) continue; // operand doesn't need a phi. |
| 10125 | Value *FirstOp = FirstInst->getOperand(i); |
| 10126 | PHINode *NewPN = PHINode::Create(FirstOp->getType(), |
| 10127 | FirstOp->getName()+".pn"); |
| 10128 | InsertNewInstBefore(NewPN, PN); |
| 10129 | |
| 10130 | NewPN->reserveOperandSpace(e); |
| 10131 | NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0)); |
| 10132 | OperandPhis[i] = NewPN; |
| 10133 | FixedOperands[i] = NewPN; |
| 10134 | HasAnyPHIs = true; |
| 10135 | } |
| 10136 | |
| 10137 | |
| 10138 | // Add all operands to the new PHIs. |
| 10139 | if (HasAnyPHIs) { |
| 10140 | for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { |
| 10141 | GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i)); |
| 10142 | BasicBlock *InBB = PN.getIncomingBlock(i); |
| 10143 | |
| 10144 | for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op) |
| 10145 | if (PHINode *OpPhi = OperandPhis[op]) |
| 10146 | OpPhi->addIncoming(InGEP->getOperand(op), InBB); |
| 10147 | } |
| 10148 | } |
| 10149 | |
| 10150 | Value *Base = FixedOperands[0]; |
| 10151 | return GetElementPtrInst::Create(Base, FixedOperands.begin()+1, |
| 10152 | FixedOperands.end()); |
| 10153 | } |
| 10154 | |
| 10155 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10156 | /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out |
| 10157 | /// of the block that defines it. This means that it must be obvious the value |
| 10158 | /// of the load is not changed from the point of the load to the end of the |
| 10159 | /// block it is in. |
| 10160 | /// |
| 10161 | /// Finally, it is safe, but not profitable, to sink a load targetting a |
| 10162 | /// non-address-taken alloca. Doing so will cause us to not promote the alloca |
| 10163 | /// to a register. |
| 10164 | static bool isSafeToSinkLoad(LoadInst *L) { |
| 10165 | BasicBlock::iterator BBI = L, E = L->getParent()->end(); |
| 10166 | |
| 10167 | for (++BBI; BBI != E; ++BBI) |
| 10168 | if (BBI->mayWriteToMemory()) |
| 10169 | return false; |
| 10170 | |
| 10171 | // Check for non-address taken alloca. If not address-taken already, it isn't |
| 10172 | // profitable to do this xform. |
| 10173 | if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) { |
| 10174 | bool isAddressTaken = false; |
| 10175 | for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); |
| 10176 | UI != E; ++UI) { |
| 10177 | if (isa<LoadInst>(UI)) continue; |
| 10178 | if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) { |
| 10179 | // If storing TO the alloca, then the address isn't taken. |
| 10180 | if (SI->getOperand(1) == AI) continue; |
| 10181 | } |
| 10182 | isAddressTaken = true; |
| 10183 | break; |
| 10184 | } |
| 10185 | |
| 10186 | if (!isAddressTaken) |
| 10187 | return false; |
| 10188 | } |
| 10189 | |
| 10190 | return true; |
| 10191 | } |
| 10192 | |
| 10193 | |
| 10194 | // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary" |
| 10195 | // operator and they all are only used by the PHI, PHI together their |
| 10196 | // inputs, and do the operation once, to the result of the PHI. |
| 10197 | Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) { |
| 10198 | Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0)); |
| 10199 | |
| 10200 | // Scan the instruction, looking for input operations that can be folded away. |
| 10201 | // If all input operands to the phi are the same instruction (e.g. a cast from |
| 10202 | // the same type or "+42") we can pull the operation through the PHI, reducing |
| 10203 | // code size and simplifying code. |
| 10204 | Constant *ConstantOp = 0; |
| 10205 | const Type *CastSrcTy = 0; |
| 10206 | bool isVolatile = false; |
| 10207 | if (isa<CastInst>(FirstInst)) { |
| 10208 | CastSrcTy = FirstInst->getOperand(0)->getType(); |
| 10209 | } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) { |
| 10210 | // Can fold binop, compare or shift here if the RHS is a constant, |
| 10211 | // otherwise call FoldPHIArgBinOpIntoPHI. |
| 10212 | ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1)); |
| 10213 | if (ConstantOp == 0) |
| 10214 | return FoldPHIArgBinOpIntoPHI(PN); |
| 10215 | } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) { |
| 10216 | isVolatile = LI->isVolatile(); |
| 10217 | // We can't sink the load if the loaded value could be modified between the |
| 10218 | // load and the PHI. |
| 10219 | if (LI->getParent() != PN.getIncomingBlock(0) || |
| 10220 | !isSafeToSinkLoad(LI)) |
| 10221 | return 0; |
Chris Lattner | 2d9fdd8 | 2008-07-08 17:18:32 +0000 | [diff] [blame] | 10222 | |
| 10223 | // If the PHI is of volatile loads and the load block has multiple |
| 10224 | // successors, sinking it would remove a load of the volatile value from |
| 10225 | // the path through the other successor. |
| 10226 | if (isVolatile && |
| 10227 | LI->getParent()->getTerminator()->getNumSuccessors() != 1) |
| 10228 | return 0; |
| 10229 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10230 | } else if (isa<GetElementPtrInst>(FirstInst)) { |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 10231 | return FoldPHIArgGEPIntoPHI(PN); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10232 | } else { |
| 10233 | return 0; // Cannot fold this operation. |
| 10234 | } |
| 10235 | |
| 10236 | // Check to see if all arguments are the same operation. |
| 10237 | for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { |
| 10238 | if (!isa<Instruction>(PN.getIncomingValue(i))) return 0; |
| 10239 | Instruction *I = cast<Instruction>(PN.getIncomingValue(i)); |
| 10240 | if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst)) |
| 10241 | return 0; |
| 10242 | if (CastSrcTy) { |
| 10243 | if (I->getOperand(0)->getType() != CastSrcTy) |
| 10244 | return 0; // Cast operation must match. |
| 10245 | } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 10246 | // We can't sink the load if the loaded value could be modified between |
| 10247 | // the load and the PHI. |
| 10248 | if (LI->isVolatile() != isVolatile || |
| 10249 | LI->getParent() != PN.getIncomingBlock(i) || |
| 10250 | !isSafeToSinkLoad(LI)) |
| 10251 | return 0; |
Chris Lattner | f786701 | 2008-04-29 17:28:22 +0000 | [diff] [blame] | 10252 | |
Chris Lattner | 2d9fdd8 | 2008-07-08 17:18:32 +0000 | [diff] [blame] | 10253 | // If the PHI is of volatile loads and the load block has multiple |
| 10254 | // successors, sinking it would remove a load of the volatile value from |
| 10255 | // the path through the other successor. |
Chris Lattner | f786701 | 2008-04-29 17:28:22 +0000 | [diff] [blame] | 10256 | if (isVolatile && |
| 10257 | LI->getParent()->getTerminator()->getNumSuccessors() != 1) |
| 10258 | return 0; |
| 10259 | |
| 10260 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10261 | } else if (I->getOperand(1) != ConstantOp) { |
| 10262 | return 0; |
| 10263 | } |
| 10264 | } |
| 10265 | |
| 10266 | // Okay, they are all the same operation. Create a new PHI node of the |
| 10267 | // correct type, and PHI together all of the LHS's of the instructions. |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 10268 | PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(), |
| 10269 | PN.getName()+".in"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10270 | NewPN->reserveOperandSpace(PN.getNumOperands()/2); |
| 10271 | |
| 10272 | Value *InVal = FirstInst->getOperand(0); |
| 10273 | NewPN->addIncoming(InVal, PN.getIncomingBlock(0)); |
| 10274 | |
| 10275 | // Add all operands to the new PHI. |
| 10276 | for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) { |
| 10277 | Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0); |
| 10278 | if (NewInVal != InVal) |
| 10279 | InVal = 0; |
| 10280 | NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i)); |
| 10281 | } |
| 10282 | |
| 10283 | Value *PhiVal; |
| 10284 | if (InVal) { |
| 10285 | // The new PHI unions all of the same values together. This is really |
| 10286 | // common, so we handle it intelligently here for compile-time speed. |
| 10287 | PhiVal = InVal; |
| 10288 | delete NewPN; |
| 10289 | } else { |
| 10290 | InsertNewInstBefore(NewPN, PN); |
| 10291 | PhiVal = NewPN; |
| 10292 | } |
| 10293 | |
| 10294 | // Insert and return the new operation. |
| 10295 | if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10296 | return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType()); |
Chris Lattner | fc984e9 | 2008-04-29 17:13:43 +0000 | [diff] [blame] | 10297 | if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10298 | return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp); |
Chris Lattner | fc984e9 | 2008-04-29 17:13:43 +0000 | [diff] [blame] | 10299 | if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10300 | return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10301 | PhiVal, ConstantOp); |
Chris Lattner | fc984e9 | 2008-04-29 17:13:43 +0000 | [diff] [blame] | 10302 | assert(isa<LoadInst>(FirstInst) && "Unknown operation"); |
| 10303 | |
| 10304 | // If this was a volatile load that we are merging, make sure to loop through |
| 10305 | // and mark all the input loads as non-volatile. If we don't do this, we will |
| 10306 | // insert a new volatile load and the old ones will not be deletable. |
| 10307 | if (isVolatile) |
| 10308 | for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) |
| 10309 | cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false); |
| 10310 | |
| 10311 | return new LoadInst(PhiVal, "", isVolatile); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10312 | } |
| 10313 | |
| 10314 | /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle |
| 10315 | /// that is dead. |
| 10316 | static bool DeadPHICycle(PHINode *PN, |
| 10317 | SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) { |
| 10318 | if (PN->use_empty()) return true; |
| 10319 | if (!PN->hasOneUse()) return false; |
| 10320 | |
| 10321 | // Remember this node, and if we find the cycle, return. |
| 10322 | if (!PotentiallyDeadPHIs.insert(PN)) |
| 10323 | return true; |
Chris Lattner | adf2e34 | 2007-08-28 04:23:55 +0000 | [diff] [blame] | 10324 | |
| 10325 | // Don't scan crazily complex things. |
| 10326 | if (PotentiallyDeadPHIs.size() == 16) |
| 10327 | return false; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10328 | |
| 10329 | if (PHINode *PU = dyn_cast<PHINode>(PN->use_back())) |
| 10330 | return DeadPHICycle(PU, PotentiallyDeadPHIs); |
| 10331 | |
| 10332 | return false; |
| 10333 | } |
| 10334 | |
Chris Lattner | 27b695d | 2007-11-06 21:52:06 +0000 | [diff] [blame] | 10335 | /// PHIsEqualValue - Return true if this phi node is always equal to |
| 10336 | /// NonPhiInVal. This happens with mutually cyclic phi nodes like: |
| 10337 | /// z = some value; x = phi (y, z); y = phi (x, z) |
| 10338 | static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, |
| 10339 | SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) { |
| 10340 | // See if we already saw this PHI node. |
| 10341 | if (!ValueEqualPHIs.insert(PN)) |
| 10342 | return true; |
| 10343 | |
| 10344 | // Don't scan crazily complex things. |
| 10345 | if (ValueEqualPHIs.size() == 16) |
| 10346 | return false; |
| 10347 | |
| 10348 | // Scan the operands to see if they are either phi nodes or are equal to |
| 10349 | // the value. |
| 10350 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { |
| 10351 | Value *Op = PN->getIncomingValue(i); |
| 10352 | if (PHINode *OpPN = dyn_cast<PHINode>(Op)) { |
| 10353 | if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs)) |
| 10354 | return false; |
| 10355 | } else if (Op != NonPhiInVal) |
| 10356 | return false; |
| 10357 | } |
| 10358 | |
| 10359 | return true; |
| 10360 | } |
| 10361 | |
| 10362 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10363 | // PHINode simplification |
| 10364 | // |
| 10365 | Instruction *InstCombiner::visitPHINode(PHINode &PN) { |
| 10366 | // If LCSSA is around, don't mess with Phi nodes |
| 10367 | if (MustPreserveLCSSA) return 0; |
| 10368 | |
| 10369 | if (Value *V = PN.hasConstantValue()) |
| 10370 | return ReplaceInstUsesWith(PN, V); |
| 10371 | |
| 10372 | // If all PHI operands are the same operation, pull them through the PHI, |
| 10373 | // reducing code size. |
| 10374 | if (isa<Instruction>(PN.getIncomingValue(0)) && |
Chris Lattner | 9e1916e | 2008-12-01 02:34:36 +0000 | [diff] [blame] | 10375 | isa<Instruction>(PN.getIncomingValue(1)) && |
| 10376 | cast<Instruction>(PN.getIncomingValue(0))->getOpcode() == |
| 10377 | cast<Instruction>(PN.getIncomingValue(1))->getOpcode() && |
| 10378 | // FIXME: The hasOneUse check will fail for PHIs that use the value more |
| 10379 | // than themselves more than once. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10380 | PN.getIncomingValue(0)->hasOneUse()) |
| 10381 | if (Instruction *Result = FoldPHIArgOpIntoPHI(PN)) |
| 10382 | return Result; |
| 10383 | |
| 10384 | // If this is a trivial cycle in the PHI node graph, remove it. Basically, if |
| 10385 | // this PHI only has a single use (a PHI), and if that PHI only has one use (a |
| 10386 | // PHI)... break the cycle. |
| 10387 | if (PN.hasOneUse()) { |
| 10388 | Instruction *PHIUser = cast<Instruction>(PN.use_back()); |
| 10389 | if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) { |
| 10390 | SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs; |
| 10391 | PotentiallyDeadPHIs.insert(&PN); |
| 10392 | if (DeadPHICycle(PU, PotentiallyDeadPHIs)) |
| 10393 | return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType())); |
| 10394 | } |
| 10395 | |
| 10396 | // If this phi has a single use, and if that use just computes a value for |
| 10397 | // the next iteration of a loop, delete the phi. This occurs with unused |
| 10398 | // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this |
| 10399 | // common case here is good because the only other things that catch this |
| 10400 | // are induction variable analysis (sometimes) and ADCE, which is only run |
| 10401 | // late. |
| 10402 | if (PHIUser->hasOneUse() && |
| 10403 | (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) && |
| 10404 | PHIUser->use_back() == &PN) { |
| 10405 | return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType())); |
| 10406 | } |
| 10407 | } |
| 10408 | |
Chris Lattner | 27b695d | 2007-11-06 21:52:06 +0000 | [diff] [blame] | 10409 | // We sometimes end up with phi cycles that non-obviously end up being the |
| 10410 | // same value, for example: |
| 10411 | // z = some value; x = phi (y, z); y = phi (x, z) |
| 10412 | // where the phi nodes don't necessarily need to be in the same block. Do a |
| 10413 | // quick check to see if the PHI node only contains a single non-phi value, if |
| 10414 | // so, scan to see if the phi cycle is actually equal to that value. |
| 10415 | { |
| 10416 | unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues(); |
| 10417 | // Scan for the first non-phi operand. |
| 10418 | while (InValNo != NumOperandVals && |
| 10419 | isa<PHINode>(PN.getIncomingValue(InValNo))) |
| 10420 | ++InValNo; |
| 10421 | |
| 10422 | if (InValNo != NumOperandVals) { |
| 10423 | Value *NonPhiInVal = PN.getOperand(InValNo); |
| 10424 | |
| 10425 | // Scan the rest of the operands to see if there are any conflicts, if so |
| 10426 | // there is no need to recursively scan other phis. |
| 10427 | for (++InValNo; InValNo != NumOperandVals; ++InValNo) { |
| 10428 | Value *OpVal = PN.getIncomingValue(InValNo); |
| 10429 | if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal)) |
| 10430 | break; |
| 10431 | } |
| 10432 | |
| 10433 | // If we scanned over all operands, then we have one unique value plus |
| 10434 | // phi values. Scan PHI nodes to see if they all merge in each other or |
| 10435 | // the value. |
| 10436 | if (InValNo == NumOperandVals) { |
| 10437 | SmallPtrSet<PHINode*, 16> ValueEqualPHIs; |
| 10438 | if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs)) |
| 10439 | return ReplaceInstUsesWith(PN, NonPhiInVal); |
| 10440 | } |
| 10441 | } |
| 10442 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10443 | return 0; |
| 10444 | } |
| 10445 | |
| 10446 | static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy, |
| 10447 | Instruction *InsertPoint, |
| 10448 | InstCombiner *IC) { |
| 10449 | unsigned PtrSize = DTy->getPrimitiveSizeInBits(); |
| 10450 | unsigned VTySize = V->getType()->getPrimitiveSizeInBits(); |
| 10451 | // We must cast correctly to the pointer type. Ensure that we |
| 10452 | // sign extend the integer value if it is smaller as this is |
| 10453 | // used for address computation. |
| 10454 | Instruction::CastOps opcode = |
| 10455 | (VTySize < PtrSize ? Instruction::SExt : |
| 10456 | (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc)); |
| 10457 | return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint); |
| 10458 | } |
| 10459 | |
| 10460 | |
| 10461 | Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { |
| 10462 | Value *PtrOp = GEP.getOperand(0); |
| 10463 | // Is it 'getelementptr %P, i32 0' or 'getelementptr %P' |
| 10464 | // If so, eliminate the noop. |
| 10465 | if (GEP.getNumOperands() == 1) |
| 10466 | return ReplaceInstUsesWith(GEP, PtrOp); |
| 10467 | |
| 10468 | if (isa<UndefValue>(GEP.getOperand(0))) |
| 10469 | return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType())); |
| 10470 | |
| 10471 | bool HasZeroPointerIndex = false; |
| 10472 | if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1))) |
| 10473 | HasZeroPointerIndex = C->isNullValue(); |
| 10474 | |
| 10475 | if (GEP.getNumOperands() == 2 && HasZeroPointerIndex) |
| 10476 | return ReplaceInstUsesWith(GEP, PtrOp); |
| 10477 | |
| 10478 | // Eliminate unneeded casts for indices. |
| 10479 | bool MadeChange = false; |
| 10480 | |
| 10481 | gep_type_iterator GTI = gep_type_begin(GEP); |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10482 | for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end(); |
| 10483 | i != e; ++i, ++GTI) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10484 | if (isa<SequentialType>(*GTI)) { |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10485 | if (CastInst *CI = dyn_cast<CastInst>(*i)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10486 | if (CI->getOpcode() == Instruction::ZExt || |
| 10487 | CI->getOpcode() == Instruction::SExt) { |
| 10488 | const Type *SrcTy = CI->getOperand(0)->getType(); |
| 10489 | // We can eliminate a cast from i32 to i64 iff the target |
| 10490 | // is a 32-bit pointer target. |
| 10491 | if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) { |
| 10492 | MadeChange = true; |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10493 | *i = CI->getOperand(0); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10494 | } |
| 10495 | } |
| 10496 | } |
| 10497 | // If we are using a wider index than needed for this platform, shrink it |
Dan Gohman | 5d639ed | 2008-09-11 23:06:38 +0000 | [diff] [blame] | 10498 | // to what we need. If narrower, sign-extend it to what we need. |
| 10499 | // If the incoming value needs a cast instruction, |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10500 | // insert it. This explicit cast can make subsequent optimizations more |
| 10501 | // obvious. |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10502 | Value *Op = *i; |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 10503 | if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10504 | if (Constant *C = dyn_cast<Constant>(Op)) { |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10505 | *i = ConstantExpr::getTrunc(C, TD->getIntPtrType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10506 | MadeChange = true; |
| 10507 | } else { |
| 10508 | Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(), |
| 10509 | GEP); |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 10510 | *i = Op; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10511 | MadeChange = true; |
| 10512 | } |
Dan Gohman | 5d639ed | 2008-09-11 23:06:38 +0000 | [diff] [blame] | 10513 | } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) { |
| 10514 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 10515 | *i = ConstantExpr::getSExt(C, TD->getIntPtrType()); |
| 10516 | MadeChange = true; |
| 10517 | } else { |
| 10518 | Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(), |
| 10519 | GEP); |
| 10520 | *i = Op; |
| 10521 | MadeChange = true; |
| 10522 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 10523 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10524 | } |
| 10525 | } |
| 10526 | if (MadeChange) return &GEP; |
| 10527 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10528 | // Combine Indices - If the source pointer to this getelementptr instruction |
| 10529 | // is a getelementptr instruction, combine the indices of the two |
| 10530 | // getelementptr instructions into a single instruction. |
| 10531 | // |
| 10532 | SmallVector<Value*, 8> SrcGEPOperands; |
| 10533 | if (User *Src = dyn_castGetElementPtr(PtrOp)) |
| 10534 | SrcGEPOperands.append(Src->op_begin(), Src->op_end()); |
| 10535 | |
| 10536 | if (!SrcGEPOperands.empty()) { |
| 10537 | // Note that if our source is a gep chain itself that we wait for that |
| 10538 | // chain to be resolved before we perform this transformation. This |
| 10539 | // avoids us creating a TON of code in some cases. |
| 10540 | // |
| 10541 | if (isa<GetElementPtrInst>(SrcGEPOperands[0]) && |
| 10542 | cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2) |
| 10543 | return 0; // Wait until our source is folded to completion. |
| 10544 | |
| 10545 | SmallVector<Value*, 8> Indices; |
| 10546 | |
| 10547 | // Find out whether the last index in the source GEP is a sequential idx. |
| 10548 | bool EndsWithSequential = false; |
| 10549 | for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)), |
| 10550 | E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I) |
| 10551 | EndsWithSequential = !isa<StructType>(*I); |
| 10552 | |
| 10553 | // Can we combine the two pointer arithmetics offsets? |
| 10554 | if (EndsWithSequential) { |
| 10555 | // Replace: gep (gep %P, long B), long A, ... |
| 10556 | // With: T = long A+B; gep %P, T, ... |
| 10557 | // |
| 10558 | Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1); |
| 10559 | if (SO1 == Constant::getNullValue(SO1->getType())) { |
| 10560 | Sum = GO1; |
| 10561 | } else if (GO1 == Constant::getNullValue(GO1->getType())) { |
| 10562 | Sum = SO1; |
| 10563 | } else { |
| 10564 | // If they aren't the same type, convert both to an integer of the |
| 10565 | // target's pointer size. |
| 10566 | if (SO1->getType() != GO1->getType()) { |
| 10567 | if (Constant *SO1C = dyn_cast<Constant>(SO1)) { |
| 10568 | SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true); |
| 10569 | } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) { |
| 10570 | GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true); |
| 10571 | } else { |
Duncan Sands | f99fdc6 | 2007-11-01 20:53:16 +0000 | [diff] [blame] | 10572 | unsigned PS = TD->getPointerSizeInBits(); |
| 10573 | if (TD->getTypeSizeInBits(SO1->getType()) == PS) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10574 | // Convert GO1 to SO1's type. |
| 10575 | GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this); |
| 10576 | |
Duncan Sands | f99fdc6 | 2007-11-01 20:53:16 +0000 | [diff] [blame] | 10577 | } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10578 | // Convert SO1 to GO1's type. |
| 10579 | SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this); |
| 10580 | } else { |
| 10581 | const Type *PT = TD->getIntPtrType(); |
| 10582 | SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this); |
| 10583 | GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this); |
| 10584 | } |
| 10585 | } |
| 10586 | } |
| 10587 | if (isa<Constant>(SO1) && isa<Constant>(GO1)) |
| 10588 | Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1)); |
| 10589 | else { |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10590 | Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10591 | InsertNewInstBefore(cast<Instruction>(Sum), GEP); |
| 10592 | } |
| 10593 | } |
| 10594 | |
| 10595 | // Recycle the GEP we already have if possible. |
| 10596 | if (SrcGEPOperands.size() == 2) { |
| 10597 | GEP.setOperand(0, SrcGEPOperands[0]); |
| 10598 | GEP.setOperand(1, Sum); |
| 10599 | return &GEP; |
| 10600 | } else { |
| 10601 | Indices.insert(Indices.end(), SrcGEPOperands.begin()+1, |
| 10602 | SrcGEPOperands.end()-1); |
| 10603 | Indices.push_back(Sum); |
| 10604 | Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end()); |
| 10605 | } |
| 10606 | } else if (isa<Constant>(*GEP.idx_begin()) && |
| 10607 | cast<Constant>(*GEP.idx_begin())->isNullValue() && |
| 10608 | SrcGEPOperands.size() != 1) { |
| 10609 | // Otherwise we can do the fold if the first index of the GEP is a zero |
| 10610 | Indices.insert(Indices.end(), SrcGEPOperands.begin()+1, |
| 10611 | SrcGEPOperands.end()); |
| 10612 | Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end()); |
| 10613 | } |
| 10614 | |
| 10615 | if (!Indices.empty()) |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 10616 | return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(), |
| 10617 | Indices.end(), GEP.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10618 | |
| 10619 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) { |
| 10620 | // GEP of global variable. If all of the indices for this GEP are |
| 10621 | // constants, we can promote this to a constexpr instead of an instruction. |
| 10622 | |
| 10623 | // Scan for nonconstants... |
| 10624 | SmallVector<Constant*, 8> Indices; |
| 10625 | User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); |
| 10626 | for (; I != E && isa<Constant>(*I); ++I) |
| 10627 | Indices.push_back(cast<Constant>(*I)); |
| 10628 | |
| 10629 | if (I == E) { // If they are all constants... |
| 10630 | Constant *CE = ConstantExpr::getGetElementPtr(GV, |
| 10631 | &Indices[0],Indices.size()); |
| 10632 | |
| 10633 | // Replace all uses of the GEP with the new constexpr... |
| 10634 | return ReplaceInstUsesWith(GEP, CE); |
| 10635 | } |
| 10636 | } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast? |
| 10637 | if (!isa<PointerType>(X->getType())) { |
| 10638 | // Not interesting. Source pointer must be a cast from pointer. |
| 10639 | } else if (HasZeroPointerIndex) { |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10640 | // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... |
| 10641 | // into : GEP [10 x i8]* X, i32 0, ... |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10642 | // |
| 10643 | // This occurs when the program declares an array extern like "int X[];" |
| 10644 | // |
| 10645 | const PointerType *CPTy = cast<PointerType>(PtrOp->getType()); |
| 10646 | const PointerType *XTy = cast<PointerType>(X->getType()); |
| 10647 | if (const ArrayType *XATy = |
| 10648 | dyn_cast<ArrayType>(XTy->getElementType())) |
| 10649 | if (const ArrayType *CATy = |
| 10650 | dyn_cast<ArrayType>(CPTy->getElementType())) |
| 10651 | if (CATy->getElementType() == XATy->getElementType()) { |
| 10652 | // At this point, we know that the cast source type is a pointer |
| 10653 | // to an array of the same type as the destination pointer |
| 10654 | // array. Because the array type is never stepped over (there |
| 10655 | // is a leading zero) we can fold the cast into this GEP. |
| 10656 | GEP.setOperand(0, X); |
| 10657 | return &GEP; |
| 10658 | } |
| 10659 | } else if (GEP.getNumOperands() == 2) { |
| 10660 | // Transform things like: |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10661 | // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V |
| 10662 | // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10663 | const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType(); |
| 10664 | const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType(); |
| 10665 | if (isa<ArrayType>(SrcElTy) && |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 10666 | TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) == |
| 10667 | TD->getTypePaddedSize(ResElTy)) { |
David Greene | 393be88 | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 10668 | Value *Idx[2]; |
| 10669 | Idx[0] = Constant::getNullValue(Type::Int32Ty); |
| 10670 | Idx[1] = GEP.getOperand(1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10671 | Value *V = InsertNewInstBefore( |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 10672 | GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10673 | // V and GEP are both pointer types --> BitCast |
| 10674 | return new BitCastInst(V, GEP.getType()); |
| 10675 | } |
| 10676 | |
| 10677 | // Transform things like: |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10678 | // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10679 | // (where tmp = 8*tmp2) into: |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10680 | // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10681 | |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10682 | if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10683 | uint64_t ArrayEltSize = |
Duncan Sands | d68f13b | 2009-01-12 20:38:59 +0000 | [diff] [blame] | 10684 | TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10685 | |
| 10686 | // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We |
| 10687 | // allow either a mul, shift, or constant here. |
| 10688 | Value *NewIdx = 0; |
| 10689 | ConstantInt *Scale = 0; |
| 10690 | if (ArrayEltSize == 1) { |
| 10691 | NewIdx = GEP.getOperand(1); |
| 10692 | Scale = ConstantInt::get(NewIdx->getType(), 1); |
| 10693 | } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) { |
| 10694 | NewIdx = ConstantInt::get(CI->getType(), 1); |
| 10695 | Scale = CI; |
| 10696 | } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){ |
| 10697 | if (Inst->getOpcode() == Instruction::Shl && |
| 10698 | isa<ConstantInt>(Inst->getOperand(1))) { |
| 10699 | ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1)); |
| 10700 | uint32_t ShAmtVal = ShAmt->getLimitedValue(64); |
| 10701 | Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal); |
| 10702 | NewIdx = Inst->getOperand(0); |
| 10703 | } else if (Inst->getOpcode() == Instruction::Mul && |
| 10704 | isa<ConstantInt>(Inst->getOperand(1))) { |
| 10705 | Scale = cast<ConstantInt>(Inst->getOperand(1)); |
| 10706 | NewIdx = Inst->getOperand(0); |
| 10707 | } |
| 10708 | } |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10709 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10710 | // If the index will be to exactly the right offset with the scale taken |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10711 | // out, perform the transformation. Note, we don't know whether Scale is |
| 10712 | // signed or not. We'll use unsigned version of division/modulo |
| 10713 | // operation after making sure Scale doesn't have the sign bit set. |
| 10714 | if (Scale && Scale->getSExtValue() >= 0LL && |
| 10715 | Scale->getZExtValue() % ArrayEltSize == 0) { |
| 10716 | Scale = ConstantInt::get(Scale->getType(), |
| 10717 | Scale->getZExtValue() / ArrayEltSize); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10718 | if (Scale->getZExtValue() != 1) { |
| 10719 | Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(), |
Wojciech Matyjewicz | 5b5ab53 | 2007-12-12 15:21:32 +0000 | [diff] [blame] | 10720 | false /*ZExt*/); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 10721 | Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10722 | NewIdx = InsertNewInstBefore(Sc, GEP); |
| 10723 | } |
| 10724 | |
| 10725 | // Insert the new GEP instruction. |
David Greene | 393be88 | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 10726 | Value *Idx[2]; |
| 10727 | Idx[0] = Constant::getNullValue(Type::Int32Ty); |
| 10728 | Idx[1] = NewIdx; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10729 | Instruction *NewGEP = |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 10730 | GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10731 | NewGEP = InsertNewInstBefore(NewGEP, GEP); |
| 10732 | // The NewGEP must be pointer typed, so must the old one -> BitCast |
| 10733 | return new BitCastInst(NewGEP, GEP.getType()); |
| 10734 | } |
| 10735 | } |
| 10736 | } |
| 10737 | } |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10738 | |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 10739 | /// See if we can simplify: |
| 10740 | /// X = bitcast A to B* |
| 10741 | /// Y = gep X, <...constant indices...> |
| 10742 | /// into a gep of the original struct. This is important for SROA and alias |
| 10743 | /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10744 | if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) { |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 10745 | if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) { |
| 10746 | // Determine how much the GEP moves the pointer. We are guaranteed to get |
| 10747 | // a constant back from EmitGEPOffset. |
| 10748 | ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this)); |
| 10749 | int64_t Offset = OffsetV->getSExtValue(); |
| 10750 | |
| 10751 | // If this GEP instruction doesn't move the pointer, just replace the GEP |
| 10752 | // with a bitcast of the real input to the dest type. |
| 10753 | if (Offset == 0) { |
| 10754 | // If the bitcast is of an allocation, and the allocation will be |
| 10755 | // converted to match the type of the cast, don't touch this. |
| 10756 | if (isa<AllocationInst>(BCI->getOperand(0))) { |
| 10757 | // See if the bitcast simplifies, if so, don't nuke this GEP yet. |
| 10758 | if (Instruction *I = visitBitCast(*BCI)) { |
| 10759 | if (I != BCI) { |
| 10760 | I->takeName(BCI); |
| 10761 | BCI->getParent()->getInstList().insert(BCI, I); |
| 10762 | ReplaceInstUsesWith(*BCI, I); |
| 10763 | } |
| 10764 | return &GEP; |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10765 | } |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10766 | } |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 10767 | return new BitCastInst(BCI->getOperand(0), GEP.getType()); |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10768 | } |
Chris Lattner | 94ccd5f | 2009-01-09 05:44:56 +0000 | [diff] [blame] | 10769 | |
| 10770 | // Otherwise, if the offset is non-zero, we need to find out if there is a |
| 10771 | // field at Offset in 'A's type. If so, we can pull the cast through the |
| 10772 | // GEP. |
| 10773 | SmallVector<Value*, 8> NewIndices; |
| 10774 | const Type *InTy = |
| 10775 | cast<PointerType>(BCI->getOperand(0)->getType())->getElementType(); |
| 10776 | if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) { |
| 10777 | Instruction *NGEP = |
| 10778 | GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(), |
| 10779 | NewIndices.end()); |
| 10780 | if (NGEP->getType() == GEP.getType()) return NGEP; |
| 10781 | InsertNewInstBefore(NGEP, GEP); |
| 10782 | NGEP->takeName(&GEP); |
| 10783 | return new BitCastInst(NGEP, GEP.getType()); |
| 10784 | } |
Chris Lattner | 111ea77 | 2009-01-09 04:53:57 +0000 | [diff] [blame] | 10785 | } |
| 10786 | } |
| 10787 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10788 | return 0; |
| 10789 | } |
| 10790 | |
| 10791 | Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) { |
| 10792 | // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1 |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 10793 | if (AI.isArrayAllocation()) { // Check C != 1 |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10794 | if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) { |
| 10795 | const Type *NewTy = |
| 10796 | ArrayType::get(AI.getAllocatedType(), C->getZExtValue()); |
| 10797 | AllocationInst *New = 0; |
| 10798 | |
| 10799 | // Create and insert the replacement instruction... |
| 10800 | if (isa<MallocInst>(AI)) |
| 10801 | New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName()); |
| 10802 | else { |
| 10803 | assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!"); |
| 10804 | New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName()); |
| 10805 | } |
| 10806 | |
| 10807 | InsertNewInstBefore(New, AI); |
| 10808 | |
| 10809 | // Scan to the end of the allocation instructions, to skip over a block of |
| 10810 | // allocas if possible... |
| 10811 | // |
| 10812 | BasicBlock::iterator It = New; |
| 10813 | while (isa<AllocationInst>(*It)) ++It; |
| 10814 | |
| 10815 | // Now that I is pointing to the first non-allocation-inst in the block, |
| 10816 | // insert our getelementptr instruction... |
| 10817 | // |
| 10818 | Value *NullIdx = Constant::getNullValue(Type::Int32Ty); |
David Greene | 393be88 | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 10819 | Value *Idx[2]; |
| 10820 | Idx[0] = NullIdx; |
| 10821 | Idx[1] = NullIdx; |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 10822 | Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2, |
| 10823 | New->getName()+".sub", It); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10824 | |
| 10825 | // Now make everything use the getelementptr instead of the original |
| 10826 | // allocation. |
| 10827 | return ReplaceInstUsesWith(AI, V); |
| 10828 | } else if (isa<UndefValue>(AI.getArraySize())) { |
| 10829 | return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); |
| 10830 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 10831 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10832 | |
Dan Gohman | 28e78f0 | 2009-01-13 20:18:38 +0000 | [diff] [blame] | 10833 | if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) { |
| 10834 | // If alloca'ing a zero byte object, replace the alloca with a null pointer. |
| 10835 | // Note that we only do this for alloca's, because malloc should allocate and |
| 10836 | // return a unique pointer, even for a zero byte allocation. |
| 10837 | if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0) |
| 10838 | return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); |
| 10839 | |
| 10840 | // If the alignment is 0 (unspecified), assign it the preferred alignment. |
| 10841 | if (AI.getAlignment() == 0) |
| 10842 | AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType())); |
| 10843 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10844 | |
| 10845 | return 0; |
| 10846 | } |
| 10847 | |
| 10848 | Instruction *InstCombiner::visitFreeInst(FreeInst &FI) { |
| 10849 | Value *Op = FI.getOperand(0); |
| 10850 | |
| 10851 | // free undef -> unreachable. |
| 10852 | if (isa<UndefValue>(Op)) { |
| 10853 | // Insert a new store to null because we cannot modify the CFG here. |
| 10854 | new StoreInst(ConstantInt::getTrue(), |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 10855 | UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10856 | return EraseInstFromFunction(FI); |
| 10857 | } |
| 10858 | |
| 10859 | // If we have 'free null' delete the instruction. This can happen in stl code |
| 10860 | // when lots of inlining happens. |
| 10861 | if (isa<ConstantPointerNull>(Op)) |
| 10862 | return EraseInstFromFunction(FI); |
| 10863 | |
| 10864 | // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X |
| 10865 | if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) { |
| 10866 | FI.setOperand(0, CI->getOperand(0)); |
| 10867 | return &FI; |
| 10868 | } |
| 10869 | |
| 10870 | // Change free (gep X, 0,0,0,0) into free(X) |
| 10871 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) { |
| 10872 | if (GEPI->hasAllZeroIndices()) { |
| 10873 | AddToWorkList(GEPI); |
| 10874 | FI.setOperand(0, GEPI->getOperand(0)); |
| 10875 | return &FI; |
| 10876 | } |
| 10877 | } |
| 10878 | |
| 10879 | // Change free(malloc) into nothing, if the malloc has a single use. |
| 10880 | if (MallocInst *MI = dyn_cast<MallocInst>(Op)) |
| 10881 | if (MI->hasOneUse()) { |
| 10882 | EraseInstFromFunction(FI); |
| 10883 | return EraseInstFromFunction(*MI); |
| 10884 | } |
| 10885 | |
| 10886 | return 0; |
| 10887 | } |
| 10888 | |
| 10889 | |
| 10890 | /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible. |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 10891 | static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI, |
Bill Wendling | 44a36ea | 2008-02-26 10:53:30 +0000 | [diff] [blame] | 10892 | const TargetData *TD) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10893 | User *CI = cast<User>(LI.getOperand(0)); |
| 10894 | Value *CastOp = CI->getOperand(0); |
| 10895 | |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 10896 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) { |
| 10897 | // Instead of loading constant c string, use corresponding integer value |
| 10898 | // directly if string length is small enough. |
Evan Cheng | 833501d | 2008-06-30 07:31:25 +0000 | [diff] [blame] | 10899 | std::string Str; |
| 10900 | if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) { |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 10901 | unsigned len = Str.length(); |
| 10902 | const Type *Ty = cast<PointerType>(CE->getType())->getElementType(); |
| 10903 | unsigned numBits = Ty->getPrimitiveSizeInBits(); |
| 10904 | // Replace LI with immediate integer store. |
| 10905 | if ((numBits >> 3) == len + 1) { |
Bill Wendling | 44a36ea | 2008-02-26 10:53:30 +0000 | [diff] [blame] | 10906 | APInt StrVal(numBits, 0); |
| 10907 | APInt SingleChar(numBits, 0); |
| 10908 | if (TD->isLittleEndian()) { |
| 10909 | for (signed i = len-1; i >= 0; i--) { |
| 10910 | SingleChar = (uint64_t) Str[i]; |
| 10911 | StrVal = (StrVal << 8) | SingleChar; |
| 10912 | } |
| 10913 | } else { |
| 10914 | for (unsigned i = 0; i < len; i++) { |
| 10915 | SingleChar = (uint64_t) Str[i]; |
| 10916 | StrVal = (StrVal << 8) | SingleChar; |
| 10917 | } |
| 10918 | // Append NULL at the end. |
| 10919 | SingleChar = 0; |
| 10920 | StrVal = (StrVal << 8) | SingleChar; |
| 10921 | } |
| 10922 | Value *NL = ConstantInt::get(StrVal); |
| 10923 | return IC.ReplaceInstUsesWith(LI, NL); |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 10924 | } |
| 10925 | } |
| 10926 | } |
| 10927 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10928 | const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType(); |
| 10929 | if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) { |
| 10930 | const Type *SrcPTy = SrcTy->getElementType(); |
| 10931 | |
| 10932 | if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || |
| 10933 | isa<VectorType>(DestPTy)) { |
| 10934 | // If the source is an array, the code below will not succeed. Check to |
| 10935 | // see if a trivial 'gep P, 0, 0' will help matters. Only do this for |
| 10936 | // constants. |
| 10937 | if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy)) |
| 10938 | if (Constant *CSrc = dyn_cast<Constant>(CastOp)) |
| 10939 | if (ASrcTy->getNumElements() != 0) { |
| 10940 | Value *Idxs[2]; |
| 10941 | Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty); |
| 10942 | CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2); |
| 10943 | SrcTy = cast<PointerType>(CastOp->getType()); |
| 10944 | SrcPTy = SrcTy->getElementType(); |
| 10945 | } |
| 10946 | |
| 10947 | if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || |
| 10948 | isa<VectorType>(SrcPTy)) && |
| 10949 | // Do not allow turning this into a load of an integer, which is then |
| 10950 | // casted to a pointer, this pessimizes pointer analysis a lot. |
| 10951 | (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) && |
| 10952 | IC.getTargetData().getTypeSizeInBits(SrcPTy) == |
| 10953 | IC.getTargetData().getTypeSizeInBits(DestPTy)) { |
| 10954 | |
| 10955 | // Okay, we are casting from one integer or pointer type to another of |
| 10956 | // the same size. Instead of casting the pointer before the load, cast |
| 10957 | // the result of the loaded value. |
| 10958 | Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp, |
| 10959 | CI->getName(), |
| 10960 | LI.isVolatile()),LI); |
| 10961 | // Now cast the result of the load. |
| 10962 | return new BitCastInst(NewLoad, LI.getType()); |
| 10963 | } |
| 10964 | } |
| 10965 | } |
| 10966 | return 0; |
| 10967 | } |
| 10968 | |
| 10969 | /// isSafeToLoadUnconditionally - Return true if we know that executing a load |
| 10970 | /// from this value cannot trap. If it is not obviously safe to load from the |
| 10971 | /// specified pointer, we do a quick local scan of the basic block containing |
| 10972 | /// ScanFrom, to determine if the address is already accessed. |
| 10973 | static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) { |
Duncan Sands | 9b27dbe | 2007-09-19 10:10:31 +0000 | [diff] [blame] | 10974 | // If it is an alloca it is always safe to load from. |
| 10975 | if (isa<AllocaInst>(V)) return true; |
| 10976 | |
Duncan Sands | e40a94a | 2007-09-19 10:25:38 +0000 | [diff] [blame] | 10977 | // If it is a global variable it is mostly safe to load from. |
Duncan Sands | 9b27dbe | 2007-09-19 10:10:31 +0000 | [diff] [blame] | 10978 | if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V)) |
Duncan Sands | e40a94a | 2007-09-19 10:25:38 +0000 | [diff] [blame] | 10979 | // Don't try to evaluate aliases. External weak GV can be null. |
Duncan Sands | 9b27dbe | 2007-09-19 10:10:31 +0000 | [diff] [blame] | 10980 | return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10981 | |
| 10982 | // Otherwise, be a little bit agressive by scanning the local block where we |
| 10983 | // want to check to see if the pointer is already being loaded or stored |
| 10984 | // from/to. If so, the previous load or store would have already trapped, |
| 10985 | // so there is no harm doing an extra load (also, CSE will later eliminate |
| 10986 | // the load entirely). |
| 10987 | BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin(); |
| 10988 | |
| 10989 | while (BBI != E) { |
| 10990 | --BBI; |
| 10991 | |
Chris Lattner | 476983a | 2008-06-20 05:12:56 +0000 | [diff] [blame] | 10992 | // If we see a free or a call (which might do a free) the pointer could be |
| 10993 | // marked invalid. |
| 10994 | if (isa<FreeInst>(BBI) || isa<CallInst>(BBI)) |
| 10995 | return false; |
| 10996 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 10997 | if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { |
| 10998 | if (LI->getOperand(0) == V) return true; |
Chris Lattner | 476983a | 2008-06-20 05:12:56 +0000 | [diff] [blame] | 10999 | } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11000 | if (SI->getOperand(1) == V) return true; |
Chris Lattner | 476983a | 2008-06-20 05:12:56 +0000 | [diff] [blame] | 11001 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11002 | |
| 11003 | } |
| 11004 | return false; |
| 11005 | } |
| 11006 | |
| 11007 | Instruction *InstCombiner::visitLoadInst(LoadInst &LI) { |
| 11008 | Value *Op = LI.getOperand(0); |
| 11009 | |
Dan Gohman | 5c4d0e1 | 2007-07-20 16:34:21 +0000 | [diff] [blame] | 11010 | // Attempt to improve the alignment. |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 11011 | unsigned KnownAlign = GetOrEnforceKnownAlignment(Op); |
| 11012 | if (KnownAlign > |
| 11013 | (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) : |
| 11014 | LI.getAlignment())) |
Dan Gohman | 5c4d0e1 | 2007-07-20 16:34:21 +0000 | [diff] [blame] | 11015 | LI.setAlignment(KnownAlign); |
| 11016 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11017 | // load (cast X) --> cast (load X) iff safe |
| 11018 | if (isa<CastInst>(Op)) |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 11019 | if (Instruction *Res = InstCombineLoadCast(*this, LI, TD)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11020 | return Res; |
| 11021 | |
| 11022 | // None of the following transforms are legal for volatile loads. |
| 11023 | if (LI.isVolatile()) return 0; |
| 11024 | |
Dan Gohman | 0ff5a1f | 2008-10-15 23:19:35 +0000 | [diff] [blame] | 11025 | // Do really simple store-to-load forwarding and load CSE, to catch cases |
| 11026 | // where there are several consequtive memory accesses to the same location, |
| 11027 | // separated by a few arithmetic operations. |
| 11028 | BasicBlock::iterator BBI = &LI; |
Chris Lattner | 6fd8c80 | 2008-11-27 08:56:30 +0000 | [diff] [blame] | 11029 | if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6)) |
| 11030 | return ReplaceInstUsesWith(LI, AvailableVal); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11031 | |
Christopher Lamb | 2c17539 | 2007-12-29 07:56:53 +0000 | [diff] [blame] | 11032 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) { |
| 11033 | const Value *GEPI0 = GEPI->getOperand(0); |
| 11034 | // TODO: Consider a target hook for valid address spaces for this xform. |
| 11035 | if (isa<ConstantPointerNull>(GEPI0) && |
| 11036 | cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11037 | // Insert a new store to null instruction before the load to indicate |
| 11038 | // that this code is not reachable. We do this instead of inserting |
| 11039 | // an unreachable instruction directly because we cannot modify the |
| 11040 | // CFG. |
| 11041 | new StoreInst(UndefValue::get(LI.getType()), |
| 11042 | Constant::getNullValue(Op->getType()), &LI); |
| 11043 | return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType())); |
| 11044 | } |
Christopher Lamb | 2c17539 | 2007-12-29 07:56:53 +0000 | [diff] [blame] | 11045 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11046 | |
| 11047 | if (Constant *C = dyn_cast<Constant>(Op)) { |
| 11048 | // load null/undef -> undef |
Christopher Lamb | 2c17539 | 2007-12-29 07:56:53 +0000 | [diff] [blame] | 11049 | // TODO: Consider a target hook for valid address spaces for this xform. |
| 11050 | if (isa<UndefValue>(C) || (C->isNullValue() && |
| 11051 | cast<PointerType>(Op->getType())->getAddressSpace() == 0)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11052 | // Insert a new store to null instruction before the load to indicate that |
| 11053 | // this code is not reachable. We do this instead of inserting an |
| 11054 | // unreachable instruction directly because we cannot modify the CFG. |
| 11055 | new StoreInst(UndefValue::get(LI.getType()), |
| 11056 | Constant::getNullValue(Op->getType()), &LI); |
| 11057 | return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType())); |
| 11058 | } |
| 11059 | |
| 11060 | // Instcombine load (constant global) into the value loaded. |
| 11061 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op)) |
| 11062 | if (GV->isConstant() && !GV->isDeclaration()) |
| 11063 | return ReplaceInstUsesWith(LI, GV->getInitializer()); |
| 11064 | |
| 11065 | // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded. |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 11066 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11067 | if (CE->getOpcode() == Instruction::GetElementPtr) { |
| 11068 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) |
| 11069 | if (GV->isConstant() && !GV->isDeclaration()) |
| 11070 | if (Constant *V = |
| 11071 | ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) |
| 11072 | return ReplaceInstUsesWith(LI, V); |
| 11073 | if (CE->getOperand(0)->isNullValue()) { |
| 11074 | // Insert a new store to null instruction before the load to indicate |
| 11075 | // that this code is not reachable. We do this instead of inserting |
| 11076 | // an unreachable instruction directly because we cannot modify the |
| 11077 | // CFG. |
| 11078 | new StoreInst(UndefValue::get(LI.getType()), |
| 11079 | Constant::getNullValue(Op->getType()), &LI); |
| 11080 | return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType())); |
| 11081 | } |
| 11082 | |
| 11083 | } else if (CE->isCast()) { |
Devang Patel | a0f8ea8 | 2007-10-18 19:52:32 +0000 | [diff] [blame] | 11084 | if (Instruction *Res = InstCombineLoadCast(*this, LI, TD)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11085 | return Res; |
| 11086 | } |
Anton Korobeynikov | 8522e1c | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 11087 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11088 | } |
Chris Lattner | 0270a11 | 2007-08-11 18:48:48 +0000 | [diff] [blame] | 11089 | |
| 11090 | // If this load comes from anywhere in a constant global, and if the global |
| 11091 | // is all undef or zero, we know what it loads. |
Duncan Sands | 52fb873 | 2008-10-01 15:25:41 +0000 | [diff] [blame] | 11092 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){ |
Chris Lattner | 0270a11 | 2007-08-11 18:48:48 +0000 | [diff] [blame] | 11093 | if (GV->isConstant() && GV->hasInitializer()) { |
| 11094 | if (GV->getInitializer()->isNullValue()) |
| 11095 | return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType())); |
| 11096 | else if (isa<UndefValue>(GV->getInitializer())) |
| 11097 | return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType())); |
| 11098 | } |
| 11099 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11100 | |
| 11101 | if (Op->hasOneUse()) { |
| 11102 | // Change select and PHI nodes to select values instead of addresses: this |
| 11103 | // helps alias analysis out a lot, allows many others simplifications, and |
| 11104 | // exposes redundancy in the code. |
| 11105 | // |
| 11106 | // Note that we cannot do the transformation unless we know that the |
| 11107 | // introduced loads cannot trap! Something like this is valid as long as |
| 11108 | // the condition is always false: load (select bool %C, int* null, int* %G), |
| 11109 | // but it would not be valid if we transformed it to load from null |
| 11110 | // unconditionally. |
| 11111 | // |
| 11112 | if (SelectInst *SI = dyn_cast<SelectInst>(Op)) { |
| 11113 | // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2). |
| 11114 | if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) && |
| 11115 | isSafeToLoadUnconditionally(SI->getOperand(2), SI)) { |
| 11116 | Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1), |
| 11117 | SI->getOperand(1)->getName()+".val"), LI); |
| 11118 | Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2), |
| 11119 | SI->getOperand(2)->getName()+".val"), LI); |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 11120 | return SelectInst::Create(SI->getCondition(), V1, V2); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11121 | } |
| 11122 | |
| 11123 | // load (select (cond, null, P)) -> load P |
| 11124 | if (Constant *C = dyn_cast<Constant>(SI->getOperand(1))) |
| 11125 | if (C->isNullValue()) { |
| 11126 | LI.setOperand(0, SI->getOperand(2)); |
| 11127 | return &LI; |
| 11128 | } |
| 11129 | |
| 11130 | // load (select (cond, P, null)) -> load P |
| 11131 | if (Constant *C = dyn_cast<Constant>(SI->getOperand(2))) |
| 11132 | if (C->isNullValue()) { |
| 11133 | LI.setOperand(0, SI->getOperand(1)); |
| 11134 | return &LI; |
| 11135 | } |
| 11136 | } |
| 11137 | } |
| 11138 | return 0; |
| 11139 | } |
| 11140 | |
| 11141 | /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11142 | /// when possible. This makes it generally easy to do alias analysis and/or |
| 11143 | /// SROA/mem2reg of the memory object. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11144 | static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) { |
| 11145 | User *CI = cast<User>(SI.getOperand(1)); |
| 11146 | Value *CastOp = CI->getOperand(0); |
| 11147 | |
| 11148 | const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType(); |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11149 | const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType()); |
| 11150 | if (SrcTy == 0) return 0; |
| 11151 | |
| 11152 | const Type *SrcPTy = SrcTy->getElementType(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11153 | |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11154 | if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy)) |
| 11155 | return 0; |
| 11156 | |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11157 | /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep" |
| 11158 | /// to its first element. This allows us to handle things like: |
| 11159 | /// store i32 xxx, (bitcast {foo*, float}* %P to i32*) |
| 11160 | /// on 32-bit hosts. |
| 11161 | SmallVector<Value*, 4> NewGEPIndices; |
| 11162 | |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11163 | // If the source is an array, the code below will not succeed. Check to |
| 11164 | // see if a trivial 'gep P, 0, 0' will help matters. Only do this for |
| 11165 | // constants. |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11166 | if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) { |
| 11167 | // Index through pointer. |
| 11168 | Constant *Zero = Constant::getNullValue(Type::Int32Ty); |
| 11169 | NewGEPIndices.push_back(Zero); |
| 11170 | |
| 11171 | while (1) { |
| 11172 | if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) { |
edwin | 7dc0aa3 | 2009-01-24 17:16:04 +0000 | [diff] [blame] | 11173 | if (!STy->getNumElements()) /* Struct can be empty {} */ |
edwin | 07d74e7 | 2009-01-24 11:30:49 +0000 | [diff] [blame] | 11174 | break; |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11175 | NewGEPIndices.push_back(Zero); |
| 11176 | SrcPTy = STy->getElementType(0); |
| 11177 | } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) { |
| 11178 | NewGEPIndices.push_back(Zero); |
| 11179 | SrcPTy = ATy->getElementType(); |
| 11180 | } else { |
| 11181 | break; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11182 | } |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11183 | } |
| 11184 | |
| 11185 | SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace()); |
| 11186 | } |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11187 | |
| 11188 | if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy)) |
| 11189 | return 0; |
| 11190 | |
Chris Lattner | c73a0d1 | 2009-01-16 20:12:52 +0000 | [diff] [blame] | 11191 | // If the pointers point into different address spaces or if they point to |
| 11192 | // values with different sizes, we can't do the transformation. |
| 11193 | if (SrcTy->getAddressSpace() != |
| 11194 | cast<PointerType>(CI->getType())->getAddressSpace() || |
| 11195 | IC.getTargetData().getTypeSizeInBits(SrcPTy) != |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11196 | IC.getTargetData().getTypeSizeInBits(DestPTy)) |
| 11197 | return 0; |
| 11198 | |
| 11199 | // Okay, we are casting from one integer or pointer type to another of |
| 11200 | // the same size. Instead of casting the pointer before |
| 11201 | // the store, cast the value to be stored. |
| 11202 | Value *NewCast; |
| 11203 | Value *SIOp0 = SI.getOperand(0); |
| 11204 | Instruction::CastOps opcode = Instruction::BitCast; |
| 11205 | const Type* CastSrcTy = SIOp0->getType(); |
| 11206 | const Type* CastDstTy = SrcPTy; |
| 11207 | if (isa<PointerType>(CastDstTy)) { |
| 11208 | if (CastSrcTy->isInteger()) |
| 11209 | opcode = Instruction::IntToPtr; |
| 11210 | } else if (isa<IntegerType>(CastDstTy)) { |
| 11211 | if (isa<PointerType>(SIOp0->getType())) |
| 11212 | opcode = Instruction::PtrToInt; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11213 | } |
Chris Lattner | 54dddc7 | 2009-01-24 01:00:13 +0000 | [diff] [blame] | 11214 | |
| 11215 | // SIOp0 is a pointer to aggregate and this is a store to the first field, |
| 11216 | // emit a GEP to index into its first field. |
| 11217 | if (!NewGEPIndices.empty()) { |
| 11218 | if (Constant *C = dyn_cast<Constant>(CastOp)) |
| 11219 | CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], |
| 11220 | NewGEPIndices.size()); |
| 11221 | else |
| 11222 | CastOp = IC.InsertNewInstBefore( |
| 11223 | GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(), |
| 11224 | NewGEPIndices.end()), SI); |
| 11225 | } |
| 11226 | |
Chris Lattner | a032c0e | 2009-01-16 20:08:59 +0000 | [diff] [blame] | 11227 | if (Constant *C = dyn_cast<Constant>(SIOp0)) |
| 11228 | NewCast = ConstantExpr::getCast(opcode, C, CastDstTy); |
| 11229 | else |
| 11230 | NewCast = IC.InsertNewInstBefore( |
| 11231 | CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), |
| 11232 | SI); |
| 11233 | return new StoreInst(NewCast, CastOp); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11234 | } |
| 11235 | |
Chris Lattner | 6fd8c80 | 2008-11-27 08:56:30 +0000 | [diff] [blame] | 11236 | /// equivalentAddressValues - Test if A and B will obviously have the same |
| 11237 | /// value. This includes recognizing that %t0 and %t1 will have the same |
| 11238 | /// value in code like this: |
| 11239 | /// %t0 = getelementptr @a, 0, 3 |
| 11240 | /// store i32 0, i32* %t0 |
| 11241 | /// %t1 = getelementptr @a, 0, 3 |
| 11242 | /// %t2 = load i32* %t1 |
| 11243 | /// |
| 11244 | static bool equivalentAddressValues(Value *A, Value *B) { |
| 11245 | // Test if the values are trivially equivalent. |
| 11246 | if (A == B) return true; |
| 11247 | |
| 11248 | // Test if the values come form identical arithmetic instructions. |
| 11249 | if (isa<BinaryOperator>(A) || |
| 11250 | isa<CastInst>(A) || |
| 11251 | isa<PHINode>(A) || |
| 11252 | isa<GetElementPtrInst>(A)) |
| 11253 | if (Instruction *BI = dyn_cast<Instruction>(B)) |
| 11254 | if (cast<Instruction>(A)->isIdenticalTo(BI)) |
| 11255 | return true; |
| 11256 | |
| 11257 | // Otherwise they may not be equivalent. |
| 11258 | return false; |
| 11259 | } |
| 11260 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11261 | Instruction *InstCombiner::visitStoreInst(StoreInst &SI) { |
| 11262 | Value *Val = SI.getOperand(0); |
| 11263 | Value *Ptr = SI.getOperand(1); |
| 11264 | |
| 11265 | if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile) |
| 11266 | EraseInstFromFunction(SI); |
| 11267 | ++NumCombined; |
| 11268 | return 0; |
| 11269 | } |
| 11270 | |
| 11271 | // If the RHS is an alloca with a single use, zapify the store, making the |
| 11272 | // alloca dead. |
Chris Lattner | a02bacc | 2008-04-29 04:58:38 +0000 | [diff] [blame] | 11273 | if (Ptr->hasOneUse() && !SI.isVolatile()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11274 | if (isa<AllocaInst>(Ptr)) { |
| 11275 | EraseInstFromFunction(SI); |
| 11276 | ++NumCombined; |
| 11277 | return 0; |
| 11278 | } |
| 11279 | |
| 11280 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) |
| 11281 | if (isa<AllocaInst>(GEP->getOperand(0)) && |
| 11282 | GEP->getOperand(0)->hasOneUse()) { |
| 11283 | EraseInstFromFunction(SI); |
| 11284 | ++NumCombined; |
| 11285 | return 0; |
| 11286 | } |
| 11287 | } |
| 11288 | |
Dan Gohman | 5c4d0e1 | 2007-07-20 16:34:21 +0000 | [diff] [blame] | 11289 | // Attempt to improve the alignment. |
Dan Gohman | 2d648bb | 2008-04-10 18:43:06 +0000 | [diff] [blame] | 11290 | unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr); |
| 11291 | if (KnownAlign > |
| 11292 | (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) : |
| 11293 | SI.getAlignment())) |
Dan Gohman | 5c4d0e1 | 2007-07-20 16:34:21 +0000 | [diff] [blame] | 11294 | SI.setAlignment(KnownAlign); |
| 11295 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11296 | // Do really simple DSE, to catch cases where there are several consequtive |
| 11297 | // stores to the same location, separated by a few arithmetic operations. This |
| 11298 | // situation often occurs with bitfield accesses. |
| 11299 | BasicBlock::iterator BBI = &SI; |
| 11300 | for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts; |
| 11301 | --ScanInsts) { |
| 11302 | --BBI; |
| 11303 | |
| 11304 | if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) { |
| 11305 | // Prev store isn't volatile, and stores to the same location? |
Chris Lattner | 6fd8c80 | 2008-11-27 08:56:30 +0000 | [diff] [blame] | 11306 | if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1), |
| 11307 | SI.getOperand(1))) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11308 | ++NumDeadStore; |
| 11309 | ++BBI; |
| 11310 | EraseInstFromFunction(*PrevSI); |
| 11311 | continue; |
| 11312 | } |
| 11313 | break; |
| 11314 | } |
| 11315 | |
| 11316 | // If this is a load, we have to stop. However, if the loaded value is from |
| 11317 | // the pointer we're loading and is producing the pointer we're storing, |
| 11318 | // then *this* store is dead (X = load P; store X -> P). |
| 11319 | if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { |
Dan Gohman | 0ff5a1f | 2008-10-15 23:19:35 +0000 | [diff] [blame] | 11320 | if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) && |
| 11321 | !SI.isVolatile()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11322 | EraseInstFromFunction(SI); |
| 11323 | ++NumCombined; |
| 11324 | return 0; |
| 11325 | } |
| 11326 | // Otherwise, this is a load from some other location. Stores before it |
| 11327 | // may not be dead. |
| 11328 | break; |
| 11329 | } |
| 11330 | |
| 11331 | // Don't skip over loads or things that can modify memory. |
Chris Lattner | 8450428 | 2008-05-08 17:20:30 +0000 | [diff] [blame] | 11332 | if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory()) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11333 | break; |
| 11334 | } |
| 11335 | |
| 11336 | |
| 11337 | if (SI.isVolatile()) return 0; // Don't hack volatile stores. |
| 11338 | |
| 11339 | // store X, null -> turns into 'unreachable' in SimplifyCFG |
| 11340 | if (isa<ConstantPointerNull>(Ptr)) { |
| 11341 | if (!isa<UndefValue>(Val)) { |
| 11342 | SI.setOperand(0, UndefValue::get(Val->getType())); |
| 11343 | if (Instruction *U = dyn_cast<Instruction>(Val)) |
| 11344 | AddToWorkList(U); // Dropped a use. |
| 11345 | ++NumCombined; |
| 11346 | } |
| 11347 | return 0; // Do not modify these! |
| 11348 | } |
| 11349 | |
| 11350 | // store undef, Ptr -> noop |
| 11351 | if (isa<UndefValue>(Val)) { |
| 11352 | EraseInstFromFunction(SI); |
| 11353 | ++NumCombined; |
| 11354 | return 0; |
| 11355 | } |
| 11356 | |
| 11357 | // If the pointer destination is a cast, see if we can fold the cast into the |
| 11358 | // source instead. |
| 11359 | if (isa<CastInst>(Ptr)) |
| 11360 | if (Instruction *Res = InstCombineStoreToCast(*this, SI)) |
| 11361 | return Res; |
| 11362 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) |
| 11363 | if (CE->isCast()) |
| 11364 | if (Instruction *Res = InstCombineStoreToCast(*this, SI)) |
| 11365 | return Res; |
| 11366 | |
| 11367 | |
| 11368 | // If this store is the last instruction in the basic block, and if the block |
| 11369 | // ends with an unconditional branch, try to move it to the successor block. |
| 11370 | BBI = &SI; ++BBI; |
| 11371 | if (BranchInst *BI = dyn_cast<BranchInst>(BBI)) |
| 11372 | if (BI->isUnconditional()) |
| 11373 | if (SimplifyStoreAtEndOfBlock(SI)) |
| 11374 | return 0; // xform done! |
| 11375 | |
| 11376 | return 0; |
| 11377 | } |
| 11378 | |
| 11379 | /// SimplifyStoreAtEndOfBlock - Turn things like: |
| 11380 | /// if () { *P = v1; } else { *P = v2 } |
| 11381 | /// into a phi node with a store in the successor. |
| 11382 | /// |
| 11383 | /// Simplify things like: |
| 11384 | /// *P = v1; if () { *P = v2; } |
| 11385 | /// into a phi node with a store in the successor. |
| 11386 | /// |
| 11387 | bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) { |
| 11388 | BasicBlock *StoreBB = SI.getParent(); |
| 11389 | |
| 11390 | // Check to see if the successor block has exactly two incoming edges. If |
| 11391 | // so, see if the other predecessor contains a store to the same location. |
| 11392 | // if so, insert a PHI node (if needed) and move the stores down. |
| 11393 | BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0); |
| 11394 | |
| 11395 | // Determine whether Dest has exactly two predecessors and, if so, compute |
| 11396 | // the other predecessor. |
| 11397 | pred_iterator PI = pred_begin(DestBB); |
| 11398 | BasicBlock *OtherBB = 0; |
| 11399 | if (*PI != StoreBB) |
| 11400 | OtherBB = *PI; |
| 11401 | ++PI; |
| 11402 | if (PI == pred_end(DestBB)) |
| 11403 | return false; |
| 11404 | |
| 11405 | if (*PI != StoreBB) { |
| 11406 | if (OtherBB) |
| 11407 | return false; |
| 11408 | OtherBB = *PI; |
| 11409 | } |
| 11410 | if (++PI != pred_end(DestBB)) |
| 11411 | return false; |
Eli Friedman | ab39f9a | 2008-06-13 21:17:49 +0000 | [diff] [blame] | 11412 | |
| 11413 | // Bail out if all the relevant blocks aren't distinct (this can happen, |
| 11414 | // for example, if SI is in an infinite loop) |
| 11415 | if (StoreBB == DestBB || OtherBB == DestBB) |
| 11416 | return false; |
| 11417 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11418 | // Verify that the other block ends in a branch and is not otherwise empty. |
| 11419 | BasicBlock::iterator BBI = OtherBB->getTerminator(); |
| 11420 | BranchInst *OtherBr = dyn_cast<BranchInst>(BBI); |
| 11421 | if (!OtherBr || BBI == OtherBB->begin()) |
| 11422 | return false; |
| 11423 | |
| 11424 | // If the other block ends in an unconditional branch, check for the 'if then |
| 11425 | // else' case. there is an instruction before the branch. |
| 11426 | StoreInst *OtherStore = 0; |
| 11427 | if (OtherBr->isUnconditional()) { |
| 11428 | // If this isn't a store, or isn't a store to the same location, bail out. |
| 11429 | --BBI; |
| 11430 | OtherStore = dyn_cast<StoreInst>(BBI); |
| 11431 | if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1)) |
| 11432 | return false; |
| 11433 | } else { |
| 11434 | // Otherwise, the other block ended with a conditional branch. If one of the |
| 11435 | // destinations is StoreBB, then we have the if/then case. |
| 11436 | if (OtherBr->getSuccessor(0) != StoreBB && |
| 11437 | OtherBr->getSuccessor(1) != StoreBB) |
| 11438 | return false; |
| 11439 | |
| 11440 | // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an |
| 11441 | // if/then triangle. See if there is a store to the same ptr as SI that |
| 11442 | // lives in OtherBB. |
| 11443 | for (;; --BBI) { |
| 11444 | // Check to see if we find the matching store. |
| 11445 | if ((OtherStore = dyn_cast<StoreInst>(BBI))) { |
| 11446 | if (OtherStore->getOperand(1) != SI.getOperand(1)) |
| 11447 | return false; |
| 11448 | break; |
| 11449 | } |
Eli Friedman | 3a311d5 | 2008-06-13 22:02:12 +0000 | [diff] [blame] | 11450 | // If we find something that may be using or overwriting the stored |
| 11451 | // value, or if we run out of instructions, we can't do the xform. |
| 11452 | if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() || |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11453 | BBI == OtherBB->begin()) |
| 11454 | return false; |
| 11455 | } |
| 11456 | |
| 11457 | // In order to eliminate the store in OtherBr, we have to |
Eli Friedman | 3a311d5 | 2008-06-13 22:02:12 +0000 | [diff] [blame] | 11458 | // make sure nothing reads or overwrites the stored value in |
| 11459 | // StoreBB. |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11460 | for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) { |
| 11461 | // FIXME: This should really be AA driven. |
Eli Friedman | 3a311d5 | 2008-06-13 22:02:12 +0000 | [diff] [blame] | 11462 | if (I->mayReadFromMemory() || I->mayWriteToMemory()) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11463 | return false; |
| 11464 | } |
| 11465 | } |
| 11466 | |
| 11467 | // Insert a PHI node now if we need it. |
| 11468 | Value *MergedVal = OtherStore->getOperand(0); |
| 11469 | if (MergedVal != SI.getOperand(0)) { |
Gabor Greif | d6da1d0 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 11470 | PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11471 | PN->reserveOperandSpace(2); |
| 11472 | PN->addIncoming(SI.getOperand(0), SI.getParent()); |
| 11473 | PN->addIncoming(OtherStore->getOperand(0), OtherBB); |
| 11474 | MergedVal = InsertNewInstBefore(PN, DestBB->front()); |
| 11475 | } |
| 11476 | |
| 11477 | // Advance to a place where it is safe to insert the new store and |
| 11478 | // insert it. |
Dan Gohman | 514277c | 2008-05-23 21:05:58 +0000 | [diff] [blame] | 11479 | BBI = DestBB->getFirstNonPHI(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11480 | InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1), |
| 11481 | OtherStore->isVolatile()), *BBI); |
| 11482 | |
| 11483 | // Nuke the old stores. |
| 11484 | EraseInstFromFunction(SI); |
| 11485 | EraseInstFromFunction(*OtherStore); |
| 11486 | ++NumCombined; |
| 11487 | return true; |
| 11488 | } |
| 11489 | |
| 11490 | |
| 11491 | Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { |
| 11492 | // Change br (not X), label True, label False to: br X, label False, True |
| 11493 | Value *X = 0; |
| 11494 | BasicBlock *TrueDest; |
| 11495 | BasicBlock *FalseDest; |
| 11496 | if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && |
| 11497 | !isa<Constant>(X)) { |
| 11498 | // Swap Destinations and condition... |
| 11499 | BI.setCondition(X); |
| 11500 | BI.setSuccessor(0, FalseDest); |
| 11501 | BI.setSuccessor(1, TrueDest); |
| 11502 | return &BI; |
| 11503 | } |
| 11504 | |
| 11505 | // Cannonicalize fcmp_one -> fcmp_oeq |
| 11506 | FCmpInst::Predicate FPred; Value *Y; |
| 11507 | if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), |
| 11508 | TrueDest, FalseDest))) |
| 11509 | if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || |
| 11510 | FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) { |
| 11511 | FCmpInst *I = cast<FCmpInst>(BI.getCondition()); |
| 11512 | FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred); |
| 11513 | Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I); |
| 11514 | NewSCC->takeName(I); |
| 11515 | // Swap Destinations and condition... |
| 11516 | BI.setCondition(NewSCC); |
| 11517 | BI.setSuccessor(0, FalseDest); |
| 11518 | BI.setSuccessor(1, TrueDest); |
| 11519 | RemoveFromWorkList(I); |
| 11520 | I->eraseFromParent(); |
| 11521 | AddToWorkList(NewSCC); |
| 11522 | return &BI; |
| 11523 | } |
| 11524 | |
| 11525 | // Cannonicalize icmp_ne -> icmp_eq |
| 11526 | ICmpInst::Predicate IPred; |
| 11527 | if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), |
| 11528 | TrueDest, FalseDest))) |
| 11529 | if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || |
| 11530 | IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || |
| 11531 | IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) { |
| 11532 | ICmpInst *I = cast<ICmpInst>(BI.getCondition()); |
| 11533 | ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred); |
| 11534 | Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I); |
| 11535 | NewSCC->takeName(I); |
| 11536 | // Swap Destinations and condition... |
| 11537 | BI.setCondition(NewSCC); |
| 11538 | BI.setSuccessor(0, FalseDest); |
| 11539 | BI.setSuccessor(1, TrueDest); |
| 11540 | RemoveFromWorkList(I); |
| 11541 | I->eraseFromParent();; |
| 11542 | AddToWorkList(NewSCC); |
| 11543 | return &BI; |
| 11544 | } |
| 11545 | |
| 11546 | return 0; |
| 11547 | } |
| 11548 | |
| 11549 | Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { |
| 11550 | Value *Cond = SI.getCondition(); |
| 11551 | if (Instruction *I = dyn_cast<Instruction>(Cond)) { |
| 11552 | if (I->getOpcode() == Instruction::Add) |
| 11553 | if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) { |
| 11554 | // change 'switch (X+4) case 1:' into 'switch (X) case -3' |
| 11555 | for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) |
| 11556 | SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)), |
| 11557 | AddRHS)); |
| 11558 | SI.setOperand(0, I->getOperand(0)); |
| 11559 | AddToWorkList(I); |
| 11560 | return &SI; |
| 11561 | } |
| 11562 | } |
| 11563 | return 0; |
| 11564 | } |
| 11565 | |
Matthijs Kooijman | da9ef70 | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 11566 | Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { |
Matthijs Kooijman | 45e8eb4 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 11567 | Value *Agg = EV.getAggregateOperand(); |
Matthijs Kooijman | da9ef70 | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 11568 | |
Matthijs Kooijman | 45e8eb4 | 2008-07-16 12:55:45 +0000 | [diff] [blame] | 11569 | if (!EV.hasIndices()) |
| 11570 | return ReplaceInstUsesWith(EV, Agg); |
| 11571 | |
| 11572 | if (Constant *C = dyn_cast<Constant>(Agg)) { |
| 11573 | if (isa<UndefValue>(C)) |
| 11574 | return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType())); |
| 11575 | |
| 11576 | if (isa<ConstantAggregateZero>(C)) |
| 11577 | return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType())); |
| 11578 | |
| 11579 | if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) { |
| 11580 | // Extract the element indexed by the first index out of the constant |
| 11581 | Value *V = C->getOperand(*EV.idx_begin()); |
| 11582 | if (EV.getNumIndices() > 1) |
| 11583 | // Extract the remaining indices out of the constant indexed by the |
| 11584 | // first index |
| 11585 | return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end()); |
| 11586 | else |
| 11587 | return ReplaceInstUsesWith(EV, V); |
| 11588 | } |
| 11589 | return 0; // Can't handle other constants |
| 11590 | } |
| 11591 | if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { |
| 11592 | // We're extracting from an insertvalue instruction, compare the indices |
| 11593 | const unsigned *exti, *exte, *insi, *inse; |
| 11594 | for (exti = EV.idx_begin(), insi = IV->idx_begin(), |
| 11595 | exte = EV.idx_end(), inse = IV->idx_end(); |
| 11596 | exti != exte && insi != inse; |
| 11597 | ++exti, ++insi) { |
| 11598 | if (*insi != *exti) |
| 11599 | // The insert and extract both reference distinctly different elements. |
| 11600 | // This means the extract is not influenced by the insert, and we can |
| 11601 | // replace the aggregate operand of the extract with the aggregate |
| 11602 | // operand of the insert. i.e., replace |
| 11603 | // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 |
| 11604 | // %E = extractvalue { i32, { i32 } } %I, 0 |
| 11605 | // with |
| 11606 | // %E = extractvalue { i32, { i32 } } %A, 0 |
| 11607 | return ExtractValueInst::Create(IV->getAggregateOperand(), |
| 11608 | EV.idx_begin(), EV.idx_end()); |
| 11609 | } |
| 11610 | if (exti == exte && insi == inse) |
| 11611 | // Both iterators are at the end: Index lists are identical. Replace |
| 11612 | // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 |
| 11613 | // %C = extractvalue { i32, { i32 } } %B, 1, 0 |
| 11614 | // with "i32 42" |
| 11615 | return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand()); |
| 11616 | if (exti == exte) { |
| 11617 | // The extract list is a prefix of the insert list. i.e. replace |
| 11618 | // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 |
| 11619 | // %E = extractvalue { i32, { i32 } } %I, 1 |
| 11620 | // with |
| 11621 | // %X = extractvalue { i32, { i32 } } %A, 1 |
| 11622 | // %E = insertvalue { i32 } %X, i32 42, 0 |
| 11623 | // by switching the order of the insert and extract (though the |
| 11624 | // insertvalue should be left in, since it may have other uses). |
| 11625 | Value *NewEV = InsertNewInstBefore( |
| 11626 | ExtractValueInst::Create(IV->getAggregateOperand(), |
| 11627 | EV.idx_begin(), EV.idx_end()), |
| 11628 | EV); |
| 11629 | return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), |
| 11630 | insi, inse); |
| 11631 | } |
| 11632 | if (insi == inse) |
| 11633 | // The insert list is a prefix of the extract list |
| 11634 | // We can simply remove the common indices from the extract and make it |
| 11635 | // operate on the inserted value instead of the insertvalue result. |
| 11636 | // i.e., replace |
| 11637 | // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 |
| 11638 | // %E = extractvalue { i32, { i32 } } %I, 1, 0 |
| 11639 | // with |
| 11640 | // %E extractvalue { i32 } { i32 42 }, 0 |
| 11641 | return ExtractValueInst::Create(IV->getInsertedValueOperand(), |
| 11642 | exti, exte); |
| 11643 | } |
| 11644 | // Can't simplify extracts from other values. Note that nested extracts are |
| 11645 | // already simplified implicitely by the above (extract ( extract (insert) ) |
| 11646 | // will be translated into extract ( insert ( extract ) ) first and then just |
| 11647 | // the value inserted, if appropriate). |
Matthijs Kooijman | da9ef70 | 2008-06-11 14:05:05 +0000 | [diff] [blame] | 11648 | return 0; |
| 11649 | } |
| 11650 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11651 | /// CheapToScalarize - Return true if the value is cheaper to scalarize than it |
| 11652 | /// is to leave as a vector operation. |
| 11653 | static bool CheapToScalarize(Value *V, bool isConstant) { |
| 11654 | if (isa<ConstantAggregateZero>(V)) |
| 11655 | return true; |
| 11656 | if (ConstantVector *C = dyn_cast<ConstantVector>(V)) { |
| 11657 | if (isConstant) return true; |
| 11658 | // If all elts are the same, we can extract. |
| 11659 | Constant *Op0 = C->getOperand(0); |
| 11660 | for (unsigned i = 1; i < C->getNumOperands(); ++i) |
| 11661 | if (C->getOperand(i) != Op0) |
| 11662 | return false; |
| 11663 | return true; |
| 11664 | } |
| 11665 | Instruction *I = dyn_cast<Instruction>(V); |
| 11666 | if (!I) return false; |
| 11667 | |
| 11668 | // Insert element gets simplified to the inserted element or is deleted if |
| 11669 | // this is constant idx extract element and its a constant idx insertelt. |
| 11670 | if (I->getOpcode() == Instruction::InsertElement && isConstant && |
| 11671 | isa<ConstantInt>(I->getOperand(2))) |
| 11672 | return true; |
| 11673 | if (I->getOpcode() == Instruction::Load && I->hasOneUse()) |
| 11674 | return true; |
| 11675 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) |
| 11676 | if (BO->hasOneUse() && |
| 11677 | (CheapToScalarize(BO->getOperand(0), isConstant) || |
| 11678 | CheapToScalarize(BO->getOperand(1), isConstant))) |
| 11679 | return true; |
| 11680 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
| 11681 | if (CI->hasOneUse() && |
| 11682 | (CheapToScalarize(CI->getOperand(0), isConstant) || |
| 11683 | CheapToScalarize(CI->getOperand(1), isConstant))) |
| 11684 | return true; |
| 11685 | |
| 11686 | return false; |
| 11687 | } |
| 11688 | |
| 11689 | /// Read and decode a shufflevector mask. |
| 11690 | /// |
| 11691 | /// It turns undef elements into values that are larger than the number of |
| 11692 | /// elements in the input. |
| 11693 | static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) { |
| 11694 | unsigned NElts = SVI->getType()->getNumElements(); |
| 11695 | if (isa<ConstantAggregateZero>(SVI->getOperand(2))) |
| 11696 | return std::vector<unsigned>(NElts, 0); |
| 11697 | if (isa<UndefValue>(SVI->getOperand(2))) |
| 11698 | return std::vector<unsigned>(NElts, 2*NElts); |
| 11699 | |
| 11700 | std::vector<unsigned> Result; |
| 11701 | const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2)); |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 11702 | for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i) |
| 11703 | if (isa<UndefValue>(*i)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11704 | Result.push_back(NElts*2); // undef -> 8 |
| 11705 | else |
Gabor Greif | 1739600 | 2008-06-12 21:37:33 +0000 | [diff] [blame] | 11706 | Result.push_back(cast<ConstantInt>(*i)->getZExtValue()); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11707 | return Result; |
| 11708 | } |
| 11709 | |
| 11710 | /// FindScalarElement - Given a vector and an element number, see if the scalar |
| 11711 | /// value is already around as a register, for example if it were inserted then |
| 11712 | /// extracted from the vector. |
| 11713 | static Value *FindScalarElement(Value *V, unsigned EltNo) { |
| 11714 | assert(isa<VectorType>(V->getType()) && "Not looking at a vector?"); |
| 11715 | const VectorType *PTy = cast<VectorType>(V->getType()); |
| 11716 | unsigned Width = PTy->getNumElements(); |
| 11717 | if (EltNo >= Width) // Out of range access. |
| 11718 | return UndefValue::get(PTy->getElementType()); |
| 11719 | |
| 11720 | if (isa<UndefValue>(V)) |
| 11721 | return UndefValue::get(PTy->getElementType()); |
| 11722 | else if (isa<ConstantAggregateZero>(V)) |
| 11723 | return Constant::getNullValue(PTy->getElementType()); |
| 11724 | else if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) |
| 11725 | return CP->getOperand(EltNo); |
| 11726 | else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) { |
| 11727 | // If this is an insert to a variable element, we don't know what it is. |
| 11728 | if (!isa<ConstantInt>(III->getOperand(2))) |
| 11729 | return 0; |
| 11730 | unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue(); |
| 11731 | |
| 11732 | // If this is an insert to the element we are looking for, return the |
| 11733 | // inserted value. |
| 11734 | if (EltNo == IIElt) |
| 11735 | return III->getOperand(1); |
| 11736 | |
| 11737 | // Otherwise, the insertelement doesn't modify the value, recurse on its |
| 11738 | // vector input. |
| 11739 | return FindScalarElement(III->getOperand(0), EltNo); |
| 11740 | } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) { |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 11741 | unsigned LHSWidth = |
| 11742 | cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11743 | unsigned InEl = getShuffleMask(SVI)[EltNo]; |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 11744 | if (InEl < LHSWidth) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11745 | return FindScalarElement(SVI->getOperand(0), InEl); |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 11746 | else if (InEl < LHSWidth*2) |
| 11747 | return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11748 | else |
| 11749 | return UndefValue::get(PTy->getElementType()); |
| 11750 | } |
| 11751 | |
| 11752 | // Otherwise, we don't know. |
| 11753 | return 0; |
| 11754 | } |
| 11755 | |
| 11756 | Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11757 | // If vector val is undef, replace extract with scalar undef. |
| 11758 | if (isa<UndefValue>(EI.getOperand(0))) |
| 11759 | return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType())); |
| 11760 | |
| 11761 | // If vector val is constant 0, replace extract with scalar 0. |
| 11762 | if (isa<ConstantAggregateZero>(EI.getOperand(0))) |
| 11763 | return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType())); |
| 11764 | |
| 11765 | if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) { |
Matthijs Kooijman | dd3425f | 2008-06-11 09:00:12 +0000 | [diff] [blame] | 11766 | // If vector val is constant with all elements the same, replace EI with |
| 11767 | // that element. When the elements are not identical, we cannot replace yet |
| 11768 | // (we do that below, but only when the index is constant). |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11769 | Constant *op0 = C->getOperand(0); |
| 11770 | for (unsigned i = 1; i < C->getNumOperands(); ++i) |
| 11771 | if (C->getOperand(i) != op0) { |
| 11772 | op0 = 0; |
| 11773 | break; |
| 11774 | } |
| 11775 | if (op0) |
| 11776 | return ReplaceInstUsesWith(EI, op0); |
| 11777 | } |
| 11778 | |
| 11779 | // If extracting a specified index from the vector, see if we can recursively |
| 11780 | // find a previously computed scalar that was inserted into the vector. |
| 11781 | if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { |
| 11782 | unsigned IndexVal = IdxC->getZExtValue(); |
| 11783 | unsigned VectorWidth = |
| 11784 | cast<VectorType>(EI.getOperand(0)->getType())->getNumElements(); |
| 11785 | |
| 11786 | // If this is extracting an invalid index, turn this into undef, to avoid |
| 11787 | // crashing the code below. |
| 11788 | if (IndexVal >= VectorWidth) |
| 11789 | return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType())); |
| 11790 | |
| 11791 | // This instruction only demands the single element from the input vector. |
| 11792 | // If the input vector has a single use, simplify it based on this use |
| 11793 | // property. |
| 11794 | if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { |
| 11795 | uint64_t UndefElts; |
| 11796 | if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), |
| 11797 | 1 << IndexVal, |
| 11798 | UndefElts)) { |
| 11799 | EI.setOperand(0, V); |
| 11800 | return &EI; |
| 11801 | } |
| 11802 | } |
| 11803 | |
| 11804 | if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal)) |
| 11805 | return ReplaceInstUsesWith(EI, Elt); |
| 11806 | |
| 11807 | // If the this extractelement is directly using a bitcast from a vector of |
| 11808 | // the same number of elements, see if we can find the source element from |
| 11809 | // it. In this case, we will end up needing to bitcast the scalars. |
| 11810 | if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { |
| 11811 | if (const VectorType *VT = |
| 11812 | dyn_cast<VectorType>(BCI->getOperand(0)->getType())) |
| 11813 | if (VT->getNumElements() == VectorWidth) |
| 11814 | if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal)) |
| 11815 | return new BitCastInst(Elt, EI.getType()); |
| 11816 | } |
| 11817 | } |
| 11818 | |
| 11819 | if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { |
| 11820 | if (I->hasOneUse()) { |
| 11821 | // Push extractelement into predecessor operation if legal and |
| 11822 | // profitable to do so |
| 11823 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { |
| 11824 | bool isConstantElt = isa<ConstantInt>(EI.getOperand(1)); |
| 11825 | if (CheapToScalarize(BO, isConstantElt)) { |
| 11826 | ExtractElementInst *newEI0 = |
| 11827 | new ExtractElementInst(BO->getOperand(0), EI.getOperand(1), |
| 11828 | EI.getName()+".lhs"); |
| 11829 | ExtractElementInst *newEI1 = |
| 11830 | new ExtractElementInst(BO->getOperand(1), EI.getOperand(1), |
| 11831 | EI.getName()+".rhs"); |
| 11832 | InsertNewInstBefore(newEI0, EI); |
| 11833 | InsertNewInstBefore(newEI1, EI); |
Gabor Greif | a645dd3 | 2008-05-16 19:29:10 +0000 | [diff] [blame] | 11834 | return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11835 | } |
| 11836 | } else if (isa<LoadInst>(I)) { |
Christopher Lamb | bb2f222 | 2007-12-17 01:12:55 +0000 | [diff] [blame] | 11837 | unsigned AS = |
| 11838 | cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace(); |
Chris Lattner | 13c2d6e | 2008-01-13 22:23:22 +0000 | [diff] [blame] | 11839 | Value *Ptr = InsertBitCastBefore(I->getOperand(0), |
| 11840 | PointerType::get(EI.getType(), AS),EI); |
Gabor Greif | b91ea9d | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 11841 | GetElementPtrInst *GEP = |
| 11842 | GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep"); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11843 | InsertNewInstBefore(GEP, EI); |
| 11844 | return new LoadInst(GEP); |
| 11845 | } |
| 11846 | } |
| 11847 | if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { |
| 11848 | // Extracting the inserted element? |
| 11849 | if (IE->getOperand(2) == EI.getOperand(1)) |
| 11850 | return ReplaceInstUsesWith(EI, IE->getOperand(1)); |
| 11851 | // If the inserted and extracted elements are constants, they must not |
| 11852 | // be the same value, extract from the pre-inserted value instead. |
| 11853 | if (isa<Constant>(IE->getOperand(2)) && |
| 11854 | isa<Constant>(EI.getOperand(1))) { |
| 11855 | AddUsesToWorkList(EI); |
| 11856 | EI.setOperand(0, IE->getOperand(0)); |
| 11857 | return &EI; |
| 11858 | } |
| 11859 | } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { |
| 11860 | // If this is extracting an element from a shufflevector, figure out where |
| 11861 | // it came from and extract from the appropriate input element instead. |
| 11862 | if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { |
| 11863 | unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()]; |
| 11864 | Value *Src; |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 11865 | unsigned LHSWidth = |
| 11866 | cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements(); |
| 11867 | |
| 11868 | if (SrcIdx < LHSWidth) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11869 | Src = SVI->getOperand(0); |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 11870 | else if (SrcIdx < LHSWidth*2) { |
| 11871 | SrcIdx -= LHSWidth; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11872 | Src = SVI->getOperand(1); |
| 11873 | } else { |
| 11874 | return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType())); |
| 11875 | } |
| 11876 | return new ExtractElementInst(Src, SrcIdx); |
| 11877 | } |
| 11878 | } |
| 11879 | } |
| 11880 | return 0; |
| 11881 | } |
| 11882 | |
| 11883 | /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns |
| 11884 | /// elements from either LHS or RHS, return the shuffle mask and true. |
| 11885 | /// Otherwise, return false. |
| 11886 | static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, |
| 11887 | std::vector<Constant*> &Mask) { |
| 11888 | assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() && |
| 11889 | "Invalid CollectSingleShuffleElements"); |
| 11890 | unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); |
| 11891 | |
| 11892 | if (isa<UndefValue>(V)) { |
| 11893 | Mask.assign(NumElts, UndefValue::get(Type::Int32Ty)); |
| 11894 | return true; |
| 11895 | } else if (V == LHS) { |
| 11896 | for (unsigned i = 0; i != NumElts; ++i) |
| 11897 | Mask.push_back(ConstantInt::get(Type::Int32Ty, i)); |
| 11898 | return true; |
| 11899 | } else if (V == RHS) { |
| 11900 | for (unsigned i = 0; i != NumElts; ++i) |
| 11901 | Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts)); |
| 11902 | return true; |
| 11903 | } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { |
| 11904 | // If this is an insert of an extract from some other vector, include it. |
| 11905 | Value *VecOp = IEI->getOperand(0); |
| 11906 | Value *ScalarOp = IEI->getOperand(1); |
| 11907 | Value *IdxOp = IEI->getOperand(2); |
| 11908 | |
| 11909 | if (!isa<ConstantInt>(IdxOp)) |
| 11910 | return false; |
| 11911 | unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); |
| 11912 | |
| 11913 | if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. |
| 11914 | // Okay, we can handle this if the vector we are insertinting into is |
| 11915 | // transitively ok. |
| 11916 | if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { |
| 11917 | // If so, update the mask to reflect the inserted undef. |
| 11918 | Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty); |
| 11919 | return true; |
| 11920 | } |
| 11921 | } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ |
| 11922 | if (isa<ConstantInt>(EI->getOperand(1)) && |
| 11923 | EI->getOperand(0)->getType() == V->getType()) { |
| 11924 | unsigned ExtractedIdx = |
| 11925 | cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); |
| 11926 | |
| 11927 | // This must be extracting from either LHS or RHS. |
| 11928 | if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { |
| 11929 | // Okay, we can handle this if the vector we are insertinting into is |
| 11930 | // transitively ok. |
| 11931 | if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { |
| 11932 | // If so, update the mask to reflect the inserted value. |
| 11933 | if (EI->getOperand(0) == LHS) { |
Mon P Wang | 6bf3c59 | 2008-08-20 02:23:25 +0000 | [diff] [blame] | 11934 | Mask[InsertedIdx % NumElts] = |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11935 | ConstantInt::get(Type::Int32Ty, ExtractedIdx); |
| 11936 | } else { |
| 11937 | assert(EI->getOperand(0) == RHS); |
Mon P Wang | 6bf3c59 | 2008-08-20 02:23:25 +0000 | [diff] [blame] | 11938 | Mask[InsertedIdx % NumElts] = |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11939 | ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts); |
| 11940 | |
| 11941 | } |
| 11942 | return true; |
| 11943 | } |
| 11944 | } |
| 11945 | } |
| 11946 | } |
| 11947 | } |
| 11948 | // TODO: Handle shufflevector here! |
| 11949 | |
| 11950 | return false; |
| 11951 | } |
| 11952 | |
| 11953 | /// CollectShuffleElements - We are building a shuffle of V, using RHS as the |
| 11954 | /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask |
| 11955 | /// that computes V and the LHS value of the shuffle. |
| 11956 | static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask, |
| 11957 | Value *&RHS) { |
| 11958 | assert(isa<VectorType>(V->getType()) && |
| 11959 | (RHS == 0 || V->getType() == RHS->getType()) && |
| 11960 | "Invalid shuffle!"); |
| 11961 | unsigned NumElts = cast<VectorType>(V->getType())->getNumElements(); |
| 11962 | |
| 11963 | if (isa<UndefValue>(V)) { |
| 11964 | Mask.assign(NumElts, UndefValue::get(Type::Int32Ty)); |
| 11965 | return V; |
| 11966 | } else if (isa<ConstantAggregateZero>(V)) { |
| 11967 | Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0)); |
| 11968 | return V; |
| 11969 | } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { |
| 11970 | // If this is an insert of an extract from some other vector, include it. |
| 11971 | Value *VecOp = IEI->getOperand(0); |
| 11972 | Value *ScalarOp = IEI->getOperand(1); |
| 11973 | Value *IdxOp = IEI->getOperand(2); |
| 11974 | |
| 11975 | if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { |
| 11976 | if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) && |
| 11977 | EI->getOperand(0)->getType() == V->getType()) { |
| 11978 | unsigned ExtractedIdx = |
| 11979 | cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); |
| 11980 | unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); |
| 11981 | |
| 11982 | // Either the extracted from or inserted into vector must be RHSVec, |
| 11983 | // otherwise we'd end up with a shuffle of three inputs. |
| 11984 | if (EI->getOperand(0) == RHS || RHS == 0) { |
| 11985 | RHS = EI->getOperand(0); |
| 11986 | Value *V = CollectShuffleElements(VecOp, Mask, RHS); |
Mon P Wang | 6bf3c59 | 2008-08-20 02:23:25 +0000 | [diff] [blame] | 11987 | Mask[InsertedIdx % NumElts] = |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 11988 | ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx); |
| 11989 | return V; |
| 11990 | } |
| 11991 | |
| 11992 | if (VecOp == RHS) { |
| 11993 | Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS); |
| 11994 | // Everything but the extracted element is replaced with the RHS. |
| 11995 | for (unsigned i = 0; i != NumElts; ++i) { |
| 11996 | if (i != InsertedIdx) |
| 11997 | Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i); |
| 11998 | } |
| 11999 | return V; |
| 12000 | } |
| 12001 | |
| 12002 | // If this insertelement is a chain that comes from exactly these two |
| 12003 | // vectors, return the vector and the effective shuffle. |
| 12004 | if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask)) |
| 12005 | return EI->getOperand(0); |
| 12006 | |
| 12007 | } |
| 12008 | } |
| 12009 | } |
| 12010 | // TODO: Handle shufflevector here! |
| 12011 | |
| 12012 | // Otherwise, can't do anything fancy. Return an identity vector. |
| 12013 | for (unsigned i = 0; i != NumElts; ++i) |
| 12014 | Mask.push_back(ConstantInt::get(Type::Int32Ty, i)); |
| 12015 | return V; |
| 12016 | } |
| 12017 | |
| 12018 | Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { |
| 12019 | Value *VecOp = IE.getOperand(0); |
| 12020 | Value *ScalarOp = IE.getOperand(1); |
| 12021 | Value *IdxOp = IE.getOperand(2); |
| 12022 | |
| 12023 | // Inserting an undef or into an undefined place, remove this. |
| 12024 | if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) |
| 12025 | ReplaceInstUsesWith(IE, VecOp); |
| 12026 | |
| 12027 | // If the inserted element was extracted from some other vector, and if the |
| 12028 | // indexes are constant, try to turn this into a shufflevector operation. |
| 12029 | if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { |
| 12030 | if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) && |
| 12031 | EI->getOperand(0)->getType() == IE.getType()) { |
| 12032 | unsigned NumVectorElts = IE.getType()->getNumElements(); |
| 12033 | unsigned ExtractedIdx = |
| 12034 | cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); |
| 12035 | unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); |
| 12036 | |
| 12037 | if (ExtractedIdx >= NumVectorElts) // Out of range extract. |
| 12038 | return ReplaceInstUsesWith(IE, VecOp); |
| 12039 | |
| 12040 | if (InsertedIdx >= NumVectorElts) // Out of range insert. |
| 12041 | return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType())); |
| 12042 | |
| 12043 | // If we are extracting a value from a vector, then inserting it right |
| 12044 | // back into the same place, just use the input vector. |
| 12045 | if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) |
| 12046 | return ReplaceInstUsesWith(IE, VecOp); |
| 12047 | |
| 12048 | // We could theoretically do this for ANY input. However, doing so could |
| 12049 | // turn chains of insertelement instructions into a chain of shufflevector |
| 12050 | // instructions, and right now we do not merge shufflevectors. As such, |
| 12051 | // only do this in a situation where it is clear that there is benefit. |
| 12052 | if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) { |
| 12053 | // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of |
| 12054 | // the values of VecOp, except then one read from EIOp0. |
| 12055 | // Build a new shuffle mask. |
| 12056 | std::vector<Constant*> Mask; |
| 12057 | if (isa<UndefValue>(VecOp)) |
| 12058 | Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty)); |
| 12059 | else { |
| 12060 | assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing"); |
| 12061 | Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty, |
| 12062 | NumVectorElts)); |
| 12063 | } |
| 12064 | Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx); |
| 12065 | return new ShuffleVectorInst(EI->getOperand(0), VecOp, |
| 12066 | ConstantVector::get(Mask)); |
| 12067 | } |
| 12068 | |
| 12069 | // If this insertelement isn't used by some other insertelement, turn it |
| 12070 | // (and any insertelements it points to), into one big shuffle. |
| 12071 | if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) { |
| 12072 | std::vector<Constant*> Mask; |
| 12073 | Value *RHS = 0; |
| 12074 | Value *LHS = CollectShuffleElements(&IE, Mask, RHS); |
| 12075 | if (RHS == 0) RHS = UndefValue::get(LHS->getType()); |
| 12076 | // We now have a shuffle of LHS, RHS, Mask. |
| 12077 | return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask)); |
| 12078 | } |
| 12079 | } |
| 12080 | } |
| 12081 | |
| 12082 | return 0; |
| 12083 | } |
| 12084 | |
| 12085 | |
| 12086 | Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { |
| 12087 | Value *LHS = SVI.getOperand(0); |
| 12088 | Value *RHS = SVI.getOperand(1); |
| 12089 | std::vector<unsigned> Mask = getShuffleMask(&SVI); |
| 12090 | |
| 12091 | bool MadeChange = false; |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 12092 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12093 | // Undefined shuffle mask -> undefined value. |
| 12094 | if (isa<UndefValue>(SVI.getOperand(2))) |
| 12095 | return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType())); |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 12096 | |
| 12097 | uint64_t UndefElts; |
| 12098 | unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements(); |
Mon P Wang | bff5d9c | 2008-11-10 04:46:22 +0000 | [diff] [blame] | 12099 | |
| 12100 | if (VWidth != cast<VectorType>(LHS->getType())->getNumElements()) |
| 12101 | return 0; |
| 12102 | |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 12103 | uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth); |
| 12104 | if (VWidth <= 64 && |
Dan Gohman | 83b702d | 2008-09-11 22:47:57 +0000 | [diff] [blame] | 12105 | SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { |
| 12106 | LHS = SVI.getOperand(0); |
| 12107 | RHS = SVI.getOperand(1); |
Dan Gohman | da93bbe | 2008-09-09 18:11:14 +0000 | [diff] [blame] | 12108 | MadeChange = true; |
Dan Gohman | 83b702d | 2008-09-11 22:47:57 +0000 | [diff] [blame] | 12109 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12110 | |
| 12111 | // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') |
| 12112 | // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). |
| 12113 | if (LHS == RHS || isa<UndefValue>(LHS)) { |
| 12114 | if (isa<UndefValue>(LHS) && LHS == RHS) { |
| 12115 | // shuffle(undef,undef,mask) -> undef. |
| 12116 | return ReplaceInstUsesWith(SVI, LHS); |
| 12117 | } |
| 12118 | |
| 12119 | // Remap any references to RHS to use LHS. |
| 12120 | std::vector<Constant*> Elts; |
| 12121 | for (unsigned i = 0, e = Mask.size(); i != e; ++i) { |
| 12122 | if (Mask[i] >= 2*e) |
| 12123 | Elts.push_back(UndefValue::get(Type::Int32Ty)); |
| 12124 | else { |
| 12125 | if ((Mask[i] >= e && isa<UndefValue>(RHS)) || |
Dan Gohman | bba96b9 | 2008-08-06 18:17:32 +0000 | [diff] [blame] | 12126 | (Mask[i] < e && isa<UndefValue>(LHS))) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12127 | Mask[i] = 2*e; // Turn into undef. |
Dan Gohman | bba96b9 | 2008-08-06 18:17:32 +0000 | [diff] [blame] | 12128 | Elts.push_back(UndefValue::get(Type::Int32Ty)); |
| 12129 | } else { |
Mon P Wang | 6bf3c59 | 2008-08-20 02:23:25 +0000 | [diff] [blame] | 12130 | Mask[i] = Mask[i] % e; // Force to LHS. |
Dan Gohman | bba96b9 | 2008-08-06 18:17:32 +0000 | [diff] [blame] | 12131 | Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i])); |
| 12132 | } |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12133 | } |
| 12134 | } |
| 12135 | SVI.setOperand(0, SVI.getOperand(1)); |
| 12136 | SVI.setOperand(1, UndefValue::get(RHS->getType())); |
| 12137 | SVI.setOperand(2, ConstantVector::get(Elts)); |
| 12138 | LHS = SVI.getOperand(0); |
| 12139 | RHS = SVI.getOperand(1); |
| 12140 | MadeChange = true; |
| 12141 | } |
| 12142 | |
| 12143 | // Analyze the shuffle, are the LHS or RHS and identity shuffles? |
| 12144 | bool isLHSID = true, isRHSID = true; |
| 12145 | |
| 12146 | for (unsigned i = 0, e = Mask.size(); i != e; ++i) { |
| 12147 | if (Mask[i] >= e*2) continue; // Ignore undef values. |
| 12148 | // Is this an identity shuffle of the LHS value? |
| 12149 | isLHSID &= (Mask[i] == i); |
| 12150 | |
| 12151 | // Is this an identity shuffle of the RHS value? |
| 12152 | isRHSID &= (Mask[i]-e == i); |
| 12153 | } |
| 12154 | |
| 12155 | // Eliminate identity shuffles. |
| 12156 | if (isLHSID) return ReplaceInstUsesWith(SVI, LHS); |
| 12157 | if (isRHSID) return ReplaceInstUsesWith(SVI, RHS); |
| 12158 | |
| 12159 | // If the LHS is a shufflevector itself, see if we can combine it with this |
| 12160 | // one without producing an unusual shuffle. Here we are really conservative: |
| 12161 | // we are absolutely afraid of producing a shuffle mask not in the input |
| 12162 | // program, because the code gen may not be smart enough to turn a merged |
| 12163 | // shuffle into two specific shuffles: it may produce worse code. As such, |
| 12164 | // we only merge two shuffles if the result is one of the two input shuffle |
| 12165 | // masks. In this case, merging the shuffles just removes one instruction, |
| 12166 | // which we know is safe. This is good for things like turning: |
| 12167 | // (splat(splat)) -> splat. |
| 12168 | if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) { |
| 12169 | if (isa<UndefValue>(RHS)) { |
| 12170 | std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI); |
| 12171 | |
| 12172 | std::vector<unsigned> NewMask; |
| 12173 | for (unsigned i = 0, e = Mask.size(); i != e; ++i) |
| 12174 | if (Mask[i] >= 2*e) |
| 12175 | NewMask.push_back(2*e); |
| 12176 | else |
| 12177 | NewMask.push_back(LHSMask[Mask[i]]); |
| 12178 | |
| 12179 | // If the result mask is equal to the src shuffle or this shuffle mask, do |
| 12180 | // the replacement. |
| 12181 | if (NewMask == LHSMask || NewMask == Mask) { |
wangmp | 496a76d | 2009-01-26 04:39:00 +0000 | [diff] [blame] | 12182 | unsigned LHSInNElts = |
| 12183 | cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12184 | std::vector<Constant*> Elts; |
| 12185 | for (unsigned i = 0, e = NewMask.size(); i != e; ++i) { |
wangmp | 496a76d | 2009-01-26 04:39:00 +0000 | [diff] [blame] | 12186 | if (NewMask[i] >= LHSInNElts*2) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12187 | Elts.push_back(UndefValue::get(Type::Int32Ty)); |
| 12188 | } else { |
| 12189 | Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i])); |
| 12190 | } |
| 12191 | } |
| 12192 | return new ShuffleVectorInst(LHSSVI->getOperand(0), |
| 12193 | LHSSVI->getOperand(1), |
| 12194 | ConstantVector::get(Elts)); |
| 12195 | } |
| 12196 | } |
| 12197 | } |
| 12198 | |
| 12199 | return MadeChange ? &SVI : 0; |
| 12200 | } |
| 12201 | |
| 12202 | |
| 12203 | |
| 12204 | |
| 12205 | /// TryToSinkInstruction - Try to move the specified instruction from its |
| 12206 | /// current block into the beginning of DestBlock, which can only happen if it's |
| 12207 | /// safe to move the instruction past all of the instructions between it and the |
| 12208 | /// end of its block. |
| 12209 | static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { |
| 12210 | assert(I->hasOneUse() && "Invariants didn't hold!"); |
| 12211 | |
| 12212 | // Cannot move control-flow-involving, volatile loads, vaarg, etc. |
Chris Lattner | cb19a1c | 2008-05-09 15:07:33 +0000 | [diff] [blame] | 12213 | if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I)) |
| 12214 | return false; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12215 | |
| 12216 | // Do not sink alloca instructions out of the entry block. |
| 12217 | if (isa<AllocaInst>(I) && I->getParent() == |
| 12218 | &DestBlock->getParent()->getEntryBlock()) |
| 12219 | return false; |
| 12220 | |
| 12221 | // We can only sink load instructions if there is nothing between the load and |
| 12222 | // the end of block that could change the value. |
Chris Lattner | 0db40a6 | 2008-05-08 17:37:37 +0000 | [diff] [blame] | 12223 | if (I->mayReadFromMemory()) { |
| 12224 | for (BasicBlock::iterator Scan = I, E = I->getParent()->end(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12225 | Scan != E; ++Scan) |
| 12226 | if (Scan->mayWriteToMemory()) |
| 12227 | return false; |
| 12228 | } |
| 12229 | |
Dan Gohman | 514277c | 2008-05-23 21:05:58 +0000 | [diff] [blame] | 12230 | BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12231 | |
| 12232 | I->moveBefore(InsertPos); |
| 12233 | ++NumSunkInst; |
| 12234 | return true; |
| 12235 | } |
| 12236 | |
| 12237 | |
| 12238 | /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding |
| 12239 | /// all reachable code to the worklist. |
| 12240 | /// |
| 12241 | /// This has a couple of tricks to make the code faster and more powerful. In |
| 12242 | /// particular, we constant fold and DCE instructions as we go, to avoid adding |
| 12243 | /// them to the worklist (this significantly speeds up instcombine on code where |
| 12244 | /// many instructions are dead or constant). Additionally, if we find a branch |
| 12245 | /// whose condition is a known constant, we only visit the reachable successors. |
| 12246 | /// |
| 12247 | static void AddReachableCodeToWorklist(BasicBlock *BB, |
| 12248 | SmallPtrSet<BasicBlock*, 64> &Visited, |
| 12249 | InstCombiner &IC, |
| 12250 | const TargetData *TD) { |
Chris Lattner | a06291a | 2008-08-15 04:03:01 +0000 | [diff] [blame] | 12251 | SmallVector<BasicBlock*, 256> Worklist; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12252 | Worklist.push_back(BB); |
| 12253 | |
| 12254 | while (!Worklist.empty()) { |
| 12255 | BB = Worklist.back(); |
| 12256 | Worklist.pop_back(); |
| 12257 | |
| 12258 | // We have now visited this block! If we've already been here, ignore it. |
| 12259 | if (!Visited.insert(BB)) continue; |
Devang Patel | 794140c | 2008-11-19 18:56:50 +0000 | [diff] [blame] | 12260 | |
| 12261 | DbgInfoIntrinsic *DBI_Prev = NULL; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12262 | for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { |
| 12263 | Instruction *Inst = BBI++; |
| 12264 | |
| 12265 | // DCE instruction if trivially dead. |
| 12266 | if (isInstructionTriviallyDead(Inst)) { |
| 12267 | ++NumDeadInst; |
| 12268 | DOUT << "IC: DCE: " << *Inst; |
| 12269 | Inst->eraseFromParent(); |
| 12270 | continue; |
| 12271 | } |
| 12272 | |
| 12273 | // ConstantProp instruction if trivially constant. |
| 12274 | if (Constant *C = ConstantFoldInstruction(Inst, TD)) { |
| 12275 | DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst; |
| 12276 | Inst->replaceAllUsesWith(C); |
| 12277 | ++NumConstProp; |
| 12278 | Inst->eraseFromParent(); |
| 12279 | continue; |
| 12280 | } |
Chris Lattner | e0f462d | 2007-07-20 22:06:41 +0000 | [diff] [blame] | 12281 | |
Devang Patel | 794140c | 2008-11-19 18:56:50 +0000 | [diff] [blame] | 12282 | // If there are two consecutive llvm.dbg.stoppoint calls then |
| 12283 | // it is likely that the optimizer deleted code in between these |
| 12284 | // two intrinsics. |
| 12285 | DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst); |
| 12286 | if (DBI_Next) { |
| 12287 | if (DBI_Prev |
| 12288 | && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint |
| 12289 | && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) { |
| 12290 | IC.RemoveFromWorkList(DBI_Prev); |
| 12291 | DBI_Prev->eraseFromParent(); |
| 12292 | } |
| 12293 | DBI_Prev = DBI_Next; |
| 12294 | } |
| 12295 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12296 | IC.AddToWorkList(Inst); |
| 12297 | } |
| 12298 | |
| 12299 | // Recursively visit successors. If this is a branch or switch on a |
| 12300 | // constant, only visit the reachable successor. |
| 12301 | TerminatorInst *TI = BB->getTerminator(); |
| 12302 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 12303 | if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { |
| 12304 | bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); |
Nick Lewycky | d551cf1 | 2008-03-09 08:50:23 +0000 | [diff] [blame] | 12305 | BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); |
Nick Lewycky | d8aa33a | 2008-04-25 16:53:59 +0000 | [diff] [blame] | 12306 | Worklist.push_back(ReachableBB); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12307 | continue; |
| 12308 | } |
| 12309 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 12310 | if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { |
| 12311 | // See if this is an explicit destination. |
| 12312 | for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) |
| 12313 | if (SI->getCaseValue(i) == Cond) { |
Nick Lewycky | d551cf1 | 2008-03-09 08:50:23 +0000 | [diff] [blame] | 12314 | BasicBlock *ReachableBB = SI->getSuccessor(i); |
Nick Lewycky | d8aa33a | 2008-04-25 16:53:59 +0000 | [diff] [blame] | 12315 | Worklist.push_back(ReachableBB); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12316 | continue; |
| 12317 | } |
| 12318 | |
| 12319 | // Otherwise it is the default destination. |
| 12320 | Worklist.push_back(SI->getSuccessor(0)); |
| 12321 | continue; |
| 12322 | } |
| 12323 | } |
| 12324 | |
| 12325 | for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) |
| 12326 | Worklist.push_back(TI->getSuccessor(i)); |
| 12327 | } |
| 12328 | } |
| 12329 | |
| 12330 | bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) { |
| 12331 | bool Changed = false; |
| 12332 | TD = &getAnalysis<TargetData>(); |
| 12333 | |
| 12334 | DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " |
| 12335 | << F.getNameStr() << "\n"); |
| 12336 | |
| 12337 | { |
| 12338 | // Do a depth-first traversal of the function, populate the worklist with |
| 12339 | // the reachable instructions. Ignore blocks that are not reachable. Keep |
| 12340 | // track of which blocks we visit. |
| 12341 | SmallPtrSet<BasicBlock*, 64> Visited; |
| 12342 | AddReachableCodeToWorklist(F.begin(), Visited, *this, TD); |
| 12343 | |
| 12344 | // Do a quick scan over the function. If we find any blocks that are |
| 12345 | // unreachable, remove any instructions inside of them. This prevents |
| 12346 | // the instcombine code from having to deal with some bad special cases. |
| 12347 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) |
| 12348 | if (!Visited.count(BB)) { |
| 12349 | Instruction *Term = BB->getTerminator(); |
| 12350 | while (Term != BB->begin()) { // Remove instrs bottom-up |
| 12351 | BasicBlock::iterator I = Term; --I; |
| 12352 | |
| 12353 | DOUT << "IC: DCE: " << *I; |
| 12354 | ++NumDeadInst; |
| 12355 | |
| 12356 | if (!I->use_empty()) |
| 12357 | I->replaceAllUsesWith(UndefValue::get(I->getType())); |
| 12358 | I->eraseFromParent(); |
Chris Lattner | f6d5886 | 2009-01-31 07:04:22 +0000 | [diff] [blame] | 12359 | Changed = true; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12360 | } |
| 12361 | } |
| 12362 | } |
| 12363 | |
| 12364 | while (!Worklist.empty()) { |
| 12365 | Instruction *I = RemoveOneFromWorkList(); |
| 12366 | if (I == 0) continue; // skip null values. |
| 12367 | |
| 12368 | // Check to see if we can DCE the instruction. |
| 12369 | if (isInstructionTriviallyDead(I)) { |
| 12370 | // Add operands to the worklist. |
| 12371 | if (I->getNumOperands() < 4) |
| 12372 | AddUsesToWorkList(*I); |
| 12373 | ++NumDeadInst; |
| 12374 | |
| 12375 | DOUT << "IC: DCE: " << *I; |
| 12376 | |
| 12377 | I->eraseFromParent(); |
| 12378 | RemoveFromWorkList(I); |
Chris Lattner | f6d5886 | 2009-01-31 07:04:22 +0000 | [diff] [blame] | 12379 | Changed = true; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12380 | continue; |
| 12381 | } |
| 12382 | |
| 12383 | // Instruction isn't dead, see if we can constant propagate it. |
| 12384 | if (Constant *C = ConstantFoldInstruction(I, TD)) { |
| 12385 | DOUT << "IC: ConstFold to: " << *C << " from: " << *I; |
| 12386 | |
| 12387 | // Add operands to the worklist. |
| 12388 | AddUsesToWorkList(*I); |
| 12389 | ReplaceInstUsesWith(*I, C); |
| 12390 | |
| 12391 | ++NumConstProp; |
| 12392 | I->eraseFromParent(); |
| 12393 | RemoveFromWorkList(I); |
Chris Lattner | f6d5886 | 2009-01-31 07:04:22 +0000 | [diff] [blame] | 12394 | Changed = true; |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12395 | continue; |
| 12396 | } |
| 12397 | |
Nick Lewycky | adb6792 | 2008-05-25 20:56:15 +0000 | [diff] [blame] | 12398 | if (TD && I->getType()->getTypeID() == Type::VoidTyID) { |
| 12399 | // See if we can constant fold its operands. |
Chris Lattner | f6d5886 | 2009-01-31 07:04:22 +0000 | [diff] [blame] | 12400 | for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) |
| 12401 | if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) |
Nick Lewycky | adb6792 | 2008-05-25 20:56:15 +0000 | [diff] [blame] | 12402 | if (Constant *NewC = ConstantFoldConstantExpression(CE, TD)) |
Chris Lattner | f6d5886 | 2009-01-31 07:04:22 +0000 | [diff] [blame] | 12403 | if (NewC != CE) { |
| 12404 | i->set(NewC); |
| 12405 | Changed = true; |
| 12406 | } |
Nick Lewycky | adb6792 | 2008-05-25 20:56:15 +0000 | [diff] [blame] | 12407 | } |
| 12408 | |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12409 | // See if we can trivially sink this instruction to a successor basic block. |
Dan Gohman | 29474e9 | 2008-07-23 00:34:11 +0000 | [diff] [blame] | 12410 | if (I->hasOneUse()) { |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12411 | BasicBlock *BB = I->getParent(); |
| 12412 | BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent(); |
| 12413 | if (UserParent != BB) { |
| 12414 | bool UserIsSuccessor = false; |
| 12415 | // See if the user is one of our successors. |
| 12416 | for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) |
| 12417 | if (*SI == UserParent) { |
| 12418 | UserIsSuccessor = true; |
| 12419 | break; |
| 12420 | } |
| 12421 | |
| 12422 | // If the user is one of our immediate successors, and if that successor |
| 12423 | // only has us as a predecessors (we'd have to split the critical edge |
| 12424 | // otherwise), we can keep going. |
| 12425 | if (UserIsSuccessor && !isa<PHINode>(I->use_back()) && |
| 12426 | next(pred_begin(UserParent)) == pred_end(UserParent)) |
| 12427 | // Okay, the CFG is simple enough, try to sink this instruction. |
| 12428 | Changed |= TryToSinkInstruction(I, UserParent); |
| 12429 | } |
| 12430 | } |
| 12431 | |
| 12432 | // Now that we have an instruction, try combining it to simplify it... |
| 12433 | #ifndef NDEBUG |
| 12434 | std::string OrigI; |
| 12435 | #endif |
| 12436 | DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str();); |
| 12437 | if (Instruction *Result = visit(*I)) { |
| 12438 | ++NumCombined; |
| 12439 | // Should we replace the old instruction with a new one? |
| 12440 | if (Result != I) { |
| 12441 | DOUT << "IC: Old = " << *I |
| 12442 | << " New = " << *Result; |
| 12443 | |
| 12444 | // Everything uses the new instruction now. |
| 12445 | I->replaceAllUsesWith(Result); |
| 12446 | |
| 12447 | // Push the new instruction and any users onto the worklist. |
| 12448 | AddToWorkList(Result); |
| 12449 | AddUsersToWorkList(*Result); |
| 12450 | |
| 12451 | // Move the name to the new instruction first. |
| 12452 | Result->takeName(I); |
| 12453 | |
| 12454 | // Insert the new instruction into the basic block... |
| 12455 | BasicBlock *InstParent = I->getParent(); |
| 12456 | BasicBlock::iterator InsertPos = I; |
| 12457 | |
| 12458 | if (!isa<PHINode>(Result)) // If combining a PHI, don't insert |
| 12459 | while (isa<PHINode>(InsertPos)) // middle of a block of PHIs. |
| 12460 | ++InsertPos; |
| 12461 | |
| 12462 | InstParent->getInstList().insert(InsertPos, Result); |
| 12463 | |
| 12464 | // Make sure that we reprocess all operands now that we reduced their |
| 12465 | // use counts. |
| 12466 | AddUsesToWorkList(*I); |
| 12467 | |
| 12468 | // Instructions can end up on the worklist more than once. Make sure |
| 12469 | // we do not process an instruction that has been deleted. |
| 12470 | RemoveFromWorkList(I); |
| 12471 | |
| 12472 | // Erase the old instruction. |
| 12473 | InstParent->getInstList().erase(I); |
| 12474 | } else { |
| 12475 | #ifndef NDEBUG |
| 12476 | DOUT << "IC: Mod = " << OrigI |
| 12477 | << " New = " << *I; |
| 12478 | #endif |
| 12479 | |
| 12480 | // If the instruction was modified, it's possible that it is now dead. |
| 12481 | // if so, remove it. |
| 12482 | if (isInstructionTriviallyDead(I)) { |
| 12483 | // Make sure we process all operands now that we are reducing their |
| 12484 | // use counts. |
| 12485 | AddUsesToWorkList(*I); |
| 12486 | |
| 12487 | // Instructions may end up in the worklist more than once. Erase all |
| 12488 | // occurrences of this instruction. |
| 12489 | RemoveFromWorkList(I); |
| 12490 | I->eraseFromParent(); |
| 12491 | } else { |
| 12492 | AddToWorkList(I); |
| 12493 | AddUsersToWorkList(*I); |
| 12494 | } |
| 12495 | } |
| 12496 | Changed = true; |
| 12497 | } |
| 12498 | } |
| 12499 | |
| 12500 | assert(WorklistMap.empty() && "Worklist empty, but map not?"); |
Chris Lattner | b933ea6 | 2007-08-05 08:47:58 +0000 | [diff] [blame] | 12501 | |
| 12502 | // Do an explicit clear, this shrinks the map if needed. |
| 12503 | WorklistMap.clear(); |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12504 | return Changed; |
| 12505 | } |
| 12506 | |
| 12507 | |
| 12508 | bool InstCombiner::runOnFunction(Function &F) { |
| 12509 | MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID); |
| 12510 | |
| 12511 | bool EverMadeChange = false; |
| 12512 | |
| 12513 | // Iterate while there is work to do. |
| 12514 | unsigned Iteration = 0; |
Bill Wendling | d9644a4 | 2008-05-14 22:45:20 +0000 | [diff] [blame] | 12515 | while (DoOneIteration(F, Iteration++)) |
Dan Gohman | f17a25c | 2007-07-18 16:29:46 +0000 | [diff] [blame] | 12516 | EverMadeChange = true; |
| 12517 | return EverMadeChange; |
| 12518 | } |
| 12519 | |
| 12520 | FunctionPass *llvm::createInstructionCombiningPass() { |
| 12521 | return new InstCombiner(); |
| 12522 | } |