LLVM API Documentation
00001 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements routines for folding instructions into simpler forms 00011 // that do not require creating new instructions. This does constant folding 00012 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 00013 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 00014 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 00015 // simplified: This is usually true and assuming it simplifies the logic (if 00016 // they have not been simplified then results are correct but maybe suboptimal). 00017 // 00018 //===----------------------------------------------------------------------===// 00019 00020 #define DEBUG_TYPE "instsimplify" 00021 #include "llvm/Analysis/InstructionSimplify.h" 00022 #include "llvm/ADT/SetVector.h" 00023 #include "llvm/ADT/Statistic.h" 00024 #include "llvm/Analysis/ConstantFolding.h" 00025 #include "llvm/Analysis/Dominators.h" 00026 #include "llvm/Analysis/ValueTracking.h" 00027 #include "llvm/Analysis/MemoryBuiltins.h" 00028 #include "llvm/IR/DataLayout.h" 00029 #include "llvm/IR/GlobalAlias.h" 00030 #include "llvm/IR/Operator.h" 00031 #include "llvm/Support/ConstantRange.h" 00032 #include "llvm/Support/GetElementPtrTypeIterator.h" 00033 #include "llvm/Support/PatternMatch.h" 00034 #include "llvm/Support/ValueHandle.h" 00035 using namespace llvm; 00036 using namespace llvm::PatternMatch; 00037 00038 enum { RecursionLimit = 3 }; 00039 00040 STATISTIC(NumExpand, "Number of expansions"); 00041 STATISTIC(NumFactor , "Number of factorizations"); 00042 STATISTIC(NumReassoc, "Number of reassociations"); 00043 00044 struct Query { 00045 const DataLayout *TD; 00046 const TargetLibraryInfo *TLI; 00047 const DominatorTree *DT; 00048 00049 Query(const DataLayout *td, const TargetLibraryInfo *tli, 00050 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {} 00051 }; 00052 00053 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned); 00054 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &, 00055 unsigned); 00056 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &, 00057 unsigned); 00058 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned); 00059 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned); 00060 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned); 00061 00062 /// getFalse - For a boolean type, or a vector of boolean type, return false, or 00063 /// a vector with every element false, as appropriate for the type. 00064 static Constant *getFalse(Type *Ty) { 00065 assert(Ty->getScalarType()->isIntegerTy(1) && 00066 "Expected i1 type or a vector of i1!"); 00067 return Constant::getNullValue(Ty); 00068 } 00069 00070 /// getTrue - For a boolean type, or a vector of boolean type, return true, or 00071 /// a vector with every element true, as appropriate for the type. 00072 static Constant *getTrue(Type *Ty) { 00073 assert(Ty->getScalarType()->isIntegerTy(1) && 00074 "Expected i1 type or a vector of i1!"); 00075 return Constant::getAllOnesValue(Ty); 00076 } 00077 00078 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 00079 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 00080 Value *RHS) { 00081 CmpInst *Cmp = dyn_cast<CmpInst>(V); 00082 if (!Cmp) 00083 return false; 00084 CmpInst::Predicate CPred = Cmp->getPredicate(); 00085 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 00086 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 00087 return true; 00088 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 00089 CRHS == LHS; 00090 } 00091 00092 /// ValueDominatesPHI - Does the given value dominate the specified phi node? 00093 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 00094 Instruction *I = dyn_cast<Instruction>(V); 00095 if (!I) 00096 // Arguments and constants dominate all instructions. 00097 return true; 00098 00099 // If we are processing instructions (and/or basic blocks) that have not been 00100 // fully added to a function, the parent nodes may still be null. Simply 00101 // return the conservative answer in these cases. 00102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent()) 00103 return false; 00104 00105 // If we have a DominatorTree then do a precise test. 00106 if (DT) { 00107 if (!DT->isReachableFromEntry(P->getParent())) 00108 return true; 00109 if (!DT->isReachableFromEntry(I->getParent())) 00110 return false; 00111 return DT->dominates(I, P); 00112 } 00113 00114 // Otherwise, if the instruction is in the entry block, and is not an invoke, 00115 // then it obviously dominates all phi nodes. 00116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() && 00117 !isa<InvokeInst>(I)) 00118 return true; 00119 00120 return false; 00121 } 00122 00123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning 00124 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is 00125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS. 00126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)". 00127 /// Returns the simplified value, or null if no simplification was performed. 00128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS, 00129 unsigned OpcToExpand, const Query &Q, 00130 unsigned MaxRecurse) { 00131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand; 00132 // Recursion is always used, so bail out at once if we already hit the limit. 00133 if (!MaxRecurse--) 00134 return 0; 00135 00136 // Check whether the expression has the form "(A op' B) op C". 00137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) 00138 if (Op0->getOpcode() == OpcodeToExpand) { 00139 // It does! Try turning it into "(A op C) op' (B op C)". 00140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 00141 // Do "A op C" and "B op C" both simplify? 00142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) 00143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 00144 // They do! Return "L op' R" if it simplifies or is already available. 00145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. 00146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand) 00147 && L == B && R == A)) { 00148 ++NumExpand; 00149 return LHS; 00150 } 00151 // Otherwise return "L op' R" if it simplifies. 00152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 00153 ++NumExpand; 00154 return V; 00155 } 00156 } 00157 } 00158 00159 // Check whether the expression has the form "A op (B op' C)". 00160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) 00161 if (Op1->getOpcode() == OpcodeToExpand) { 00162 // It does! Try turning it into "(A op B) op' (A op C)". 00163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 00164 // Do "A op B" and "A op C" both simplify? 00165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) 00166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) { 00167 // They do! Return "L op' R" if it simplifies or is already available. 00168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. 00169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand) 00170 && L == C && R == B)) { 00171 ++NumExpand; 00172 return RHS; 00173 } 00174 // Otherwise return "L op' R" if it simplifies. 00175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 00176 ++NumExpand; 00177 return V; 00178 } 00179 } 00180 } 00181 00182 return 0; 00183 } 00184 00185 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term 00186 /// using the operation OpCodeToExtract. For example, when Opcode is Add and 00187 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)". 00188 /// Returns the simplified value, or null if no simplification was performed. 00189 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS, 00190 unsigned OpcToExtract, const Query &Q, 00191 unsigned MaxRecurse) { 00192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract; 00193 // Recursion is always used, so bail out at once if we already hit the limit. 00194 if (!MaxRecurse--) 00195 return 0; 00196 00197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 00198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 00199 00200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract || 00201 !Op1 || Op1->getOpcode() != OpcodeToExtract) 00202 return 0; 00203 00204 // The expression has the form "(A op' B) op (C op' D)". 00205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1); 00206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1); 00207 00208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)". 00209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 00210 // commutative case, "(A op' B) op (C op' A)"? 00211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) { 00212 Value *DD = A == C ? D : C; 00213 // Form "A op' (B op DD)" if it simplifies completely. 00214 // Does "B op DD" simplify? 00215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) { 00216 // It does! Return "A op' V" if it simplifies or is already available. 00217 // If V equals B then "A op' V" is just the LHS. If V equals DD then 00218 // "A op' V" is just the RHS. 00219 if (V == B || V == DD) { 00220 ++NumFactor; 00221 return V == B ? LHS : RHS; 00222 } 00223 // Otherwise return "A op' V" if it simplifies. 00224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) { 00225 ++NumFactor; 00226 return W; 00227 } 00228 } 00229 } 00230 00231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)". 00232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 00233 // commutative case, "(A op' B) op (B op' D)"? 00234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) { 00235 Value *CC = B == D ? C : D; 00236 // Form "(A op CC) op' B" if it simplifies completely.. 00237 // Does "A op CC" simplify? 00238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) { 00239 // It does! Return "V op' B" if it simplifies or is already available. 00240 // If V equals A then "V op' B" is just the LHS. If V equals CC then 00241 // "V op' B" is just the RHS. 00242 if (V == A || V == CC) { 00243 ++NumFactor; 00244 return V == A ? LHS : RHS; 00245 } 00246 // Otherwise return "V op' B" if it simplifies. 00247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) { 00248 ++NumFactor; 00249 return W; 00250 } 00251 } 00252 } 00253 00254 return 0; 00255 } 00256 00257 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary 00258 /// operations. Returns the simpler value, or null if none was found. 00259 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS, 00260 const Query &Q, unsigned MaxRecurse) { 00261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc; 00262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 00263 00264 // Recursion is always used, so bail out at once if we already hit the limit. 00265 if (!MaxRecurse--) 00266 return 0; 00267 00268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 00269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 00270 00271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 00272 if (Op0 && Op0->getOpcode() == Opcode) { 00273 Value *A = Op0->getOperand(0); 00274 Value *B = Op0->getOperand(1); 00275 Value *C = RHS; 00276 00277 // Does "B op C" simplify? 00278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 00279 // It does! Return "A op V" if it simplifies or is already available. 00280 // If V equals B then "A op V" is just the LHS. 00281 if (V == B) return LHS; 00282 // Otherwise return "A op V" if it simplifies. 00283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 00284 ++NumReassoc; 00285 return W; 00286 } 00287 } 00288 } 00289 00290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 00291 if (Op1 && Op1->getOpcode() == Opcode) { 00292 Value *A = LHS; 00293 Value *B = Op1->getOperand(0); 00294 Value *C = Op1->getOperand(1); 00295 00296 // Does "A op B" simplify? 00297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 00298 // It does! Return "V op C" if it simplifies or is already available. 00299 // If V equals B then "V op C" is just the RHS. 00300 if (V == B) return RHS; 00301 // Otherwise return "V op C" if it simplifies. 00302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 00303 ++NumReassoc; 00304 return W; 00305 } 00306 } 00307 } 00308 00309 // The remaining transforms require commutativity as well as associativity. 00310 if (!Instruction::isCommutative(Opcode)) 00311 return 0; 00312 00313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 00314 if (Op0 && Op0->getOpcode() == Opcode) { 00315 Value *A = Op0->getOperand(0); 00316 Value *B = Op0->getOperand(1); 00317 Value *C = RHS; 00318 00319 // Does "C op A" simplify? 00320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 00321 // It does! Return "V op B" if it simplifies or is already available. 00322 // If V equals A then "V op B" is just the LHS. 00323 if (V == A) return LHS; 00324 // Otherwise return "V op B" if it simplifies. 00325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 00326 ++NumReassoc; 00327 return W; 00328 } 00329 } 00330 } 00331 00332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 00333 if (Op1 && Op1->getOpcode() == Opcode) { 00334 Value *A = LHS; 00335 Value *B = Op1->getOperand(0); 00336 Value *C = Op1->getOperand(1); 00337 00338 // Does "C op A" simplify? 00339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 00340 // It does! Return "B op V" if it simplifies or is already available. 00341 // If V equals C then "B op V" is just the RHS. 00342 if (V == C) return RHS; 00343 // Otherwise return "B op V" if it simplifies. 00344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 00345 ++NumReassoc; 00346 return W; 00347 } 00348 } 00349 } 00350 00351 return 0; 00352 } 00353 00354 /// ThreadBinOpOverSelect - In the case of a binary operation with a select 00355 /// instruction as an operand, try to simplify the binop by seeing whether 00356 /// evaluating it on both branches of the select results in the same value. 00357 /// Returns the common value if so, otherwise returns null. 00358 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS, 00359 const Query &Q, unsigned MaxRecurse) { 00360 // Recursion is always used, so bail out at once if we already hit the limit. 00361 if (!MaxRecurse--) 00362 return 0; 00363 00364 SelectInst *SI; 00365 if (isa<SelectInst>(LHS)) { 00366 SI = cast<SelectInst>(LHS); 00367 } else { 00368 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 00369 SI = cast<SelectInst>(RHS); 00370 } 00371 00372 // Evaluate the BinOp on the true and false branches of the select. 00373 Value *TV; 00374 Value *FV; 00375 if (SI == LHS) { 00376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 00377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 00378 } else { 00379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 00380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 00381 } 00382 00383 // If they simplified to the same value, then return the common value. 00384 // If they both failed to simplify then return null. 00385 if (TV == FV) 00386 return TV; 00387 00388 // If one branch simplified to undef, return the other one. 00389 if (TV && isa<UndefValue>(TV)) 00390 return FV; 00391 if (FV && isa<UndefValue>(FV)) 00392 return TV; 00393 00394 // If applying the operation did not change the true and false select values, 00395 // then the result of the binop is the select itself. 00396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 00397 return SI; 00398 00399 // If one branch simplified and the other did not, and the simplified 00400 // value is equal to the unsimplified one, return the simplified value. 00401 // For example, select (cond, X, X & Z) & Z -> X & Z. 00402 if ((FV && !TV) || (TV && !FV)) { 00403 // Check that the simplified value has the form "X op Y" where "op" is the 00404 // same as the original operation. 00405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 00406 if (Simplified && Simplified->getOpcode() == Opcode) { 00407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 00408 // We already know that "op" is the same as for the simplified value. See 00409 // if the operands match too. If so, return the simplified value. 00410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 00411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 00412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 00413 if (Simplified->getOperand(0) == UnsimplifiedLHS && 00414 Simplified->getOperand(1) == UnsimplifiedRHS) 00415 return Simplified; 00416 if (Simplified->isCommutative() && 00417 Simplified->getOperand(1) == UnsimplifiedLHS && 00418 Simplified->getOperand(0) == UnsimplifiedRHS) 00419 return Simplified; 00420 } 00421 } 00422 00423 return 0; 00424 } 00425 00426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction, 00427 /// try to simplify the comparison by seeing whether both branches of the select 00428 /// result in the same value. Returns the common value if so, otherwise returns 00429 /// null. 00430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 00431 Value *RHS, const Query &Q, 00432 unsigned MaxRecurse) { 00433 // Recursion is always used, so bail out at once if we already hit the limit. 00434 if (!MaxRecurse--) 00435 return 0; 00436 00437 // Make sure the select is on the LHS. 00438 if (!isa<SelectInst>(LHS)) { 00439 std::swap(LHS, RHS); 00440 Pred = CmpInst::getSwappedPredicate(Pred); 00441 } 00442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 00443 SelectInst *SI = cast<SelectInst>(LHS); 00444 Value *Cond = SI->getCondition(); 00445 Value *TV = SI->getTrueValue(); 00446 Value *FV = SI->getFalseValue(); 00447 00448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 00449 // Does "cmp TV, RHS" simplify? 00450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse); 00451 if (TCmp == Cond) { 00452 // It not only simplified, it simplified to the select condition. Replace 00453 // it with 'true'. 00454 TCmp = getTrue(Cond->getType()); 00455 } else if (!TCmp) { 00456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select 00457 // condition then we can replace it with 'true'. Otherwise give up. 00458 if (!isSameCompare(Cond, Pred, TV, RHS)) 00459 return 0; 00460 TCmp = getTrue(Cond->getType()); 00461 } 00462 00463 // Does "cmp FV, RHS" simplify? 00464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse); 00465 if (FCmp == Cond) { 00466 // It not only simplified, it simplified to the select condition. Replace 00467 // it with 'false'. 00468 FCmp = getFalse(Cond->getType()); 00469 } else if (!FCmp) { 00470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select 00471 // condition then we can replace it with 'false'. Otherwise give up. 00472 if (!isSameCompare(Cond, Pred, FV, RHS)) 00473 return 0; 00474 FCmp = getFalse(Cond->getType()); 00475 } 00476 00477 // If both sides simplified to the same value, then use it as the result of 00478 // the original comparison. 00479 if (TCmp == FCmp) 00480 return TCmp; 00481 00482 // The remaining cases only make sense if the select condition has the same 00483 // type as the result of the comparison, so bail out if this is not so. 00484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy()) 00485 return 0; 00486 // If the false value simplified to false, then the result of the compare 00487 // is equal to "Cond && TCmp". This also catches the case when the false 00488 // value simplified to false and the true value to true, returning "Cond". 00489 if (match(FCmp, m_Zero())) 00490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 00491 return V; 00492 // If the true value simplified to true, then the result of the compare 00493 // is equal to "Cond || FCmp". 00494 if (match(TCmp, m_One())) 00495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 00496 return V; 00497 // Finally, if the false value simplified to true and the true value to 00498 // false, then the result of the compare is equal to "!Cond". 00499 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 00500 if (Value *V = 00501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()), 00502 Q, MaxRecurse)) 00503 return V; 00504 00505 return 0; 00506 } 00507 00508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that 00509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating 00510 /// it on the incoming phi values yields the same result for every value. If so 00511 /// returns the common value, otherwise returns null. 00512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS, 00513 const Query &Q, unsigned MaxRecurse) { 00514 // Recursion is always used, so bail out at once if we already hit the limit. 00515 if (!MaxRecurse--) 00516 return 0; 00517 00518 PHINode *PI; 00519 if (isa<PHINode>(LHS)) { 00520 PI = cast<PHINode>(LHS); 00521 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 00522 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 00523 return 0; 00524 } else { 00525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 00526 PI = cast<PHINode>(RHS); 00527 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 00528 if (!ValueDominatesPHI(LHS, PI, Q.DT)) 00529 return 0; 00530 } 00531 00532 // Evaluate the BinOp on the incoming phi values. 00533 Value *CommonValue = 0; 00534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 00535 Value *Incoming = PI->getIncomingValue(i); 00536 // If the incoming value is the phi node itself, it can safely be skipped. 00537 if (Incoming == PI) continue; 00538 Value *V = PI == LHS ? 00539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 00540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 00541 // If the operation failed to simplify, or simplified to a different value 00542 // to previously, then give up. 00543 if (!V || (CommonValue && V != CommonValue)) 00544 return 0; 00545 CommonValue = V; 00546 } 00547 00548 return CommonValue; 00549 } 00550 00551 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try 00552 /// try to simplify the comparison by seeing whether comparing with all of the 00553 /// incoming phi values yields the same result every time. If so returns the 00554 /// common result, otherwise returns null. 00555 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 00556 const Query &Q, unsigned MaxRecurse) { 00557 // Recursion is always used, so bail out at once if we already hit the limit. 00558 if (!MaxRecurse--) 00559 return 0; 00560 00561 // Make sure the phi is on the LHS. 00562 if (!isa<PHINode>(LHS)) { 00563 std::swap(LHS, RHS); 00564 Pred = CmpInst::getSwappedPredicate(Pred); 00565 } 00566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 00567 PHINode *PI = cast<PHINode>(LHS); 00568 00569 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 00570 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 00571 return 0; 00572 00573 // Evaluate the BinOp on the incoming phi values. 00574 Value *CommonValue = 0; 00575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 00576 Value *Incoming = PI->getIncomingValue(i); 00577 // If the incoming value is the phi node itself, it can safely be skipped. 00578 if (Incoming == PI) continue; 00579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse); 00580 // If the operation failed to simplify, or simplified to a different value 00581 // to previously, then give up. 00582 if (!V || (CommonValue && V != CommonValue)) 00583 return 0; 00584 CommonValue = V; 00585 } 00586 00587 return CommonValue; 00588 } 00589 00590 /// SimplifyAddInst - Given operands for an Add, see if we can 00591 /// fold the result. If not, this returns null. 00592 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 00593 const Query &Q, unsigned MaxRecurse) { 00594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 00595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00596 Constant *Ops[] = { CLHS, CRHS }; 00597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops, 00598 Q.TD, Q.TLI); 00599 } 00600 00601 // Canonicalize the constant to the RHS. 00602 std::swap(Op0, Op1); 00603 } 00604 00605 // X + undef -> undef 00606 if (match(Op1, m_Undef())) 00607 return Op1; 00608 00609 // X + 0 -> X 00610 if (match(Op1, m_Zero())) 00611 return Op0; 00612 00613 // X + (Y - X) -> Y 00614 // (Y - X) + X -> Y 00615 // Eg: X + -X -> 0 00616 Value *Y = 0; 00617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 00618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 00619 return Y; 00620 00621 // X + ~X -> -1 since ~X = -X-1 00622 if (match(Op0, m_Not(m_Specific(Op1))) || 00623 match(Op1, m_Not(m_Specific(Op0)))) 00624 return Constant::getAllOnesValue(Op0->getType()); 00625 00626 /// i1 add -> xor. 00627 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 00628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 00629 return V; 00630 00631 // Try some generic simplifications for associative operations. 00632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 00633 MaxRecurse)) 00634 return V; 00635 00636 // Mul distributes over Add. Try some generic simplifications based on this. 00637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul, 00638 Q, MaxRecurse)) 00639 return V; 00640 00641 // Threading Add over selects and phi nodes is pointless, so don't bother. 00642 // Threading over the select in "A + select(cond, B, C)" means evaluating 00643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 00644 // only if B and C are equal. If B and C are equal then (since we assume 00645 // that operands have already been simplified) "select(cond, B, C)" should 00646 // have been simplified to the common value of B and C already. Analysing 00647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 00648 // for threading over phi nodes. 00649 00650 return 0; 00651 } 00652 00653 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 00654 const DataLayout *TD, const TargetLibraryInfo *TLI, 00655 const DominatorTree *DT) { 00656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT), 00657 RecursionLimit); 00658 } 00659 00660 /// \brief Compute the base pointer and cumulative constant offsets for V. 00661 /// 00662 /// This strips all constant offsets off of V, leaving it the base pointer, and 00663 /// accumulates the total constant offset applied in the returned constant. It 00664 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 00665 /// no constant offsets applied. 00666 /// 00667 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 00668 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 00669 /// folding. 00670 static Constant *stripAndComputeConstantOffsets(const DataLayout *TD, 00671 Value *&V) { 00672 assert(V->getType()->getScalarType()->isPointerTy()); 00673 00674 // Without DataLayout, just be conservative for now. Theoretically, more could 00675 // be done in this case. 00676 if (!TD) 00677 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0); 00678 00679 unsigned IntPtrWidth = TD->getPointerSizeInBits(); 00680 APInt Offset = APInt::getNullValue(IntPtrWidth); 00681 00682 // Even though we don't look through PHI nodes, we could be called on an 00683 // instruction in an unreachable block, which may be on a cycle. 00684 SmallPtrSet<Value *, 4> Visited; 00685 Visited.insert(V); 00686 do { 00687 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 00688 if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(*TD, Offset)) 00689 break; 00690 V = GEP->getPointerOperand(); 00691 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 00692 V = cast<Operator>(V)->getOperand(0); 00693 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 00694 if (GA->mayBeOverridden()) 00695 break; 00696 V = GA->getAliasee(); 00697 } else { 00698 break; 00699 } 00700 assert(V->getType()->getScalarType()->isPointerTy() && 00701 "Unexpected operand type!"); 00702 } while (Visited.insert(V)); 00703 00704 Type *IntPtrTy = TD->getIntPtrType(V->getContext()); 00705 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset); 00706 if (V->getType()->isVectorTy()) 00707 return ConstantVector::getSplat(V->getType()->getVectorNumElements(), 00708 OffsetIntPtr); 00709 return OffsetIntPtr; 00710 } 00711 00712 /// \brief Compute the constant difference between two pointer values. 00713 /// If the difference is not a constant, returns zero. 00714 static Constant *computePointerDifference(const DataLayout *TD, 00715 Value *LHS, Value *RHS) { 00716 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS); 00717 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS); 00718 00719 // If LHS and RHS are not related via constant offsets to the same base 00720 // value, there is nothing we can do here. 00721 if (LHS != RHS) 00722 return 0; 00723 00724 // Otherwise, the difference of LHS - RHS can be computed as: 00725 // LHS - RHS 00726 // = (LHSOffset + Base) - (RHSOffset + Base) 00727 // = LHSOffset - RHSOffset 00728 return ConstantExpr::getSub(LHSOffset, RHSOffset); 00729 } 00730 00731 /// SimplifySubInst - Given operands for a Sub, see if we can 00732 /// fold the result. If not, this returns null. 00733 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 00734 const Query &Q, unsigned MaxRecurse) { 00735 if (Constant *CLHS = dyn_cast<Constant>(Op0)) 00736 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00737 Constant *Ops[] = { CLHS, CRHS }; 00738 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(), 00739 Ops, Q.TD, Q.TLI); 00740 } 00741 00742 // X - undef -> undef 00743 // undef - X -> undef 00744 if (match(Op0, m_Undef()) || match(Op1, m_Undef())) 00745 return UndefValue::get(Op0->getType()); 00746 00747 // X - 0 -> X 00748 if (match(Op1, m_Zero())) 00749 return Op0; 00750 00751 // X - X -> 0 00752 if (Op0 == Op1) 00753 return Constant::getNullValue(Op0->getType()); 00754 00755 // (X*2) - X -> X 00756 // (X<<1) - X -> X 00757 Value *X = 0; 00758 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) || 00759 match(Op0, m_Shl(m_Specific(Op1), m_One()))) 00760 return Op1; 00761 00762 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. 00763 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X 00764 Value *Y = 0, *Z = Op1; 00765 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z 00766 // See if "V === Y - Z" simplifies. 00767 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) 00768 // It does! Now see if "X + V" simplifies. 00769 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { 00770 // It does, we successfully reassociated! 00771 ++NumReassoc; 00772 return W; 00773 } 00774 // See if "V === X - Z" simplifies. 00775 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 00776 // It does! Now see if "Y + V" simplifies. 00777 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { 00778 // It does, we successfully reassociated! 00779 ++NumReassoc; 00780 return W; 00781 } 00782 } 00783 00784 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. 00785 // For example, X - (X + 1) -> -1 00786 X = Op0; 00787 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) 00788 // See if "V === X - Y" simplifies. 00789 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 00790 // It does! Now see if "V - Z" simplifies. 00791 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { 00792 // It does, we successfully reassociated! 00793 ++NumReassoc; 00794 return W; 00795 } 00796 // See if "V === X - Z" simplifies. 00797 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 00798 // It does! Now see if "V - Y" simplifies. 00799 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { 00800 // It does, we successfully reassociated! 00801 ++NumReassoc; 00802 return W; 00803 } 00804 } 00805 00806 // Z - (X - Y) -> (Z - X) + Y if everything simplifies. 00807 // For example, X - (X - Y) -> Y. 00808 Z = Op0; 00809 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) 00810 // See if "V === Z - X" simplifies. 00811 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) 00812 // It does! Now see if "V + Y" simplifies. 00813 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { 00814 // It does, we successfully reassociated! 00815 ++NumReassoc; 00816 return W; 00817 } 00818 00819 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. 00820 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && 00821 match(Op1, m_Trunc(m_Value(Y)))) 00822 if (X->getType() == Y->getType()) 00823 // See if "V === X - Y" simplifies. 00824 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 00825 // It does! Now see if "trunc V" simplifies. 00826 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1)) 00827 // It does, return the simplified "trunc V". 00828 return W; 00829 00830 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 00831 if (match(Op0, m_PtrToInt(m_Value(X))) && 00832 match(Op1, m_PtrToInt(m_Value(Y)))) 00833 if (Constant *Result = computePointerDifference(Q.TD, X, Y)) 00834 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 00835 00836 // Mul distributes over Sub. Try some generic simplifications based on this. 00837 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul, 00838 Q, MaxRecurse)) 00839 return V; 00840 00841 // i1 sub -> xor. 00842 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 00843 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 00844 return V; 00845 00846 // Threading Sub over selects and phi nodes is pointless, so don't bother. 00847 // Threading over the select in "A - select(cond, B, C)" means evaluating 00848 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 00849 // only if B and C are equal. If B and C are equal then (since we assume 00850 // that operands have already been simplified) "select(cond, B, C)" should 00851 // have been simplified to the common value of B and C already. Analysing 00852 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 00853 // for threading over phi nodes. 00854 00855 return 0; 00856 } 00857 00858 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 00859 const DataLayout *TD, const TargetLibraryInfo *TLI, 00860 const DominatorTree *DT) { 00861 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT), 00862 RecursionLimit); 00863 } 00864 00865 /// Given operands for an FAdd, see if we can fold the result. If not, this 00866 /// returns null. 00867 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 00868 const Query &Q, unsigned MaxRecurse) { 00869 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 00870 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00871 Constant *Ops[] = { CLHS, CRHS }; 00872 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(), 00873 Ops, Q.TD, Q.TLI); 00874 } 00875 00876 // Canonicalize the constant to the RHS. 00877 std::swap(Op0, Op1); 00878 } 00879 00880 // fadd X, -0 ==> X 00881 if (match(Op1, m_NegZero())) 00882 return Op0; 00883 00884 // fadd X, 0 ==> X, when we know X is not -0 00885 if (match(Op1, m_Zero()) && 00886 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 00887 return Op0; 00888 00889 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0 00890 // where nnan and ninf have to occur at least once somewhere in this 00891 // expression 00892 Value *SubOp = 0; 00893 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0)))) 00894 SubOp = Op1; 00895 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1)))) 00896 SubOp = Op0; 00897 if (SubOp) { 00898 Instruction *FSub = cast<Instruction>(SubOp); 00899 if ((FMF.noNaNs() || FSub->hasNoNaNs()) && 00900 (FMF.noInfs() || FSub->hasNoInfs())) 00901 return Constant::getNullValue(Op0->getType()); 00902 } 00903 00904 return 0; 00905 } 00906 00907 /// Given operands for an FSub, see if we can fold the result. If not, this 00908 /// returns null. 00909 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 00910 const Query &Q, unsigned MaxRecurse) { 00911 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 00912 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00913 Constant *Ops[] = { CLHS, CRHS }; 00914 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(), 00915 Ops, Q.TD, Q.TLI); 00916 } 00917 } 00918 00919 // fsub X, 0 ==> X 00920 if (match(Op1, m_Zero())) 00921 return Op0; 00922 00923 // fsub X, -0 ==> X, when we know X is not -0 00924 if (match(Op1, m_NegZero()) && 00925 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 00926 return Op0; 00927 00928 // fsub 0, (fsub -0.0, X) ==> X 00929 Value *X; 00930 if (match(Op0, m_AnyZero())) { 00931 if (match(Op1, m_FSub(m_NegZero(), m_Value(X)))) 00932 return X; 00933 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X)))) 00934 return X; 00935 } 00936 00937 // fsub nnan ninf x, x ==> 0.0 00938 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1) 00939 return Constant::getNullValue(Op0->getType()); 00940 00941 return 0; 00942 } 00943 00944 /// Given the operands for an FMul, see if we can fold the result 00945 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, 00946 FastMathFlags FMF, 00947 const Query &Q, 00948 unsigned MaxRecurse) { 00949 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 00950 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00951 Constant *Ops[] = { CLHS, CRHS }; 00952 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(), 00953 Ops, Q.TD, Q.TLI); 00954 } 00955 00956 // Canonicalize the constant to the RHS. 00957 std::swap(Op0, Op1); 00958 } 00959 00960 // fmul X, 1.0 ==> X 00961 if (match(Op1, m_FPOne())) 00962 return Op0; 00963 00964 // fmul nnan nsz X, 0 ==> 0 00965 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero())) 00966 return Op1; 00967 00968 return 0; 00969 } 00970 00971 /// SimplifyMulInst - Given operands for a Mul, see if we can 00972 /// fold the result. If not, this returns null. 00973 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q, 00974 unsigned MaxRecurse) { 00975 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 00976 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 00977 Constant *Ops[] = { CLHS, CRHS }; 00978 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(), 00979 Ops, Q.TD, Q.TLI); 00980 } 00981 00982 // Canonicalize the constant to the RHS. 00983 std::swap(Op0, Op1); 00984 } 00985 00986 // X * undef -> 0 00987 if (match(Op1, m_Undef())) 00988 return Constant::getNullValue(Op0->getType()); 00989 00990 // X * 0 -> 0 00991 if (match(Op1, m_Zero())) 00992 return Op1; 00993 00994 // X * 1 -> X 00995 if (match(Op1, m_One())) 00996 return Op0; 00997 00998 // (X / Y) * Y -> X if the division is exact. 00999 Value *X = 0; 01000 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 01001 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y) 01002 return X; 01003 01004 // i1 mul -> and. 01005 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 01006 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 01007 return V; 01008 01009 // Try some generic simplifications for associative operations. 01010 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 01011 MaxRecurse)) 01012 return V; 01013 01014 // Mul distributes over Add. Try some generic simplifications based on this. 01015 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add, 01016 Q, MaxRecurse)) 01017 return V; 01018 01019 // If the operation is with the result of a select instruction, check whether 01020 // operating on either branch of the select always yields the same value. 01021 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01022 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 01023 MaxRecurse)) 01024 return V; 01025 01026 // If the operation is with the result of a phi instruction, check whether 01027 // operating on all incoming values of the phi always yields the same value. 01028 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01029 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 01030 MaxRecurse)) 01031 return V; 01032 01033 return 0; 01034 } 01035 01036 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 01037 const DataLayout *TD, const TargetLibraryInfo *TLI, 01038 const DominatorTree *DT) { 01039 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit); 01040 } 01041 01042 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 01043 const DataLayout *TD, const TargetLibraryInfo *TLI, 01044 const DominatorTree *DT) { 01045 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit); 01046 } 01047 01048 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, 01049 FastMathFlags FMF, 01050 const DataLayout *TD, 01051 const TargetLibraryInfo *TLI, 01052 const DominatorTree *DT) { 01053 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit); 01054 } 01055 01056 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD, 01057 const TargetLibraryInfo *TLI, 01058 const DominatorTree *DT) { 01059 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01060 } 01061 01062 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can 01063 /// fold the result. If not, this returns null. 01064 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 01065 const Query &Q, unsigned MaxRecurse) { 01066 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 01067 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 01068 Constant *Ops[] = { C0, C1 }; 01069 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI); 01070 } 01071 } 01072 01073 bool isSigned = Opcode == Instruction::SDiv; 01074 01075 // X / undef -> undef 01076 if (match(Op1, m_Undef())) 01077 return Op1; 01078 01079 // undef / X -> 0 01080 if (match(Op0, m_Undef())) 01081 return Constant::getNullValue(Op0->getType()); 01082 01083 // 0 / X -> 0, we don't need to preserve faults! 01084 if (match(Op0, m_Zero())) 01085 return Op0; 01086 01087 // X / 1 -> X 01088 if (match(Op1, m_One())) 01089 return Op0; 01090 01091 if (Op0->getType()->isIntegerTy(1)) 01092 // It can't be division by zero, hence it must be division by one. 01093 return Op0; 01094 01095 // X / X -> 1 01096 if (Op0 == Op1) 01097 return ConstantInt::get(Op0->getType(), 1); 01098 01099 // (X * Y) / Y -> X if the multiplication does not overflow. 01100 Value *X = 0, *Y = 0; 01101 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) { 01102 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1 01103 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0); 01104 // If the Mul knows it does not overflow, then we are good to go. 01105 if ((isSigned && Mul->hasNoSignedWrap()) || 01106 (!isSigned && Mul->hasNoUnsignedWrap())) 01107 return X; 01108 // If X has the form X = A / Y then X * Y cannot overflow. 01109 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X)) 01110 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y) 01111 return X; 01112 } 01113 01114 // (X rem Y) / Y -> 0 01115 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 01116 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 01117 return Constant::getNullValue(Op0->getType()); 01118 01119 // If the operation is with the result of a select instruction, check whether 01120 // operating on either branch of the select always yields the same value. 01121 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01122 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 01123 return V; 01124 01125 // If the operation is with the result of a phi instruction, check whether 01126 // operating on all incoming values of the phi always yields the same value. 01127 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01128 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 01129 return V; 01130 01131 return 0; 01132 } 01133 01134 /// SimplifySDivInst - Given operands for an SDiv, see if we can 01135 /// fold the result. If not, this returns null. 01136 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q, 01137 unsigned MaxRecurse) { 01138 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse)) 01139 return V; 01140 01141 return 0; 01142 } 01143 01144 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD, 01145 const TargetLibraryInfo *TLI, 01146 const DominatorTree *DT) { 01147 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01148 } 01149 01150 /// SimplifyUDivInst - Given operands for a UDiv, see if we can 01151 /// fold the result. If not, this returns null. 01152 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q, 01153 unsigned MaxRecurse) { 01154 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse)) 01155 return V; 01156 01157 return 0; 01158 } 01159 01160 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD, 01161 const TargetLibraryInfo *TLI, 01162 const DominatorTree *DT) { 01163 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01164 } 01165 01166 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q, 01167 unsigned) { 01168 // undef / X -> undef (the undef could be a snan). 01169 if (match(Op0, m_Undef())) 01170 return Op0; 01171 01172 // X / undef -> undef 01173 if (match(Op1, m_Undef())) 01174 return Op1; 01175 01176 return 0; 01177 } 01178 01179 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD, 01180 const TargetLibraryInfo *TLI, 01181 const DominatorTree *DT) { 01182 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01183 } 01184 01185 /// SimplifyRem - Given operands for an SRem or URem, see if we can 01186 /// fold the result. If not, this returns null. 01187 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 01188 const Query &Q, unsigned MaxRecurse) { 01189 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 01190 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 01191 Constant *Ops[] = { C0, C1 }; 01192 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI); 01193 } 01194 } 01195 01196 // X % undef -> undef 01197 if (match(Op1, m_Undef())) 01198 return Op1; 01199 01200 // undef % X -> 0 01201 if (match(Op0, m_Undef())) 01202 return Constant::getNullValue(Op0->getType()); 01203 01204 // 0 % X -> 0, we don't need to preserve faults! 01205 if (match(Op0, m_Zero())) 01206 return Op0; 01207 01208 // X % 0 -> undef, we don't need to preserve faults! 01209 if (match(Op1, m_Zero())) 01210 return UndefValue::get(Op0->getType()); 01211 01212 // X % 1 -> 0 01213 if (match(Op1, m_One())) 01214 return Constant::getNullValue(Op0->getType()); 01215 01216 if (Op0->getType()->isIntegerTy(1)) 01217 // It can't be remainder by zero, hence it must be remainder by one. 01218 return Constant::getNullValue(Op0->getType()); 01219 01220 // X % X -> 0 01221 if (Op0 == Op1) 01222 return Constant::getNullValue(Op0->getType()); 01223 01224 // If the operation is with the result of a select instruction, check whether 01225 // operating on either branch of the select always yields the same value. 01226 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01227 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 01228 return V; 01229 01230 // If the operation is with the result of a phi instruction, check whether 01231 // operating on all incoming values of the phi always yields the same value. 01232 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01233 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 01234 return V; 01235 01236 return 0; 01237 } 01238 01239 /// SimplifySRemInst - Given operands for an SRem, see if we can 01240 /// fold the result. If not, this returns null. 01241 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q, 01242 unsigned MaxRecurse) { 01243 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse)) 01244 return V; 01245 01246 return 0; 01247 } 01248 01249 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD, 01250 const TargetLibraryInfo *TLI, 01251 const DominatorTree *DT) { 01252 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01253 } 01254 01255 /// SimplifyURemInst - Given operands for a URem, see if we can 01256 /// fold the result. If not, this returns null. 01257 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q, 01258 unsigned MaxRecurse) { 01259 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse)) 01260 return V; 01261 01262 return 0; 01263 } 01264 01265 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD, 01266 const TargetLibraryInfo *TLI, 01267 const DominatorTree *DT) { 01268 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01269 } 01270 01271 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &, 01272 unsigned) { 01273 // undef % X -> undef (the undef could be a snan). 01274 if (match(Op0, m_Undef())) 01275 return Op0; 01276 01277 // X % undef -> undef 01278 if (match(Op1, m_Undef())) 01279 return Op1; 01280 01281 return 0; 01282 } 01283 01284 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD, 01285 const TargetLibraryInfo *TLI, 01286 const DominatorTree *DT) { 01287 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01288 } 01289 01290 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can 01291 /// fold the result. If not, this returns null. 01292 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1, 01293 const Query &Q, unsigned MaxRecurse) { 01294 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 01295 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 01296 Constant *Ops[] = { C0, C1 }; 01297 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI); 01298 } 01299 } 01300 01301 // 0 shift by X -> 0 01302 if (match(Op0, m_Zero())) 01303 return Op0; 01304 01305 // X shift by 0 -> X 01306 if (match(Op1, m_Zero())) 01307 return Op0; 01308 01309 // X shift by undef -> undef because it may shift by the bitwidth. 01310 if (match(Op1, m_Undef())) 01311 return Op1; 01312 01313 // Shifting by the bitwidth or more is undefined. 01314 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) 01315 if (CI->getValue().getLimitedValue() >= 01316 Op0->getType()->getScalarSizeInBits()) 01317 return UndefValue::get(Op0->getType()); 01318 01319 // If the operation is with the result of a select instruction, check whether 01320 // operating on either branch of the select always yields the same value. 01321 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01322 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 01323 return V; 01324 01325 // If the operation is with the result of a phi instruction, check whether 01326 // operating on all incoming values of the phi always yields the same value. 01327 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01328 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 01329 return V; 01330 01331 return 0; 01332 } 01333 01334 /// SimplifyShlInst - Given operands for an Shl, see if we can 01335 /// fold the result. If not, this returns null. 01336 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 01337 const Query &Q, unsigned MaxRecurse) { 01338 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse)) 01339 return V; 01340 01341 // undef << X -> 0 01342 if (match(Op0, m_Undef())) 01343 return Constant::getNullValue(Op0->getType()); 01344 01345 // (X >> A) << A -> X 01346 Value *X; 01347 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 01348 return X; 01349 return 0; 01350 } 01351 01352 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 01353 const DataLayout *TD, const TargetLibraryInfo *TLI, 01354 const DominatorTree *DT) { 01355 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT), 01356 RecursionLimit); 01357 } 01358 01359 /// SimplifyLShrInst - Given operands for an LShr, see if we can 01360 /// fold the result. If not, this returns null. 01361 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 01362 const Query &Q, unsigned MaxRecurse) { 01363 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse)) 01364 return V; 01365 01366 // undef >>l X -> 0 01367 if (match(Op0, m_Undef())) 01368 return Constant::getNullValue(Op0->getType()); 01369 01370 // (X << A) >> A -> X 01371 Value *X; 01372 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 01373 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap()) 01374 return X; 01375 01376 return 0; 01377 } 01378 01379 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 01380 const DataLayout *TD, 01381 const TargetLibraryInfo *TLI, 01382 const DominatorTree *DT) { 01383 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT), 01384 RecursionLimit); 01385 } 01386 01387 /// SimplifyAShrInst - Given operands for an AShr, see if we can 01388 /// fold the result. If not, this returns null. 01389 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 01390 const Query &Q, unsigned MaxRecurse) { 01391 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse)) 01392 return V; 01393 01394 // all ones >>a X -> all ones 01395 if (match(Op0, m_AllOnes())) 01396 return Op0; 01397 01398 // undef >>a X -> all ones 01399 if (match(Op0, m_Undef())) 01400 return Constant::getAllOnesValue(Op0->getType()); 01401 01402 // (X << A) >> A -> X 01403 Value *X; 01404 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 01405 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap()) 01406 return X; 01407 01408 return 0; 01409 } 01410 01411 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 01412 const DataLayout *TD, 01413 const TargetLibraryInfo *TLI, 01414 const DominatorTree *DT) { 01415 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT), 01416 RecursionLimit); 01417 } 01418 01419 /// SimplifyAndInst - Given operands for an And, see if we can 01420 /// fold the result. If not, this returns null. 01421 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q, 01422 unsigned MaxRecurse) { 01423 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 01424 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 01425 Constant *Ops[] = { CLHS, CRHS }; 01426 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(), 01427 Ops, Q.TD, Q.TLI); 01428 } 01429 01430 // Canonicalize the constant to the RHS. 01431 std::swap(Op0, Op1); 01432 } 01433 01434 // X & undef -> 0 01435 if (match(Op1, m_Undef())) 01436 return Constant::getNullValue(Op0->getType()); 01437 01438 // X & X = X 01439 if (Op0 == Op1) 01440 return Op0; 01441 01442 // X & 0 = 0 01443 if (match(Op1, m_Zero())) 01444 return Op1; 01445 01446 // X & -1 = X 01447 if (match(Op1, m_AllOnes())) 01448 return Op0; 01449 01450 // A & ~A = ~A & A = 0 01451 if (match(Op0, m_Not(m_Specific(Op1))) || 01452 match(Op1, m_Not(m_Specific(Op0)))) 01453 return Constant::getNullValue(Op0->getType()); 01454 01455 // (A | ?) & A = A 01456 Value *A = 0, *B = 0; 01457 if (match(Op0, m_Or(m_Value(A), m_Value(B))) && 01458 (A == Op1 || B == Op1)) 01459 return Op1; 01460 01461 // A & (A | ?) = A 01462 if (match(Op1, m_Or(m_Value(A), m_Value(B))) && 01463 (A == Op0 || B == Op0)) 01464 return Op0; 01465 01466 // A & (-A) = A if A is a power of two or zero. 01467 if (match(Op0, m_Neg(m_Specific(Op1))) || 01468 match(Op1, m_Neg(m_Specific(Op0)))) { 01469 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true)) 01470 return Op0; 01471 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) 01472 return Op1; 01473 } 01474 01475 // Try some generic simplifications for associative operations. 01476 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 01477 MaxRecurse)) 01478 return V; 01479 01480 // And distributes over Or. Try some generic simplifications based on this. 01481 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or, 01482 Q, MaxRecurse)) 01483 return V; 01484 01485 // And distributes over Xor. Try some generic simplifications based on this. 01486 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor, 01487 Q, MaxRecurse)) 01488 return V; 01489 01490 // Or distributes over And. Try some generic simplifications based on this. 01491 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or, 01492 Q, MaxRecurse)) 01493 return V; 01494 01495 // If the operation is with the result of a select instruction, check whether 01496 // operating on either branch of the select always yields the same value. 01497 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01498 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 01499 MaxRecurse)) 01500 return V; 01501 01502 // If the operation is with the result of a phi instruction, check whether 01503 // operating on all incoming values of the phi always yields the same value. 01504 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01505 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 01506 MaxRecurse)) 01507 return V; 01508 01509 return 0; 01510 } 01511 01512 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD, 01513 const TargetLibraryInfo *TLI, 01514 const DominatorTree *DT) { 01515 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01516 } 01517 01518 /// SimplifyOrInst - Given operands for an Or, see if we can 01519 /// fold the result. If not, this returns null. 01520 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q, 01521 unsigned MaxRecurse) { 01522 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 01523 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 01524 Constant *Ops[] = { CLHS, CRHS }; 01525 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(), 01526 Ops, Q.TD, Q.TLI); 01527 } 01528 01529 // Canonicalize the constant to the RHS. 01530 std::swap(Op0, Op1); 01531 } 01532 01533 // X | undef -> -1 01534 if (match(Op1, m_Undef())) 01535 return Constant::getAllOnesValue(Op0->getType()); 01536 01537 // X | X = X 01538 if (Op0 == Op1) 01539 return Op0; 01540 01541 // X | 0 = X 01542 if (match(Op1, m_Zero())) 01543 return Op0; 01544 01545 // X | -1 = -1 01546 if (match(Op1, m_AllOnes())) 01547 return Op1; 01548 01549 // A | ~A = ~A | A = -1 01550 if (match(Op0, m_Not(m_Specific(Op1))) || 01551 match(Op1, m_Not(m_Specific(Op0)))) 01552 return Constant::getAllOnesValue(Op0->getType()); 01553 01554 // (A & ?) | A = A 01555 Value *A = 0, *B = 0; 01556 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 01557 (A == Op1 || B == Op1)) 01558 return Op1; 01559 01560 // A | (A & ?) = A 01561 if (match(Op1, m_And(m_Value(A), m_Value(B))) && 01562 (A == Op0 || B == Op0)) 01563 return Op0; 01564 01565 // ~(A & ?) | A = -1 01566 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) && 01567 (A == Op1 || B == Op1)) 01568 return Constant::getAllOnesValue(Op1->getType()); 01569 01570 // A | ~(A & ?) = -1 01571 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) && 01572 (A == Op0 || B == Op0)) 01573 return Constant::getAllOnesValue(Op0->getType()); 01574 01575 // Try some generic simplifications for associative operations. 01576 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 01577 MaxRecurse)) 01578 return V; 01579 01580 // Or distributes over And. Try some generic simplifications based on this. 01581 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q, 01582 MaxRecurse)) 01583 return V; 01584 01585 // And distributes over Or. Try some generic simplifications based on this. 01586 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And, 01587 Q, MaxRecurse)) 01588 return V; 01589 01590 // If the operation is with the result of a select instruction, check whether 01591 // operating on either branch of the select always yields the same value. 01592 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 01593 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 01594 MaxRecurse)) 01595 return V; 01596 01597 // If the operation is with the result of a phi instruction, check whether 01598 // operating on all incoming values of the phi always yields the same value. 01599 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 01600 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 01601 return V; 01602 01603 return 0; 01604 } 01605 01606 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD, 01607 const TargetLibraryInfo *TLI, 01608 const DominatorTree *DT) { 01609 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01610 } 01611 01612 /// SimplifyXorInst - Given operands for a Xor, see if we can 01613 /// fold the result. If not, this returns null. 01614 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q, 01615 unsigned MaxRecurse) { 01616 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 01617 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 01618 Constant *Ops[] = { CLHS, CRHS }; 01619 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(), 01620 Ops, Q.TD, Q.TLI); 01621 } 01622 01623 // Canonicalize the constant to the RHS. 01624 std::swap(Op0, Op1); 01625 } 01626 01627 // A ^ undef -> undef 01628 if (match(Op1, m_Undef())) 01629 return Op1; 01630 01631 // A ^ 0 = A 01632 if (match(Op1, m_Zero())) 01633 return Op0; 01634 01635 // A ^ A = 0 01636 if (Op0 == Op1) 01637 return Constant::getNullValue(Op0->getType()); 01638 01639 // A ^ ~A = ~A ^ A = -1 01640 if (match(Op0, m_Not(m_Specific(Op1))) || 01641 match(Op1, m_Not(m_Specific(Op0)))) 01642 return Constant::getAllOnesValue(Op0->getType()); 01643 01644 // Try some generic simplifications for associative operations. 01645 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 01646 MaxRecurse)) 01647 return V; 01648 01649 // And distributes over Xor. Try some generic simplifications based on this. 01650 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And, 01651 Q, MaxRecurse)) 01652 return V; 01653 01654 // Threading Xor over selects and phi nodes is pointless, so don't bother. 01655 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 01656 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 01657 // only if B and C are equal. If B and C are equal then (since we assume 01658 // that operands have already been simplified) "select(cond, B, C)" should 01659 // have been simplified to the common value of B and C already. Analysing 01660 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 01661 // for threading over phi nodes. 01662 01663 return 0; 01664 } 01665 01666 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD, 01667 const TargetLibraryInfo *TLI, 01668 const DominatorTree *DT) { 01669 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit); 01670 } 01671 01672 static Type *GetCompareTy(Value *Op) { 01673 return CmpInst::makeCmpResultType(Op->getType()); 01674 } 01675 01676 /// ExtractEquivalentCondition - Rummage around inside V looking for something 01677 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found, 01678 /// otherwise return null. Helper function for analyzing max/min idioms. 01679 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 01680 Value *LHS, Value *RHS) { 01681 SelectInst *SI = dyn_cast<SelectInst>(V); 01682 if (!SI) 01683 return 0; 01684 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 01685 if (!Cmp) 01686 return 0; 01687 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 01688 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 01689 return Cmp; 01690 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 01691 LHS == CmpRHS && RHS == CmpLHS) 01692 return Cmp; 01693 return 0; 01694 } 01695 01696 // A significant optimization not implemented here is assuming that alloca 01697 // addresses are not equal to incoming argument values. They don't *alias*, 01698 // as we say, but that doesn't mean they aren't equal, so we take a 01699 // conservative approach. 01700 // 01701 // This is inspired in part by C++11 5.10p1: 01702 // "Two pointers of the same type compare equal if and only if they are both 01703 // null, both point to the same function, or both represent the same 01704 // address." 01705 // 01706 // This is pretty permissive. 01707 // 01708 // It's also partly due to C11 6.5.9p6: 01709 // "Two pointers compare equal if and only if both are null pointers, both are 01710 // pointers to the same object (including a pointer to an object and a 01711 // subobject at its beginning) or function, both are pointers to one past the 01712 // last element of the same array object, or one is a pointer to one past the 01713 // end of one array object and the other is a pointer to the start of a 01714 // different array object that happens to immediately follow the first array 01715 // object in the address space.) 01716 // 01717 // C11's version is more restrictive, however there's no reason why an argument 01718 // couldn't be a one-past-the-end value for a stack object in the caller and be 01719 // equal to the beginning of a stack object in the callee. 01720 // 01721 // If the C and C++ standards are ever made sufficiently restrictive in this 01722 // area, it may be possible to update LLVM's semantics accordingly and reinstate 01723 // this optimization. 01724 static Constant *computePointerICmp(const DataLayout *TD, 01725 const TargetLibraryInfo *TLI, 01726 CmpInst::Predicate Pred, 01727 Value *LHS, Value *RHS) { 01728 // First, skip past any trivial no-ops. 01729 LHS = LHS->stripPointerCasts(); 01730 RHS = RHS->stripPointerCasts(); 01731 01732 // A non-null pointer is not equal to a null pointer. 01733 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) && 01734 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE)) 01735 return ConstantInt::get(GetCompareTy(LHS), 01736 !CmpInst::isTrueWhenEqual(Pred)); 01737 01738 // We can only fold certain predicates on pointer comparisons. 01739 switch (Pred) { 01740 default: 01741 return 0; 01742 01743 // Equality comaprisons are easy to fold. 01744 case CmpInst::ICMP_EQ: 01745 case CmpInst::ICMP_NE: 01746 break; 01747 01748 // We can only handle unsigned relational comparisons because 'inbounds' on 01749 // a GEP only protects against unsigned wrapping. 01750 case CmpInst::ICMP_UGT: 01751 case CmpInst::ICMP_UGE: 01752 case CmpInst::ICMP_ULT: 01753 case CmpInst::ICMP_ULE: 01754 // However, we have to switch them to their signed variants to handle 01755 // negative indices from the base pointer. 01756 Pred = ICmpInst::getSignedPredicate(Pred); 01757 break; 01758 } 01759 01760 // Strip off any constant offsets so that we can reason about them. 01761 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 01762 // here and compare base addresses like AliasAnalysis does, however there are 01763 // numerous hazards. AliasAnalysis and its utilities rely on special rules 01764 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 01765 // doesn't need to guarantee pointer inequality when it says NoAlias. 01766 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS); 01767 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS); 01768 01769 // If LHS and RHS are related via constant offsets to the same base 01770 // value, we can replace it with an icmp which just compares the offsets. 01771 if (LHS == RHS) 01772 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 01773 01774 // Various optimizations for (in)equality comparisons. 01775 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 01776 // Different non-empty allocations that exist at the same time have 01777 // different addresses (if the program can tell). Global variables always 01778 // exist, so they always exist during the lifetime of each other and all 01779 // allocas. Two different allocas usually have different addresses... 01780 // 01781 // However, if there's an @llvm.stackrestore dynamically in between two 01782 // allocas, they may have the same address. It's tempting to reduce the 01783 // scope of the problem by only looking at *static* allocas here. That would 01784 // cover the majority of allocas while significantly reducing the likelihood 01785 // of having an @llvm.stackrestore pop up in the middle. However, it's not 01786 // actually impossible for an @llvm.stackrestore to pop up in the middle of 01787 // an entry block. Also, if we have a block that's not attached to a 01788 // function, we can't tell if it's "static" under the current definition. 01789 // Theoretically, this problem could be fixed by creating a new kind of 01790 // instruction kind specifically for static allocas. Such a new instruction 01791 // could be required to be at the top of the entry block, thus preventing it 01792 // from being subject to a @llvm.stackrestore. Instcombine could even 01793 // convert regular allocas into these special allocas. It'd be nifty. 01794 // However, until then, this problem remains open. 01795 // 01796 // So, we'll assume that two non-empty allocas have different addresses 01797 // for now. 01798 // 01799 // With all that, if the offsets are within the bounds of their allocations 01800 // (and not one-past-the-end! so we can't use inbounds!), and their 01801 // allocations aren't the same, the pointers are not equal. 01802 // 01803 // Note that it's not necessary to check for LHS being a global variable 01804 // address, due to canonicalization and constant folding. 01805 if (isa<AllocaInst>(LHS) && 01806 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 01807 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 01808 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 01809 uint64_t LHSSize, RHSSize; 01810 if (LHSOffsetCI && RHSOffsetCI && 01811 getObjectSize(LHS, LHSSize, TD, TLI) && 01812 getObjectSize(RHS, RHSSize, TD, TLI)) { 01813 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 01814 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 01815 if (!LHSOffsetValue.isNegative() && 01816 !RHSOffsetValue.isNegative() && 01817 LHSOffsetValue.ult(LHSSize) && 01818 RHSOffsetValue.ult(RHSSize)) { 01819 return ConstantInt::get(GetCompareTy(LHS), 01820 !CmpInst::isTrueWhenEqual(Pred)); 01821 } 01822 } 01823 01824 // Repeat the above check but this time without depending on DataLayout 01825 // or being able to compute a precise size. 01826 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 01827 !cast<PointerType>(RHS->getType())->isEmptyTy() && 01828 LHSOffset->isNullValue() && 01829 RHSOffset->isNullValue()) 01830 return ConstantInt::get(GetCompareTy(LHS), 01831 !CmpInst::isTrueWhenEqual(Pred)); 01832 } 01833 } 01834 01835 // Otherwise, fail. 01836 return 0; 01837 } 01838 01839 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can 01840 /// fold the result. If not, this returns null. 01841 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 01842 const Query &Q, unsigned MaxRecurse) { 01843 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 01844 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 01845 01846 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 01847 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 01848 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI); 01849 01850 // If we have a constant, make sure it is on the RHS. 01851 std::swap(LHS, RHS); 01852 Pred = CmpInst::getSwappedPredicate(Pred); 01853 } 01854 01855 Type *ITy = GetCompareTy(LHS); // The return type. 01856 Type *OpTy = LHS->getType(); // The operand type. 01857 01858 // icmp X, X -> true/false 01859 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false 01860 // because X could be 0. 01861 if (LHS == RHS || isa<UndefValue>(RHS)) 01862 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 01863 01864 // Special case logic when the operands have i1 type. 01865 if (OpTy->getScalarType()->isIntegerTy(1)) { 01866 switch (Pred) { 01867 default: break; 01868 case ICmpInst::ICMP_EQ: 01869 // X == 1 -> X 01870 if (match(RHS, m_One())) 01871 return LHS; 01872 break; 01873 case ICmpInst::ICMP_NE: 01874 // X != 0 -> X 01875 if (match(RHS, m_Zero())) 01876 return LHS; 01877 break; 01878 case ICmpInst::ICMP_UGT: 01879 // X >u 0 -> X 01880 if (match(RHS, m_Zero())) 01881 return LHS; 01882 break; 01883 case ICmpInst::ICMP_UGE: 01884 // X >=u 1 -> X 01885 if (match(RHS, m_One())) 01886 return LHS; 01887 break; 01888 case ICmpInst::ICMP_SLT: 01889 // X <s 0 -> X 01890 if (match(RHS, m_Zero())) 01891 return LHS; 01892 break; 01893 case ICmpInst::ICMP_SLE: 01894 // X <=s -1 -> X 01895 if (match(RHS, m_One())) 01896 return LHS; 01897 break; 01898 } 01899 } 01900 01901 // If we are comparing with zero then try hard since this is a common case. 01902 if (match(RHS, m_Zero())) { 01903 bool LHSKnownNonNegative, LHSKnownNegative; 01904 switch (Pred) { 01905 default: llvm_unreachable("Unknown ICmp predicate!"); 01906 case ICmpInst::ICMP_ULT: 01907 return getFalse(ITy); 01908 case ICmpInst::ICMP_UGE: 01909 return getTrue(ITy); 01910 case ICmpInst::ICMP_EQ: 01911 case ICmpInst::ICMP_ULE: 01912 if (isKnownNonZero(LHS, Q.TD)) 01913 return getFalse(ITy); 01914 break; 01915 case ICmpInst::ICMP_NE: 01916 case ICmpInst::ICMP_UGT: 01917 if (isKnownNonZero(LHS, Q.TD)) 01918 return getTrue(ITy); 01919 break; 01920 case ICmpInst::ICMP_SLT: 01921 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD); 01922 if (LHSKnownNegative) 01923 return getTrue(ITy); 01924 if (LHSKnownNonNegative) 01925 return getFalse(ITy); 01926 break; 01927 case ICmpInst::ICMP_SLE: 01928 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD); 01929 if (LHSKnownNegative) 01930 return getTrue(ITy); 01931 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD)) 01932 return getFalse(ITy); 01933 break; 01934 case ICmpInst::ICMP_SGE: 01935 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD); 01936 if (LHSKnownNegative) 01937 return getFalse(ITy); 01938 if (LHSKnownNonNegative) 01939 return getTrue(ITy); 01940 break; 01941 case ICmpInst::ICMP_SGT: 01942 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD); 01943 if (LHSKnownNegative) 01944 return getFalse(ITy); 01945 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD)) 01946 return getTrue(ITy); 01947 break; 01948 } 01949 } 01950 01951 // See if we are doing a comparison with a constant integer. 01952 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 01953 // Rule out tautological comparisons (eg., ult 0 or uge 0). 01954 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue()); 01955 if (RHS_CR.isEmptySet()) 01956 return ConstantInt::getFalse(CI->getContext()); 01957 if (RHS_CR.isFullSet()) 01958 return ConstantInt::getTrue(CI->getContext()); 01959 01960 // Many binary operators with constant RHS have easy to compute constant 01961 // range. Use them to check whether the comparison is a tautology. 01962 uint32_t Width = CI->getBitWidth(); 01963 APInt Lower = APInt(Width, 0); 01964 APInt Upper = APInt(Width, 0); 01965 ConstantInt *CI2; 01966 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) { 01967 // 'urem x, CI2' produces [0, CI2). 01968 Upper = CI2->getValue(); 01969 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) { 01970 // 'srem x, CI2' produces (-|CI2|, |CI2|). 01971 Upper = CI2->getValue().abs(); 01972 Lower = (-Upper) + 1; 01973 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) { 01974 // 'udiv CI2, x' produces [0, CI2]. 01975 Upper = CI2->getValue() + 1; 01976 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) { 01977 // 'udiv x, CI2' produces [0, UINT_MAX / CI2]. 01978 APInt NegOne = APInt::getAllOnesValue(Width); 01979 if (!CI2->isZero()) 01980 Upper = NegOne.udiv(CI2->getValue()) + 1; 01981 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) { 01982 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]. 01983 APInt IntMin = APInt::getSignedMinValue(Width); 01984 APInt IntMax = APInt::getSignedMaxValue(Width); 01985 APInt Val = CI2->getValue().abs(); 01986 if (!Val.isMinValue()) { 01987 Lower = IntMin.sdiv(Val); 01988 Upper = IntMax.sdiv(Val) + 1; 01989 } 01990 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) { 01991 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2]. 01992 APInt NegOne = APInt::getAllOnesValue(Width); 01993 if (CI2->getValue().ult(Width)) 01994 Upper = NegOne.lshr(CI2->getValue()) + 1; 01995 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) { 01996 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2]. 01997 APInt IntMin = APInt::getSignedMinValue(Width); 01998 APInt IntMax = APInt::getSignedMaxValue(Width); 01999 if (CI2->getValue().ult(Width)) { 02000 Lower = IntMin.ashr(CI2->getValue()); 02001 Upper = IntMax.ashr(CI2->getValue()) + 1; 02002 } 02003 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) { 02004 // 'or x, CI2' produces [CI2, UINT_MAX]. 02005 Lower = CI2->getValue(); 02006 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) { 02007 // 'and x, CI2' produces [0, CI2]. 02008 Upper = CI2->getValue() + 1; 02009 } 02010 if (Lower != Upper) { 02011 ConstantRange LHS_CR = ConstantRange(Lower, Upper); 02012 if (RHS_CR.contains(LHS_CR)) 02013 return ConstantInt::getTrue(RHS->getContext()); 02014 if (RHS_CR.inverse().contains(LHS_CR)) 02015 return ConstantInt::getFalse(RHS->getContext()); 02016 } 02017 } 02018 02019 // Compare of cast, for example (zext X) != 0 -> X != 0 02020 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 02021 Instruction *LI = cast<CastInst>(LHS); 02022 Value *SrcOp = LI->getOperand(0); 02023 Type *SrcTy = SrcOp->getType(); 02024 Type *DstTy = LI->getType(); 02025 02026 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 02027 // if the integer type is the same size as the pointer type. 02028 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) && 02029 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) { 02030 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 02031 // Transfer the cast to the constant. 02032 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 02033 ConstantExpr::getIntToPtr(RHSC, SrcTy), 02034 Q, MaxRecurse-1)) 02035 return V; 02036 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 02037 if (RI->getOperand(0)->getType() == SrcTy) 02038 // Compare without the cast. 02039 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 02040 Q, MaxRecurse-1)) 02041 return V; 02042 } 02043 } 02044 02045 if (isa<ZExtInst>(LHS)) { 02046 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 02047 // same type. 02048 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 02049 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 02050 // Compare X and Y. Note that signed predicates become unsigned. 02051 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 02052 SrcOp, RI->getOperand(0), Q, 02053 MaxRecurse-1)) 02054 return V; 02055 } 02056 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 02057 // too. If not, then try to deduce the result of the comparison. 02058 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 02059 // Compute the constant that would happen if we truncated to SrcTy then 02060 // reextended to DstTy. 02061 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 02062 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 02063 02064 // If the re-extended constant didn't change then this is effectively 02065 // also a case of comparing two zero-extended values. 02066 if (RExt == CI && MaxRecurse) 02067 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 02068 SrcOp, Trunc, Q, MaxRecurse-1)) 02069 return V; 02070 02071 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 02072 // there. Use this to work out the result of the comparison. 02073 if (RExt != CI) { 02074 switch (Pred) { 02075 default: llvm_unreachable("Unknown ICmp predicate!"); 02076 // LHS <u RHS. 02077 case ICmpInst::ICMP_EQ: 02078 case ICmpInst::ICMP_UGT: 02079 case ICmpInst::ICMP_UGE: 02080 return ConstantInt::getFalse(CI->getContext()); 02081 02082 case ICmpInst::ICMP_NE: 02083 case ICmpInst::ICMP_ULT: 02084 case ICmpInst::ICMP_ULE: 02085 return ConstantInt::getTrue(CI->getContext()); 02086 02087 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 02088 // is non-negative then LHS <s RHS. 02089 case ICmpInst::ICMP_SGT: 02090 case ICmpInst::ICMP_SGE: 02091 return CI->getValue().isNegative() ? 02092 ConstantInt::getTrue(CI->getContext()) : 02093 ConstantInt::getFalse(CI->getContext()); 02094 02095 case ICmpInst::ICMP_SLT: 02096 case ICmpInst::ICMP_SLE: 02097 return CI->getValue().isNegative() ? 02098 ConstantInt::getFalse(CI->getContext()) : 02099 ConstantInt::getTrue(CI->getContext()); 02100 } 02101 } 02102 } 02103 } 02104 02105 if (isa<SExtInst>(LHS)) { 02106 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 02107 // same type. 02108 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 02109 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 02110 // Compare X and Y. Note that the predicate does not change. 02111 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 02112 Q, MaxRecurse-1)) 02113 return V; 02114 } 02115 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 02116 // too. If not, then try to deduce the result of the comparison. 02117 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 02118 // Compute the constant that would happen if we truncated to SrcTy then 02119 // reextended to DstTy. 02120 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 02121 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 02122 02123 // If the re-extended constant didn't change then this is effectively 02124 // also a case of comparing two sign-extended values. 02125 if (RExt == CI && MaxRecurse) 02126 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 02127 return V; 02128 02129 // Otherwise the upper bits of LHS are all equal, while RHS has varying 02130 // bits there. Use this to work out the result of the comparison. 02131 if (RExt != CI) { 02132 switch (Pred) { 02133 default: llvm_unreachable("Unknown ICmp predicate!"); 02134 case ICmpInst::ICMP_EQ: 02135 return ConstantInt::getFalse(CI->getContext()); 02136 case ICmpInst::ICMP_NE: 02137 return ConstantInt::getTrue(CI->getContext()); 02138 02139 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 02140 // LHS >s RHS. 02141 case ICmpInst::ICMP_SGT: 02142 case ICmpInst::ICMP_SGE: 02143 return CI->getValue().isNegative() ? 02144 ConstantInt::getTrue(CI->getContext()) : 02145 ConstantInt::getFalse(CI->getContext()); 02146 case ICmpInst::ICMP_SLT: 02147 case ICmpInst::ICMP_SLE: 02148 return CI->getValue().isNegative() ? 02149 ConstantInt::getFalse(CI->getContext()) : 02150 ConstantInt::getTrue(CI->getContext()); 02151 02152 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 02153 // LHS >u RHS. 02154 case ICmpInst::ICMP_UGT: 02155 case ICmpInst::ICMP_UGE: 02156 // Comparison is true iff the LHS <s 0. 02157 if (MaxRecurse) 02158 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 02159 Constant::getNullValue(SrcTy), 02160 Q, MaxRecurse-1)) 02161 return V; 02162 break; 02163 case ICmpInst::ICMP_ULT: 02164 case ICmpInst::ICMP_ULE: 02165 // Comparison is true iff the LHS >=s 0. 02166 if (MaxRecurse) 02167 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 02168 Constant::getNullValue(SrcTy), 02169 Q, MaxRecurse-1)) 02170 return V; 02171 break; 02172 } 02173 } 02174 } 02175 } 02176 } 02177 02178 // Special logic for binary operators. 02179 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 02180 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 02181 if (MaxRecurse && (LBO || RBO)) { 02182 // Analyze the case when either LHS or RHS is an add instruction. 02183 Value *A = 0, *B = 0, *C = 0, *D = 0; 02184 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 02185 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 02186 if (LBO && LBO->getOpcode() == Instruction::Add) { 02187 A = LBO->getOperand(0); B = LBO->getOperand(1); 02188 NoLHSWrapProblem = ICmpInst::isEquality(Pred) || 02189 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) || 02190 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap()); 02191 } 02192 if (RBO && RBO->getOpcode() == Instruction::Add) { 02193 C = RBO->getOperand(0); D = RBO->getOperand(1); 02194 NoRHSWrapProblem = ICmpInst::isEquality(Pred) || 02195 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) || 02196 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap()); 02197 } 02198 02199 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 02200 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 02201 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 02202 Constant::getNullValue(RHS->getType()), 02203 Q, MaxRecurse-1)) 02204 return V; 02205 02206 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 02207 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 02208 if (Value *V = SimplifyICmpInst(Pred, 02209 Constant::getNullValue(LHS->getType()), 02210 C == LHS ? D : C, Q, MaxRecurse-1)) 02211 return V; 02212 02213 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 02214 if (A && C && (A == C || A == D || B == C || B == D) && 02215 NoLHSWrapProblem && NoRHSWrapProblem) { 02216 // Determine Y and Z in the form icmp (X+Y), (X+Z). 02217 Value *Y, *Z; 02218 if (A == C) { 02219 // C + B == C + D -> B == D 02220 Y = B; 02221 Z = D; 02222 } else if (A == D) { 02223 // D + B == C + D -> B == C 02224 Y = B; 02225 Z = C; 02226 } else if (B == C) { 02227 // A + C == C + D -> A == D 02228 Y = A; 02229 Z = D; 02230 } else { 02231 assert(B == D); 02232 // A + D == C + D -> A == C 02233 Y = A; 02234 Z = C; 02235 } 02236 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1)) 02237 return V; 02238 } 02239 } 02240 02241 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 02242 bool KnownNonNegative, KnownNegative; 02243 switch (Pred) { 02244 default: 02245 break; 02246 case ICmpInst::ICMP_SGT: 02247 case ICmpInst::ICMP_SGE: 02248 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD); 02249 if (!KnownNonNegative) 02250 break; 02251 // fall-through 02252 case ICmpInst::ICMP_EQ: 02253 case ICmpInst::ICMP_UGT: 02254 case ICmpInst::ICMP_UGE: 02255 return getFalse(ITy); 02256 case ICmpInst::ICMP_SLT: 02257 case ICmpInst::ICMP_SLE: 02258 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD); 02259 if (!KnownNonNegative) 02260 break; 02261 // fall-through 02262 case ICmpInst::ICMP_NE: 02263 case ICmpInst::ICMP_ULT: 02264 case ICmpInst::ICMP_ULE: 02265 return getTrue(ITy); 02266 } 02267 } 02268 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { 02269 bool KnownNonNegative, KnownNegative; 02270 switch (Pred) { 02271 default: 02272 break; 02273 case ICmpInst::ICMP_SGT: 02274 case ICmpInst::ICMP_SGE: 02275 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD); 02276 if (!KnownNonNegative) 02277 break; 02278 // fall-through 02279 case ICmpInst::ICMP_NE: 02280 case ICmpInst::ICMP_UGT: 02281 case ICmpInst::ICMP_UGE: 02282 return getTrue(ITy); 02283 case ICmpInst::ICMP_SLT: 02284 case ICmpInst::ICMP_SLE: 02285 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD); 02286 if (!KnownNonNegative) 02287 break; 02288 // fall-through 02289 case ICmpInst::ICMP_EQ: 02290 case ICmpInst::ICMP_ULT: 02291 case ICmpInst::ICMP_ULE: 02292 return getFalse(ITy); 02293 } 02294 } 02295 02296 // x udiv y <=u x. 02297 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 02298 // icmp pred (X /u Y), X 02299 if (Pred == ICmpInst::ICMP_UGT) 02300 return getFalse(ITy); 02301 if (Pred == ICmpInst::ICMP_ULE) 02302 return getTrue(ITy); 02303 } 02304 02305 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 02306 LBO->getOperand(1) == RBO->getOperand(1)) { 02307 switch (LBO->getOpcode()) { 02308 default: break; 02309 case Instruction::UDiv: 02310 case Instruction::LShr: 02311 if (ICmpInst::isSigned(Pred)) 02312 break; 02313 // fall-through 02314 case Instruction::SDiv: 02315 case Instruction::AShr: 02316 if (!LBO->isExact() || !RBO->isExact()) 02317 break; 02318 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 02319 RBO->getOperand(0), Q, MaxRecurse-1)) 02320 return V; 02321 break; 02322 case Instruction::Shl: { 02323 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap(); 02324 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap(); 02325 if (!NUW && !NSW) 02326 break; 02327 if (!NSW && ICmpInst::isSigned(Pred)) 02328 break; 02329 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 02330 RBO->getOperand(0), Q, MaxRecurse-1)) 02331 return V; 02332 break; 02333 } 02334 } 02335 } 02336 02337 // Simplify comparisons involving max/min. 02338 Value *A, *B; 02339 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 02340 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 02341 02342 // Signed variants on "max(a,b)>=a -> true". 02343 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 02344 if (A != RHS) std::swap(A, B); // smax(A, B) pred A. 02345 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 02346 // We analyze this as smax(A, B) pred A. 02347 P = Pred; 02348 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 02349 (A == LHS || B == LHS)) { 02350 if (A != LHS) std::swap(A, B); // A pred smax(A, B). 02351 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 02352 // We analyze this as smax(A, B) swapped-pred A. 02353 P = CmpInst::getSwappedPredicate(Pred); 02354 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 02355 (A == RHS || B == RHS)) { 02356 if (A != RHS) std::swap(A, B); // smin(A, B) pred A. 02357 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 02358 // We analyze this as smax(-A, -B) swapped-pred -A. 02359 // Note that we do not need to actually form -A or -B thanks to EqP. 02360 P = CmpInst::getSwappedPredicate(Pred); 02361 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 02362 (A == LHS || B == LHS)) { 02363 if (A != LHS) std::swap(A, B); // A pred smin(A, B). 02364 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 02365 // We analyze this as smax(-A, -B) pred -A. 02366 // Note that we do not need to actually form -A or -B thanks to EqP. 02367 P = Pred; 02368 } 02369 if (P != CmpInst::BAD_ICMP_PREDICATE) { 02370 // Cases correspond to "max(A, B) p A". 02371 switch (P) { 02372 default: 02373 break; 02374 case CmpInst::ICMP_EQ: 02375 case CmpInst::ICMP_SLE: 02376 // Equivalent to "A EqP B". This may be the same as the condition tested 02377 // in the max/min; if so, we can just return that. 02378 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 02379 return V; 02380 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 02381 return V; 02382 // Otherwise, see if "A EqP B" simplifies. 02383 if (MaxRecurse) 02384 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 02385 return V; 02386 break; 02387 case CmpInst::ICMP_NE: 02388 case CmpInst::ICMP_SGT: { 02389 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 02390 // Equivalent to "A InvEqP B". This may be the same as the condition 02391 // tested in the max/min; if so, we can just return that. 02392 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 02393 return V; 02394 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 02395 return V; 02396 // Otherwise, see if "A InvEqP B" simplifies. 02397 if (MaxRecurse) 02398 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 02399 return V; 02400 break; 02401 } 02402 case CmpInst::ICMP_SGE: 02403 // Always true. 02404 return getTrue(ITy); 02405 case CmpInst::ICMP_SLT: 02406 // Always false. 02407 return getFalse(ITy); 02408 } 02409 } 02410 02411 // Unsigned variants on "max(a,b)>=a -> true". 02412 P = CmpInst::BAD_ICMP_PREDICATE; 02413 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 02414 if (A != RHS) std::swap(A, B); // umax(A, B) pred A. 02415 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 02416 // We analyze this as umax(A, B) pred A. 02417 P = Pred; 02418 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 02419 (A == LHS || B == LHS)) { 02420 if (A != LHS) std::swap(A, B); // A pred umax(A, B). 02421 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 02422 // We analyze this as umax(A, B) swapped-pred A. 02423 P = CmpInst::getSwappedPredicate(Pred); 02424 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 02425 (A == RHS || B == RHS)) { 02426 if (A != RHS) std::swap(A, B); // umin(A, B) pred A. 02427 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 02428 // We analyze this as umax(-A, -B) swapped-pred -A. 02429 // Note that we do not need to actually form -A or -B thanks to EqP. 02430 P = CmpInst::getSwappedPredicate(Pred); 02431 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 02432 (A == LHS || B == LHS)) { 02433 if (A != LHS) std::swap(A, B); // A pred umin(A, B). 02434 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 02435 // We analyze this as umax(-A, -B) pred -A. 02436 // Note that we do not need to actually form -A or -B thanks to EqP. 02437 P = Pred; 02438 } 02439 if (P != CmpInst::BAD_ICMP_PREDICATE) { 02440 // Cases correspond to "max(A, B) p A". 02441 switch (P) { 02442 default: 02443 break; 02444 case CmpInst::ICMP_EQ: 02445 case CmpInst::ICMP_ULE: 02446 // Equivalent to "A EqP B". This may be the same as the condition tested 02447 // in the max/min; if so, we can just return that. 02448 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 02449 return V; 02450 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 02451 return V; 02452 // Otherwise, see if "A EqP B" simplifies. 02453 if (MaxRecurse) 02454 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 02455 return V; 02456 break; 02457 case CmpInst::ICMP_NE: 02458 case CmpInst::ICMP_UGT: { 02459 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 02460 // Equivalent to "A InvEqP B". This may be the same as the condition 02461 // tested in the max/min; if so, we can just return that. 02462 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 02463 return V; 02464 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 02465 return V; 02466 // Otherwise, see if "A InvEqP B" simplifies. 02467 if (MaxRecurse) 02468 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 02469 return V; 02470 break; 02471 } 02472 case CmpInst::ICMP_UGE: 02473 // Always true. 02474 return getTrue(ITy); 02475 case CmpInst::ICMP_ULT: 02476 // Always false. 02477 return getFalse(ITy); 02478 } 02479 } 02480 02481 // Variants on "max(x,y) >= min(x,z)". 02482 Value *C, *D; 02483 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 02484 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 02485 (A == C || A == D || B == C || B == D)) { 02486 // max(x, ?) pred min(x, ?). 02487 if (Pred == CmpInst::ICMP_SGE) 02488 // Always true. 02489 return getTrue(ITy); 02490 if (Pred == CmpInst::ICMP_SLT) 02491 // Always false. 02492 return getFalse(ITy); 02493 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 02494 match(RHS, m_SMax(m_Value(C), m_Value(D))) && 02495 (A == C || A == D || B == C || B == D)) { 02496 // min(x, ?) pred max(x, ?). 02497 if (Pred == CmpInst::ICMP_SLE) 02498 // Always true. 02499 return getTrue(ITy); 02500 if (Pred == CmpInst::ICMP_SGT) 02501 // Always false. 02502 return getFalse(ITy); 02503 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 02504 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 02505 (A == C || A == D || B == C || B == D)) { 02506 // max(x, ?) pred min(x, ?). 02507 if (Pred == CmpInst::ICMP_UGE) 02508 // Always true. 02509 return getTrue(ITy); 02510 if (Pred == CmpInst::ICMP_ULT) 02511 // Always false. 02512 return getFalse(ITy); 02513 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 02514 match(RHS, m_UMax(m_Value(C), m_Value(D))) && 02515 (A == C || A == D || B == C || B == D)) { 02516 // min(x, ?) pred max(x, ?). 02517 if (Pred == CmpInst::ICMP_ULE) 02518 // Always true. 02519 return getTrue(ITy); 02520 if (Pred == CmpInst::ICMP_UGT) 02521 // Always false. 02522 return getFalse(ITy); 02523 } 02524 02525 // Simplify comparisons of related pointers using a powerful, recursive 02526 // GEP-walk when we have target data available.. 02527 if (LHS->getType()->isPointerTy()) 02528 if (Constant *C = computePointerICmp(Q.TD, Q.TLI, Pred, LHS, RHS)) 02529 return C; 02530 02531 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { 02532 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { 02533 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && 02534 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && 02535 (ICmpInst::isEquality(Pred) || 02536 (GLHS->isInBounds() && GRHS->isInBounds() && 02537 Pred == ICmpInst::getSignedPredicate(Pred)))) { 02538 // The bases are equal and the indices are constant. Build a constant 02539 // expression GEP with the same indices and a null base pointer to see 02540 // what constant folding can make out of it. 02541 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); 02542 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end()); 02543 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS); 02544 02545 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); 02546 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS); 02547 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS); 02548 } 02549 } 02550 } 02551 02552 // If the comparison is with the result of a select instruction, check whether 02553 // comparing with either branch of the select always yields the same value. 02554 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 02555 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 02556 return V; 02557 02558 // If the comparison is with the result of a phi instruction, check whether 02559 // doing the compare with each incoming phi value yields a common result. 02560 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 02561 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 02562 return V; 02563 02564 return 0; 02565 } 02566 02567 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 02568 const DataLayout *TD, 02569 const TargetLibraryInfo *TLI, 02570 const DominatorTree *DT) { 02571 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT), 02572 RecursionLimit); 02573 } 02574 02575 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can 02576 /// fold the result. If not, this returns null. 02577 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 02578 const Query &Q, unsigned MaxRecurse) { 02579 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 02580 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 02581 02582 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 02583 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 02584 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI); 02585 02586 // If we have a constant, make sure it is on the RHS. 02587 std::swap(LHS, RHS); 02588 Pred = CmpInst::getSwappedPredicate(Pred); 02589 } 02590 02591 // Fold trivial predicates. 02592 if (Pred == FCmpInst::FCMP_FALSE) 02593 return ConstantInt::get(GetCompareTy(LHS), 0); 02594 if (Pred == FCmpInst::FCMP_TRUE) 02595 return ConstantInt::get(GetCompareTy(LHS), 1); 02596 02597 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef 02598 return UndefValue::get(GetCompareTy(LHS)); 02599 02600 // fcmp x,x -> true/false. Not all compares are foldable. 02601 if (LHS == RHS) { 02602 if (CmpInst::isTrueWhenEqual(Pred)) 02603 return ConstantInt::get(GetCompareTy(LHS), 1); 02604 if (CmpInst::isFalseWhenEqual(Pred)) 02605 return ConstantInt::get(GetCompareTy(LHS), 0); 02606 } 02607 02608 // Handle fcmp with constant RHS 02609 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 02610 // If the constant is a nan, see if we can fold the comparison based on it. 02611 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) { 02612 if (CFP->getValueAPF().isNaN()) { 02613 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo" 02614 return ConstantInt::getFalse(CFP->getContext()); 02615 assert(FCmpInst::isUnordered(Pred) && 02616 "Comparison must be either ordered or unordered!"); 02617 // True if unordered. 02618 return ConstantInt::getTrue(CFP->getContext()); 02619 } 02620 // Check whether the constant is an infinity. 02621 if (CFP->getValueAPF().isInfinity()) { 02622 if (CFP->getValueAPF().isNegative()) { 02623 switch (Pred) { 02624 case FCmpInst::FCMP_OLT: 02625 // No value is ordered and less than negative infinity. 02626 return ConstantInt::getFalse(CFP->getContext()); 02627 case FCmpInst::FCMP_UGE: 02628 // All values are unordered with or at least negative infinity. 02629 return ConstantInt::getTrue(CFP->getContext()); 02630 default: 02631 break; 02632 } 02633 } else { 02634 switch (Pred) { 02635 case FCmpInst::FCMP_OGT: 02636 // No value is ordered and greater than infinity. 02637 return ConstantInt::getFalse(CFP->getContext()); 02638 case FCmpInst::FCMP_ULE: 02639 // All values are unordered with and at most infinity. 02640 return ConstantInt::getTrue(CFP->getContext()); 02641 default: 02642 break; 02643 } 02644 } 02645 } 02646 } 02647 } 02648 02649 // If the comparison is with the result of a select instruction, check whether 02650 // comparing with either branch of the select always yields the same value. 02651 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 02652 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 02653 return V; 02654 02655 // If the comparison is with the result of a phi instruction, check whether 02656 // doing the compare with each incoming phi value yields a common result. 02657 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 02658 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 02659 return V; 02660 02661 return 0; 02662 } 02663 02664 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 02665 const DataLayout *TD, 02666 const TargetLibraryInfo *TLI, 02667 const DominatorTree *DT) { 02668 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT), 02669 RecursionLimit); 02670 } 02671 02672 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold 02673 /// the result. If not, this returns null. 02674 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal, 02675 Value *FalseVal, const Query &Q, 02676 unsigned MaxRecurse) { 02677 // select true, X, Y -> X 02678 // select false, X, Y -> Y 02679 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal)) 02680 return CB->getZExtValue() ? TrueVal : FalseVal; 02681 02682 // select C, X, X -> X 02683 if (TrueVal == FalseVal) 02684 return TrueVal; 02685 02686 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y 02687 if (isa<Constant>(TrueVal)) 02688 return TrueVal; 02689 return FalseVal; 02690 } 02691 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X 02692 return FalseVal; 02693 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X 02694 return TrueVal; 02695 02696 return 0; 02697 } 02698 02699 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 02700 const DataLayout *TD, 02701 const TargetLibraryInfo *TLI, 02702 const DominatorTree *DT) { 02703 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT), 02704 RecursionLimit); 02705 } 02706 02707 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can 02708 /// fold the result. If not, this returns null. 02709 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) { 02710 // The type of the GEP pointer operand. 02711 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType()); 02712 // The GEP pointer operand is not a pointer, it's a vector of pointers. 02713 if (!PtrTy) 02714 return 0; 02715 02716 // getelementptr P -> P. 02717 if (Ops.size() == 1) 02718 return Ops[0]; 02719 02720 if (isa<UndefValue>(Ops[0])) { 02721 // Compute the (pointer) type returned by the GEP instruction. 02722 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1)); 02723 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace()); 02724 return UndefValue::get(GEPTy); 02725 } 02726 02727 if (Ops.size() == 2) { 02728 // getelementptr P, 0 -> P. 02729 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1])) 02730 if (C->isZero()) 02731 return Ops[0]; 02732 // getelementptr P, N -> P if P points to a type of zero size. 02733 if (Q.TD) { 02734 Type *Ty = PtrTy->getElementType(); 02735 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0) 02736 return Ops[0]; 02737 } 02738 } 02739 02740 // Check to see if this is constant foldable. 02741 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 02742 if (!isa<Constant>(Ops[i])) 02743 return 0; 02744 02745 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1)); 02746 } 02747 02748 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD, 02749 const TargetLibraryInfo *TLI, 02750 const DominatorTree *DT) { 02751 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit); 02752 } 02753 02754 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we 02755 /// can fold the result. If not, this returns null. 02756 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 02757 ArrayRef<unsigned> Idxs, const Query &Q, 02758 unsigned) { 02759 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 02760 if (Constant *CVal = dyn_cast<Constant>(Val)) 02761 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 02762 02763 // insertvalue x, undef, n -> x 02764 if (match(Val, m_Undef())) 02765 return Agg; 02766 02767 // insertvalue x, (extractvalue y, n), n 02768 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 02769 if (EV->getAggregateOperand()->getType() == Agg->getType() && 02770 EV->getIndices() == Idxs) { 02771 // insertvalue undef, (extractvalue y, n), n -> y 02772 if (match(Agg, m_Undef())) 02773 return EV->getAggregateOperand(); 02774 02775 // insertvalue y, (extractvalue y, n), n -> y 02776 if (Agg == EV->getAggregateOperand()) 02777 return Agg; 02778 } 02779 02780 return 0; 02781 } 02782 02783 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 02784 ArrayRef<unsigned> Idxs, 02785 const DataLayout *TD, 02786 const TargetLibraryInfo *TLI, 02787 const DominatorTree *DT) { 02788 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT), 02789 RecursionLimit); 02790 } 02791 02792 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null. 02793 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) { 02794 // If all of the PHI's incoming values are the same then replace the PHI node 02795 // with the common value. 02796 Value *CommonValue = 0; 02797 bool HasUndefInput = false; 02798 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 02799 Value *Incoming = PN->getIncomingValue(i); 02800 // If the incoming value is the phi node itself, it can safely be skipped. 02801 if (Incoming == PN) continue; 02802 if (isa<UndefValue>(Incoming)) { 02803 // Remember that we saw an undef value, but otherwise ignore them. 02804 HasUndefInput = true; 02805 continue; 02806 } 02807 if (CommonValue && Incoming != CommonValue) 02808 return 0; // Not the same, bail out. 02809 CommonValue = Incoming; 02810 } 02811 02812 // If CommonValue is null then all of the incoming values were either undef or 02813 // equal to the phi node itself. 02814 if (!CommonValue) 02815 return UndefValue::get(PN->getType()); 02816 02817 // If we have a PHI node like phi(X, undef, X), where X is defined by some 02818 // instruction, we cannot return X as the result of the PHI node unless it 02819 // dominates the PHI block. 02820 if (HasUndefInput) 02821 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0; 02822 02823 return CommonValue; 02824 } 02825 02826 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) { 02827 if (Constant *C = dyn_cast<Constant>(Op)) 02828 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI); 02829 02830 return 0; 02831 } 02832 02833 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD, 02834 const TargetLibraryInfo *TLI, 02835 const DominatorTree *DT) { 02836 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit); 02837 } 02838 02839 //=== Helper functions for higher up the class hierarchy. 02840 02841 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can 02842 /// fold the result. If not, this returns null. 02843 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 02844 const Query &Q, unsigned MaxRecurse) { 02845 switch (Opcode) { 02846 case Instruction::Add: 02847 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 02848 Q, MaxRecurse); 02849 case Instruction::FAdd: 02850 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 02851 02852 case Instruction::Sub: 02853 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 02854 Q, MaxRecurse); 02855 case Instruction::FSub: 02856 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 02857 02858 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse); 02859 case Instruction::FMul: 02860 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse); 02861 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 02862 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 02863 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse); 02864 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 02865 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 02866 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse); 02867 case Instruction::Shl: 02868 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 02869 Q, MaxRecurse); 02870 case Instruction::LShr: 02871 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 02872 case Instruction::AShr: 02873 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 02874 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 02875 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse); 02876 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 02877 default: 02878 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 02879 if (Constant *CRHS = dyn_cast<Constant>(RHS)) { 02880 Constant *COps[] = {CLHS, CRHS}; 02881 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD, 02882 Q.TLI); 02883 } 02884 02885 // If the operation is associative, try some generic simplifications. 02886 if (Instruction::isAssociative(Opcode)) 02887 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse)) 02888 return V; 02889 02890 // If the operation is with the result of a select instruction check whether 02891 // operating on either branch of the select always yields the same value. 02892 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 02893 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse)) 02894 return V; 02895 02896 // If the operation is with the result of a phi instruction, check whether 02897 // operating on all incoming values of the phi always yields the same value. 02898 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 02899 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse)) 02900 return V; 02901 02902 return 0; 02903 } 02904 } 02905 02906 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 02907 const DataLayout *TD, const TargetLibraryInfo *TLI, 02908 const DominatorTree *DT) { 02909 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit); 02910 } 02911 02912 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can 02913 /// fold the result. 02914 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 02915 const Query &Q, unsigned MaxRecurse) { 02916 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 02917 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 02918 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 02919 } 02920 02921 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 02922 const DataLayout *TD, const TargetLibraryInfo *TLI, 02923 const DominatorTree *DT) { 02924 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT), 02925 RecursionLimit); 02926 } 02927 02928 static bool IsIdempotent(Intrinsic::ID ID) { 02929 switch (ID) { 02930 default: return false; 02931 02932 // Unary idempotent: f(f(x)) = f(x) 02933 case Intrinsic::fabs: 02934 case Intrinsic::floor: 02935 case Intrinsic::ceil: 02936 case Intrinsic::trunc: 02937 case Intrinsic::rint: 02938 case Intrinsic::nearbyint: 02939 return true; 02940 } 02941 } 02942 02943 template <typename IterTy> 02944 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd, 02945 const Query &Q, unsigned MaxRecurse) { 02946 // Perform idempotent optimizations 02947 if (!IsIdempotent(IID)) 02948 return 0; 02949 02950 // Unary Ops 02951 if (std::distance(ArgBegin, ArgEnd) == 1) 02952 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) 02953 if (II->getIntrinsicID() == IID) 02954 return II; 02955 02956 return 0; 02957 } 02958 02959 template <typename IterTy> 02960 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd, 02961 const Query &Q, unsigned MaxRecurse) { 02962 Type *Ty = V->getType(); 02963 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 02964 Ty = PTy->getElementType(); 02965 FunctionType *FTy = cast<FunctionType>(Ty); 02966 02967 // call undef -> undef 02968 if (isa<UndefValue>(V)) 02969 return UndefValue::get(FTy->getReturnType()); 02970 02971 Function *F = dyn_cast<Function>(V); 02972 if (!F) 02973 return 0; 02974 02975 if (unsigned IID = F->getIntrinsicID()) 02976 if (Value *Ret = 02977 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse)) 02978 return Ret; 02979 02980 if (!canConstantFoldCallTo(F)) 02981 return 0; 02982 02983 SmallVector<Constant *, 4> ConstantArgs; 02984 ConstantArgs.reserve(ArgEnd - ArgBegin); 02985 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) { 02986 Constant *C = dyn_cast<Constant>(*I); 02987 if (!C) 02988 return 0; 02989 ConstantArgs.push_back(C); 02990 } 02991 02992 return ConstantFoldCall(F, ConstantArgs, Q.TLI); 02993 } 02994 02995 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin, 02996 User::op_iterator ArgEnd, const DataLayout *TD, 02997 const TargetLibraryInfo *TLI, 02998 const DominatorTree *DT) { 02999 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT), 03000 RecursionLimit); 03001 } 03002 03003 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args, 03004 const DataLayout *TD, const TargetLibraryInfo *TLI, 03005 const DominatorTree *DT) { 03006 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT), 03007 RecursionLimit); 03008 } 03009 03010 /// SimplifyInstruction - See if we can compute a simplified version of this 03011 /// instruction. If not, this returns null. 03012 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD, 03013 const TargetLibraryInfo *TLI, 03014 const DominatorTree *DT) { 03015 Value *Result; 03016 03017 switch (I->getOpcode()) { 03018 default: 03019 Result = ConstantFoldInstruction(I, TD, TLI); 03020 break; 03021 case Instruction::FAdd: 03022 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), 03023 I->getFastMathFlags(), TD, TLI, DT); 03024 break; 03025 case Instruction::Add: 03026 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1), 03027 cast<BinaryOperator>(I)->hasNoSignedWrap(), 03028 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 03029 TD, TLI, DT); 03030 break; 03031 case Instruction::FSub: 03032 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), 03033 I->getFastMathFlags(), TD, TLI, DT); 03034 break; 03035 case Instruction::Sub: 03036 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1), 03037 cast<BinaryOperator>(I)->hasNoSignedWrap(), 03038 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 03039 TD, TLI, DT); 03040 break; 03041 case Instruction::FMul: 03042 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), 03043 I->getFastMathFlags(), TD, TLI, DT); 03044 break; 03045 case Instruction::Mul: 03046 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03047 break; 03048 case Instruction::SDiv: 03049 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03050 break; 03051 case Instruction::UDiv: 03052 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03053 break; 03054 case Instruction::FDiv: 03055 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03056 break; 03057 case Instruction::SRem: 03058 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03059 break; 03060 case Instruction::URem: 03061 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03062 break; 03063 case Instruction::FRem: 03064 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03065 break; 03066 case Instruction::Shl: 03067 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), 03068 cast<BinaryOperator>(I)->hasNoSignedWrap(), 03069 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 03070 TD, TLI, DT); 03071 break; 03072 case Instruction::LShr: 03073 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), 03074 cast<BinaryOperator>(I)->isExact(), 03075 TD, TLI, DT); 03076 break; 03077 case Instruction::AShr: 03078 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), 03079 cast<BinaryOperator>(I)->isExact(), 03080 TD, TLI, DT); 03081 break; 03082 case Instruction::And: 03083 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03084 break; 03085 case Instruction::Or: 03086 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03087 break; 03088 case Instruction::Xor: 03089 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03090 break; 03091 case Instruction::ICmp: 03092 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), 03093 I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03094 break; 03095 case Instruction::FCmp: 03096 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), 03097 I->getOperand(0), I->getOperand(1), TD, TLI, DT); 03098 break; 03099 case Instruction::Select: 03100 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), 03101 I->getOperand(2), TD, TLI, DT); 03102 break; 03103 case Instruction::GetElementPtr: { 03104 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end()); 03105 Result = SimplifyGEPInst(Ops, TD, TLI, DT); 03106 break; 03107 } 03108 case Instruction::InsertValue: { 03109 InsertValueInst *IV = cast<InsertValueInst>(I); 03110 Result = SimplifyInsertValueInst(IV->getAggregateOperand(), 03111 IV->getInsertedValueOperand(), 03112 IV->getIndices(), TD, TLI, DT); 03113 break; 03114 } 03115 case Instruction::PHI: 03116 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT)); 03117 break; 03118 case Instruction::Call: { 03119 CallSite CS(cast<CallInst>(I)); 03120 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), 03121 TD, TLI, DT); 03122 break; 03123 } 03124 case Instruction::Trunc: 03125 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT); 03126 break; 03127 } 03128 03129 /// If called on unreachable code, the above logic may report that the 03130 /// instruction simplified to itself. Make life easier for users by 03131 /// detecting that case here, returning a safe value instead. 03132 return Result == I ? UndefValue::get(I->getType()) : Result; 03133 } 03134 03135 /// \brief Implementation of recursive simplification through an instructions 03136 /// uses. 03137 /// 03138 /// This is the common implementation of the recursive simplification routines. 03139 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 03140 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 03141 /// instructions to process and attempt to simplify it using 03142 /// InstructionSimplify. 03143 /// 03144 /// This routine returns 'true' only when *it* simplifies something. The passed 03145 /// in simplified value does not count toward this. 03146 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, 03147 const DataLayout *TD, 03148 const TargetLibraryInfo *TLI, 03149 const DominatorTree *DT) { 03150 bool Simplified = false; 03151 SmallSetVector<Instruction *, 8> Worklist; 03152 03153 // If we have an explicit value to collapse to, do that round of the 03154 // simplification loop by hand initially. 03155 if (SimpleV) { 03156 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; 03157 ++UI) 03158 if (*UI != I) 03159 Worklist.insert(cast<Instruction>(*UI)); 03160 03161 // Replace the instruction with its simplified value. 03162 I->replaceAllUsesWith(SimpleV); 03163 03164 // Gracefully handle edge cases where the instruction is not wired into any 03165 // parent block. 03166 if (I->getParent()) 03167 I->eraseFromParent(); 03168 } else { 03169 Worklist.insert(I); 03170 } 03171 03172 // Note that we must test the size on each iteration, the worklist can grow. 03173 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 03174 I = Worklist[Idx]; 03175 03176 // See if this instruction simplifies. 03177 SimpleV = SimplifyInstruction(I, TD, TLI, DT); 03178 if (!SimpleV) 03179 continue; 03180 03181 Simplified = true; 03182 03183 // Stash away all the uses of the old instruction so we can check them for 03184 // recursive simplifications after a RAUW. This is cheaper than checking all 03185 // uses of To on the recursive step in most cases. 03186 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; 03187 ++UI) 03188 Worklist.insert(cast<Instruction>(*UI)); 03189 03190 // Replace the instruction with its simplified value. 03191 I->replaceAllUsesWith(SimpleV); 03192 03193 // Gracefully handle edge cases where the instruction is not wired into any 03194 // parent block. 03195 if (I->getParent()) 03196 I->eraseFromParent(); 03197 } 03198 return Simplified; 03199 } 03200 03201 bool llvm::recursivelySimplifyInstruction(Instruction *I, 03202 const DataLayout *TD, 03203 const TargetLibraryInfo *TLI, 03204 const DominatorTree *DT) { 03205 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT); 03206 } 03207 03208 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, 03209 const DataLayout *TD, 03210 const TargetLibraryInfo *TLI, 03211 const DominatorTree *DT) { 03212 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 03213 assert(SimpleV && "Must provide a simplified value."); 03214 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT); 03215 }