InstructionCombining.cpp revision f2a97ed13d8aa23fab6d141b3c633e6ae513233e
1//===- InstructionCombining.cpp - Combine multiple instructions -----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// InstructionCombining - Combine instructions to form fewer, simple 11// instructions. This pass does not modify the CFG. This pass is where 12// algebraic simplification happens. 13// 14// This pass combines things like: 15// %Y = add i32 %X, 1 16// %Z = add i32 %Y, 1 17// into: 18// %Z = add i32 %X, 2 19// 20// This is a simple worklist driven algorithm. 21// 22// This pass guarantees that the following canonicalizations are performed on 23// the program: 24// 1. If a binary operator has a constant operand, it is moved to the RHS 25// 2. Bitwise operators with constant operands are always grouped so that 26// shifts are performed first, then or's, then and's, then xor's. 27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible 28// 4. All cmp instructions on boolean values are replaced with logical ops 29// 5. add X, X is represented as (X*2) => (X << 1) 30// 6. Multiplies with a power-of-two constant argument are transformed into 31// shifts. 32// ... etc. 33// 34//===----------------------------------------------------------------------===// 35 36#define DEBUG_TYPE "instcombine" 37#include "llvm/Transforms/Scalar.h" 38#include "InstCombine.h" 39#include "llvm/IntrinsicInst.h" 40#include "llvm/Analysis/ConstantFolding.h" 41#include "llvm/Analysis/InstructionSimplify.h" 42#include "llvm/Analysis/MemoryBuiltins.h" 43#include "llvm/Target/TargetData.h" 44#include "llvm/Transforms/Utils/Local.h" 45#include "llvm/Support/CFG.h" 46#include "llvm/Support/Debug.h" 47#include "llvm/Support/GetElementPtrTypeIterator.h" 48#include "llvm/Support/PatternMatch.h" 49#include "llvm/ADT/SmallPtrSet.h" 50#include "llvm/ADT/Statistic.h" 51#include "llvm-c/Initialization.h" 52#include <algorithm> 53#include <climits> 54using namespace llvm; 55using namespace llvm::PatternMatch; 56 57STATISTIC(NumCombined , "Number of insts combined"); 58STATISTIC(NumConstProp, "Number of constant folds"); 59STATISTIC(NumDeadInst , "Number of dead inst eliminated"); 60STATISTIC(NumSunkInst , "Number of instructions sunk"); 61 62// Initialization Routines 63void llvm::initializeInstCombine(PassRegistry &Registry) { 64 initializeInstCombinerPass(Registry); 65} 66 67void LLVMInitializeInstCombine(LLVMPassRegistryRef R) { 68 initializeInstCombine(*unwrap(R)); 69} 70 71char InstCombiner::ID = 0; 72INITIALIZE_PASS(InstCombiner, "instcombine", 73 "Combine redundant instructions", false, false) 74 75void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const { 76 AU.addPreservedID(LCSSAID); 77 AU.setPreservesCFG(); 78} 79 80 81/// ShouldChangeType - Return true if it is desirable to convert a computation 82/// from 'From' to 'To'. We don't want to convert from a legal to an illegal 83/// type for example, or from a smaller to a larger illegal type. 84bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const { 85 assert(From->isIntegerTy() && To->isIntegerTy()); 86 87 // If we don't have TD, we don't know if the source/dest are legal. 88 if (!TD) return false; 89 90 unsigned FromWidth = From->getPrimitiveSizeInBits(); 91 unsigned ToWidth = To->getPrimitiveSizeInBits(); 92 bool FromLegal = TD->isLegalInteger(FromWidth); 93 bool ToLegal = TD->isLegalInteger(ToWidth); 94 95 // If this is a legal integer from type, and the result would be an illegal 96 // type, don't do the transformation. 97 if (FromLegal && !ToLegal) 98 return false; 99 100 // Otherwise, if both are illegal, do not increase the size of the result. We 101 // do allow things like i160 -> i64, but not i64 -> i160. 102 if (!FromLegal && !ToLegal && ToWidth > FromWidth) 103 return false; 104 105 return true; 106} 107 108 109/// SimplifyAssociativeOrCommutative - This performs a few simplifications for 110/// operators which are associative or commutative: 111// 112// Commutative operators: 113// 114// 1. Order operands such that they are listed from right (least complex) to 115// left (most complex). This puts constants before unary operators before 116// binary operators. 117// 118// Associative operators: 119// 120// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 121// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 122// 123// Associative and commutative operators: 124// 125// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 126// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 127// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 128// if C1 and C2 are constants. 129// 130bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) { 131 Instruction::BinaryOps Opcode = I.getOpcode(); 132 bool Changed = false; 133 134 do { 135 // Order operands such that they are listed from right (least complex) to 136 // left (most complex). This puts constants before unary operators before 137 // binary operators. 138 if (I.isCommutative() && getComplexity(I.getOperand(0)) < 139 getComplexity(I.getOperand(1))) 140 Changed = !I.swapOperands(); 141 142 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 143 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 144 145 if (I.isAssociative()) { 146 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies. 147 if (Op0 && Op0->getOpcode() == Opcode) { 148 Value *A = Op0->getOperand(0); 149 Value *B = Op0->getOperand(1); 150 Value *C = I.getOperand(1); 151 152 // Does "B op C" simplify? 153 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) { 154 // It simplifies to V. Form "A op V". 155 I.setOperand(0, A); 156 I.setOperand(1, V); 157 Changed = true; 158 continue; 159 } 160 } 161 162 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies. 163 if (Op1 && Op1->getOpcode() == Opcode) { 164 Value *A = I.getOperand(0); 165 Value *B = Op1->getOperand(0); 166 Value *C = Op1->getOperand(1); 167 168 // Does "A op B" simplify? 169 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) { 170 // It simplifies to V. Form "V op C". 171 I.setOperand(0, V); 172 I.setOperand(1, C); 173 Changed = true; 174 continue; 175 } 176 } 177 } 178 179 if (I.isAssociative() && I.isCommutative()) { 180 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies. 181 if (Op0 && Op0->getOpcode() == Opcode) { 182 Value *A = Op0->getOperand(0); 183 Value *B = Op0->getOperand(1); 184 Value *C = I.getOperand(1); 185 186 // Does "C op A" simplify? 187 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 188 // It simplifies to V. Form "V op B". 189 I.setOperand(0, V); 190 I.setOperand(1, B); 191 Changed = true; 192 continue; 193 } 194 } 195 196 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies. 197 if (Op1 && Op1->getOpcode() == Opcode) { 198 Value *A = I.getOperand(0); 199 Value *B = Op1->getOperand(0); 200 Value *C = Op1->getOperand(1); 201 202 // Does "C op A" simplify? 203 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) { 204 // It simplifies to V. Form "B op V". 205 I.setOperand(0, B); 206 I.setOperand(1, V); 207 Changed = true; 208 continue; 209 } 210 } 211 212 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)" 213 // if C1 and C2 are constants. 214 if (Op0 && Op1 && 215 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode && 216 isa<Constant>(Op0->getOperand(1)) && 217 isa<Constant>(Op1->getOperand(1)) && 218 Op0->hasOneUse() && Op1->hasOneUse()) { 219 Value *A = Op0->getOperand(0); 220 Constant *C1 = cast<Constant>(Op0->getOperand(1)); 221 Value *B = Op1->getOperand(0); 222 Constant *C2 = cast<Constant>(Op1->getOperand(1)); 223 224 Constant *Folded = ConstantExpr::get(Opcode, C1, C2); 225 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(), 226 &I); 227 Worklist.Add(New); 228 I.setOperand(0, New); 229 I.setOperand(1, Folded); 230 Changed = true; 231 continue; 232 } 233 } 234 235 // No further simplifications. 236 return Changed; 237 } while (1); 238} 239 240/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to 241/// "(X LOp Y) ROp (X LOp Z)". 242static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, 243 Instruction::BinaryOps ROp) { 244 switch (LOp) { 245 default: 246 return false; 247 248 case Instruction::And: 249 // And distributes over Or and Xor. 250 switch (ROp) { 251 default: 252 return false; 253 case Instruction::Or: 254 case Instruction::Xor: 255 return true; 256 } 257 258 case Instruction::Mul: 259 // Multiplication distributes over addition and subtraction. 260 switch (ROp) { 261 default: 262 return false; 263 case Instruction::Add: 264 case Instruction::Sub: 265 return true; 266 } 267 268 case Instruction::Or: 269 // Or distributes over And. 270 switch (ROp) { 271 default: 272 return false; 273 case Instruction::And: 274 return true; 275 } 276 } 277} 278 279/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to 280/// "(X ROp Z) LOp (Y ROp Z)". 281static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, 282 Instruction::BinaryOps ROp) { 283 if (Instruction::isCommutative(ROp)) 284 return LeftDistributesOverRight(ROp, LOp); 285 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z", 286 // but this requires knowing that the addition does not overflow and other 287 // such subtleties. 288 return false; 289} 290 291/// SimplifyByFactorizing - This tries to simplify binary operations which 292/// some other binary operation distributes over by factorizing out a common 293/// term (eg "(A*B)+(A*C)" -> "A*(B+C)"). Returns the simplified value, or 294/// null if no simplification was performed. 295Instruction *InstCombiner::SimplifyByFactorizing(BinaryOperator &I) { 296 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0)); 297 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)); 298 if (!Op0 || !Op1 || Op0->getOpcode() != Op1->getOpcode()) 299 return 0; 300 301 // The instruction has the form "(A op' B) op (C op' D)". 302 Value *A = Op0->getOperand(0); Value *B = Op0->getOperand(1); 303 Value *C = Op1->getOperand(0); Value *D = Op1->getOperand(1); 304 Instruction::BinaryOps OuterOpcode = I.getOpcode(); // op 305 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op' 306 307 // Does "X op' Y" always equal "Y op' X"? 308 bool InnerCommutative = Instruction::isCommutative(InnerOpcode); 309 310 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"? 311 if (LeftDistributesOverRight(InnerOpcode, OuterOpcode)) 312 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 313 // commutative case, "(A op' B) op (C op' A)"? 314 if (A == C || (InnerCommutative && A == D)) { 315 if (A != C) 316 std::swap(C, D); 317 // Consider forming "A op' (B op D)". 318 // If "B op D" simplifies then it can be formed with no cost. 319 Value *RHS = SimplifyBinOp(OuterOpcode, B, D, TD); 320 // If "B op D" doesn't simplify then only proceed if both of the existing 321 // operations "A op' B" and "C op' D" will be zapped since no longer used. 322 if (!RHS && Op0->hasOneUse() && Op1->hasOneUse()) 323 RHS = Builder->CreateBinOp(OuterOpcode, B, D, Op1->getName()); 324 if (RHS) 325 return BinaryOperator::Create(InnerOpcode, A, RHS); 326 } 327 328 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"? 329 if (RightDistributesOverLeft(OuterOpcode, InnerOpcode)) 330 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 331 // commutative case, "(A op' B) op (B op' D)"? 332 if (B == D || (InnerCommutative && B == C)) { 333 if (B != D) 334 std::swap(C, D); 335 // Consider forming "(A op C) op' B". 336 // If "A op C" simplifies then it can be formed with no cost. 337 Value *LHS = SimplifyBinOp(OuterOpcode, A, C, TD); 338 // If "A op C" doesn't simplify then only proceed if both of the existing 339 // operations "A op' B" and "C op' D" will be zapped since no longer used. 340 if (!LHS && Op0->hasOneUse() && Op1->hasOneUse()) 341 LHS = Builder->CreateBinOp(OuterOpcode, A, C, Op0->getName()); 342 if (LHS) 343 return BinaryOperator::Create(InnerOpcode, LHS, B); 344 } 345 346 return 0; 347} 348 349// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction 350// if the LHS is a constant zero (which is the 'negate' form). 351// 352Value *InstCombiner::dyn_castNegVal(Value *V) const { 353 if (BinaryOperator::isNeg(V)) 354 return BinaryOperator::getNegArgument(V); 355 356 // Constants can be considered to be negated values if they can be folded. 357 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) 358 return ConstantExpr::getNeg(C); 359 360 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) 361 if (C->getType()->getElementType()->isIntegerTy()) 362 return ConstantExpr::getNeg(C); 363 364 return 0; 365} 366 367// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the 368// instruction if the LHS is a constant negative zero (which is the 'negate' 369// form). 370// 371Value *InstCombiner::dyn_castFNegVal(Value *V) const { 372 if (BinaryOperator::isFNeg(V)) 373 return BinaryOperator::getFNegArgument(V); 374 375 // Constants can be considered to be negated values if they can be folded. 376 if (ConstantFP *C = dyn_cast<ConstantFP>(V)) 377 return ConstantExpr::getFNeg(C); 378 379 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) 380 if (C->getType()->getElementType()->isFloatingPointTy()) 381 return ConstantExpr::getFNeg(C); 382 383 return 0; 384} 385 386static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO, 387 InstCombiner *IC) { 388 if (CastInst *CI = dyn_cast<CastInst>(&I)) 389 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType()); 390 391 // Figure out if the constant is the left or the right argument. 392 bool ConstIsRHS = isa<Constant>(I.getOperand(1)); 393 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS)); 394 395 if (Constant *SOC = dyn_cast<Constant>(SO)) { 396 if (ConstIsRHS) 397 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand); 398 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC); 399 } 400 401 Value *Op0 = SO, *Op1 = ConstOperand; 402 if (!ConstIsRHS) 403 std::swap(Op0, Op1); 404 405 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 406 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1, 407 SO->getName()+".op"); 408 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I)) 409 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 410 SO->getName()+".cmp"); 411 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I)) 412 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1, 413 SO->getName()+".cmp"); 414 llvm_unreachable("Unknown binary instruction type!"); 415} 416 417// FoldOpIntoSelect - Given an instruction with a select as one operand and a 418// constant as the other operand, try to fold the binary operator into the 419// select arguments. This also works for Cast instructions, which obviously do 420// not have a second operand. 421Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) { 422 // Don't modify shared select instructions 423 if (!SI->hasOneUse()) return 0; 424 Value *TV = SI->getOperand(1); 425 Value *FV = SI->getOperand(2); 426 427 if (isa<Constant>(TV) || isa<Constant>(FV)) { 428 // Bool selects with constant operands can be folded to logical ops. 429 if (SI->getType()->isIntegerTy(1)) return 0; 430 431 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this); 432 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this); 433 434 return SelectInst::Create(SI->getCondition(), SelectTrueVal, 435 SelectFalseVal); 436 } 437 return 0; 438} 439 440 441/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which 442/// has a PHI node as operand #0, see if we can fold the instruction into the 443/// PHI (which is only possible if all operands to the PHI are constants). 444/// 445/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms 446/// that would normally be unprofitable because they strongly encourage jump 447/// threading. 448Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I, 449 bool AllowAggressive) { 450 AllowAggressive = false; 451 PHINode *PN = cast<PHINode>(I.getOperand(0)); 452 unsigned NumPHIValues = PN->getNumIncomingValues(); 453 if (NumPHIValues == 0 || 454 // We normally only transform phis with a single use, unless we're trying 455 // hard to make jump threading happen. 456 (!PN->hasOneUse() && !AllowAggressive)) 457 return 0; 458 459 460 // Check to see if all of the operands of the PHI are simple constants 461 // (constantint/constantfp/undef). If there is one non-constant value, 462 // remember the BB it is in. If there is more than one or if *it* is a PHI, 463 // bail out. We don't do arbitrary constant expressions here because moving 464 // their computation can be expensive without a cost model. 465 BasicBlock *NonConstBB = 0; 466 for (unsigned i = 0; i != NumPHIValues; ++i) 467 if (!isa<Constant>(PN->getIncomingValue(i)) || 468 isa<ConstantExpr>(PN->getIncomingValue(i))) { 469 if (NonConstBB) return 0; // More than one non-const value. 470 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi. 471 NonConstBB = PN->getIncomingBlock(i); 472 473 // If the incoming non-constant value is in I's block, we have an infinite 474 // loop. 475 if (NonConstBB == I.getParent()) 476 return 0; 477 } 478 479 // If there is exactly one non-constant value, we can insert a copy of the 480 // operation in that block. However, if this is a critical edge, we would be 481 // inserting the computation one some other paths (e.g. inside a loop). Only 482 // do this if the pred block is unconditionally branching into the phi block. 483 if (NonConstBB != 0 && !AllowAggressive) { 484 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator()); 485 if (!BI || !BI->isUnconditional()) return 0; 486 } 487 488 // Okay, we can do the transformation: create the new PHI node. 489 PHINode *NewPN = PHINode::Create(I.getType(), ""); 490 NewPN->reserveOperandSpace(PN->getNumOperands()/2); 491 InsertNewInstBefore(NewPN, *PN); 492 NewPN->takeName(PN); 493 494 // Next, add all of the operands to the PHI. 495 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) { 496 // We only currently try to fold the condition of a select when it is a phi, 497 // not the true/false values. 498 Value *TrueV = SI->getTrueValue(); 499 Value *FalseV = SI->getFalseValue(); 500 BasicBlock *PhiTransBB = PN->getParent(); 501 for (unsigned i = 0; i != NumPHIValues; ++i) { 502 BasicBlock *ThisBB = PN->getIncomingBlock(i); 503 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB); 504 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB); 505 Value *InV = 0; 506 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 507 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred; 508 } else { 509 assert(PN->getIncomingBlock(i) == NonConstBB); 510 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred, 511 FalseVInPred, 512 "phitmp", NonConstBB->getTerminator()); 513 Worklist.Add(cast<Instruction>(InV)); 514 } 515 NewPN->addIncoming(InV, ThisBB); 516 } 517 } else if (I.getNumOperands() == 2) { 518 Constant *C = cast<Constant>(I.getOperand(1)); 519 for (unsigned i = 0; i != NumPHIValues; ++i) { 520 Value *InV = 0; 521 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 522 if (CmpInst *CI = dyn_cast<CmpInst>(&I)) 523 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C); 524 else 525 InV = ConstantExpr::get(I.getOpcode(), InC, C); 526 } else { 527 assert(PN->getIncomingBlock(i) == NonConstBB); 528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 529 InV = BinaryOperator::Create(BO->getOpcode(), 530 PN->getIncomingValue(i), C, "phitmp", 531 NonConstBB->getTerminator()); 532 else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) 533 InV = CmpInst::Create(CI->getOpcode(), 534 CI->getPredicate(), 535 PN->getIncomingValue(i), C, "phitmp", 536 NonConstBB->getTerminator()); 537 else 538 llvm_unreachable("Unknown binop!"); 539 540 Worklist.Add(cast<Instruction>(InV)); 541 } 542 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 543 } 544 } else { 545 CastInst *CI = cast<CastInst>(&I); 546 const Type *RetTy = CI->getType(); 547 for (unsigned i = 0; i != NumPHIValues; ++i) { 548 Value *InV; 549 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) { 550 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy); 551 } else { 552 assert(PN->getIncomingBlock(i) == NonConstBB); 553 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 554 I.getType(), "phitmp", 555 NonConstBB->getTerminator()); 556 Worklist.Add(cast<Instruction>(InV)); 557 } 558 NewPN->addIncoming(InV, PN->getIncomingBlock(i)); 559 } 560 } 561 return ReplaceInstUsesWith(I, NewPN); 562} 563 564/// FindElementAtOffset - Given a type and a constant offset, determine whether 565/// or not there is a sequence of GEP indices into the type that will land us at 566/// the specified offset. If so, fill them into NewIndices and return the 567/// resultant element type, otherwise return null. 568const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset, 569 SmallVectorImpl<Value*> &NewIndices) { 570 if (!TD) return 0; 571 if (!Ty->isSized()) return 0; 572 573 // Start with the index over the outer type. Note that the type size 574 // might be zero (even if the offset isn't zero) if the indexed type 575 // is something like [0 x {int, int}] 576 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext()); 577 int64_t FirstIdx = 0; 578 if (int64_t TySize = TD->getTypeAllocSize(Ty)) { 579 FirstIdx = Offset/TySize; 580 Offset -= FirstIdx*TySize; 581 582 // Handle hosts where % returns negative instead of values [0..TySize). 583 if (Offset < 0) { 584 --FirstIdx; 585 Offset += TySize; 586 assert(Offset >= 0); 587 } 588 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset"); 589 } 590 591 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx)); 592 593 // Index into the types. If we fail, set OrigBase to null. 594 while (Offset) { 595 // Indexing into tail padding between struct/array elements. 596 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty)) 597 return 0; 598 599 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 600 const StructLayout *SL = TD->getStructLayout(STy); 601 assert(Offset < (int64_t)SL->getSizeInBytes() && 602 "Offset must stay within the indexed type"); 603 604 unsigned Elt = SL->getElementContainingOffset(Offset); 605 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 606 Elt)); 607 608 Offset -= SL->getElementOffset(Elt); 609 Ty = STy->getElementType(Elt); 610 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 611 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType()); 612 assert(EltSize && "Cannot index into a zero-sized array"); 613 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize)); 614 Offset %= EltSize; 615 Ty = AT->getElementType(); 616 } else { 617 // Otherwise, we can't index into the middle of this atomic type, bail. 618 return 0; 619 } 620 } 621 622 return Ty; 623} 624 625 626 627Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) { 628 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end()); 629 630 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD)) 631 return ReplaceInstUsesWith(GEP, V); 632 633 Value *PtrOp = GEP.getOperand(0); 634 635 // Eliminate unneeded casts for indices, and replace indices which displace 636 // by multiples of a zero size type with zero. 637 if (TD) { 638 bool MadeChange = false; 639 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext()); 640 641 gep_type_iterator GTI = gep_type_begin(GEP); 642 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); 643 I != E; ++I, ++GTI) { 644 // Skip indices into struct types. 645 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI); 646 if (!SeqTy) continue; 647 648 // If the element type has zero size then any index over it is equivalent 649 // to an index of zero, so replace it with zero if it is not zero already. 650 if (SeqTy->getElementType()->isSized() && 651 TD->getTypeAllocSize(SeqTy->getElementType()) == 0) 652 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) { 653 *I = Constant::getNullValue(IntPtrTy); 654 MadeChange = true; 655 } 656 657 if ((*I)->getType() != IntPtrTy) { 658 // If we are using a wider index than needed for this platform, shrink 659 // it to what we need. If narrower, sign-extend it to what we need. 660 // This explicit cast can make subsequent optimizations more obvious. 661 *I = Builder->CreateIntCast(*I, IntPtrTy, true); 662 MadeChange = true; 663 } 664 } 665 if (MadeChange) return &GEP; 666 } 667 668 // Combine Indices - If the source pointer to this getelementptr instruction 669 // is a getelementptr instruction, combine the indices of the two 670 // getelementptr instructions into a single instruction. 671 // 672 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) { 673 // Note that if our source is a gep chain itself that we wait for that 674 // chain to be resolved before we perform this transformation. This 675 // avoids us creating a TON of code in some cases. 676 // 677 if (GetElementPtrInst *SrcGEP = 678 dyn_cast<GetElementPtrInst>(Src->getOperand(0))) 679 if (SrcGEP->getNumOperands() == 2) 680 return 0; // Wait until our source is folded to completion. 681 682 SmallVector<Value*, 8> Indices; 683 684 // Find out whether the last index in the source GEP is a sequential idx. 685 bool EndsWithSequential = false; 686 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src); 687 I != E; ++I) 688 EndsWithSequential = !(*I)->isStructTy(); 689 690 // Can we combine the two pointer arithmetics offsets? 691 if (EndsWithSequential) { 692 // Replace: gep (gep %P, long B), long A, ... 693 // With: T = long A+B; gep %P, T, ... 694 // 695 Value *Sum; 696 Value *SO1 = Src->getOperand(Src->getNumOperands()-1); 697 Value *GO1 = GEP.getOperand(1); 698 if (SO1 == Constant::getNullValue(SO1->getType())) { 699 Sum = GO1; 700 } else if (GO1 == Constant::getNullValue(GO1->getType())) { 701 Sum = SO1; 702 } else { 703 // If they aren't the same type, then the input hasn't been processed 704 // by the loop above yet (which canonicalizes sequential index types to 705 // intptr_t). Just avoid transforming this until the input has been 706 // normalized. 707 if (SO1->getType() != GO1->getType()) 708 return 0; 709 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum"); 710 } 711 712 // Update the GEP in place if possible. 713 if (Src->getNumOperands() == 2) { 714 GEP.setOperand(0, Src->getOperand(0)); 715 GEP.setOperand(1, Sum); 716 return &GEP; 717 } 718 Indices.append(Src->op_begin()+1, Src->op_end()-1); 719 Indices.push_back(Sum); 720 Indices.append(GEP.op_begin()+2, GEP.op_end()); 721 } else if (isa<Constant>(*GEP.idx_begin()) && 722 cast<Constant>(*GEP.idx_begin())->isNullValue() && 723 Src->getNumOperands() != 1) { 724 // Otherwise we can do the fold if the first index of the GEP is a zero 725 Indices.append(Src->op_begin()+1, Src->op_end()); 726 Indices.append(GEP.idx_begin()+1, GEP.idx_end()); 727 } 728 729 if (!Indices.empty()) 730 return (GEP.isInBounds() && Src->isInBounds()) ? 731 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(), 732 Indices.end(), GEP.getName()) : 733 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(), 734 Indices.end(), GEP.getName()); 735 } 736 737 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0). 738 Value *StrippedPtr = PtrOp->stripPointerCasts(); 739 if (StrippedPtr != PtrOp) { 740 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType()); 741 742 bool HasZeroPointerIndex = false; 743 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1))) 744 HasZeroPointerIndex = C->isZero(); 745 746 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... 747 // into : GEP [10 x i8]* X, i32 0, ... 748 // 749 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ... 750 // into : GEP i8* X, ... 751 // 752 // This occurs when the program declares an array extern like "int X[];" 753 if (HasZeroPointerIndex) { 754 const PointerType *CPTy = cast<PointerType>(PtrOp->getType()); 755 if (const ArrayType *CATy = 756 dyn_cast<ArrayType>(CPTy->getElementType())) { 757 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ? 758 if (CATy->getElementType() == StrippedPtrTy->getElementType()) { 759 // -> GEP i8* X, ... 760 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end()); 761 GetElementPtrInst *Res = 762 GetElementPtrInst::Create(StrippedPtr, Idx.begin(), 763 Idx.end(), GEP.getName()); 764 Res->setIsInBounds(GEP.isInBounds()); 765 return Res; 766 } 767 768 if (const ArrayType *XATy = 769 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){ 770 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ? 771 if (CATy->getElementType() == XATy->getElementType()) { 772 // -> GEP [10 x i8]* X, i32 0, ... 773 // At this point, we know that the cast source type is a pointer 774 // to an array of the same type as the destination pointer 775 // array. Because the array type is never stepped over (there 776 // is a leading zero) we can fold the cast into this GEP. 777 GEP.setOperand(0, StrippedPtr); 778 return &GEP; 779 } 780 } 781 } 782 } else if (GEP.getNumOperands() == 2) { 783 // Transform things like: 784 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V 785 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast 786 const Type *SrcElTy = StrippedPtrTy->getElementType(); 787 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType(); 788 if (TD && SrcElTy->isArrayTy() && 789 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) == 790 TD->getTypeAllocSize(ResElTy)) { 791 Value *Idx[2]; 792 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 793 Idx[1] = GEP.getOperand(1); 794 Value *NewGEP = GEP.isInBounds() ? 795 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) : 796 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()); 797 // V and GEP are both pointer types --> BitCast 798 return new BitCastInst(NewGEP, GEP.getType()); 799 } 800 801 // Transform things like: 802 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp 803 // (where tmp = 8*tmp2) into: 804 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast 805 806 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) { 807 uint64_t ArrayEltSize = 808 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()); 809 810 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We 811 // allow either a mul, shift, or constant here. 812 Value *NewIdx = 0; 813 ConstantInt *Scale = 0; 814 if (ArrayEltSize == 1) { 815 NewIdx = GEP.getOperand(1); 816 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1); 817 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) { 818 NewIdx = ConstantInt::get(CI->getType(), 1); 819 Scale = CI; 820 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){ 821 if (Inst->getOpcode() == Instruction::Shl && 822 isa<ConstantInt>(Inst->getOperand(1))) { 823 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1)); 824 uint32_t ShAmtVal = ShAmt->getLimitedValue(64); 825 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()), 826 1ULL << ShAmtVal); 827 NewIdx = Inst->getOperand(0); 828 } else if (Inst->getOpcode() == Instruction::Mul && 829 isa<ConstantInt>(Inst->getOperand(1))) { 830 Scale = cast<ConstantInt>(Inst->getOperand(1)); 831 NewIdx = Inst->getOperand(0); 832 } 833 } 834 835 // If the index will be to exactly the right offset with the scale taken 836 // out, perform the transformation. Note, we don't know whether Scale is 837 // signed or not. We'll use unsigned version of division/modulo 838 // operation after making sure Scale doesn't have the sign bit set. 839 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL && 840 Scale->getZExtValue() % ArrayEltSize == 0) { 841 Scale = ConstantInt::get(Scale->getType(), 842 Scale->getZExtValue() / ArrayEltSize); 843 if (Scale->getZExtValue() != 1) { 844 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(), 845 false /*ZExt*/); 846 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale"); 847 } 848 849 // Insert the new GEP instruction. 850 Value *Idx[2]; 851 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext())); 852 Idx[1] = NewIdx; 853 Value *NewGEP = GEP.isInBounds() ? 854 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()): 855 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()); 856 // The NewGEP must be pointer typed, so must the old one -> BitCast 857 return new BitCastInst(NewGEP, GEP.getType()); 858 } 859 } 860 } 861 } 862 863 /// See if we can simplify: 864 /// X = bitcast A* to B* 865 /// Y = gep X, <...constant indices...> 866 /// into a gep of the original struct. This is important for SROA and alias 867 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged. 868 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) { 869 if (TD && 870 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) { 871 // Determine how much the GEP moves the pointer. We are guaranteed to get 872 // a constant back from EmitGEPOffset. 873 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP)); 874 int64_t Offset = OffsetV->getSExtValue(); 875 876 // If this GEP instruction doesn't move the pointer, just replace the GEP 877 // with a bitcast of the real input to the dest type. 878 if (Offset == 0) { 879 // If the bitcast is of an allocation, and the allocation will be 880 // converted to match the type of the cast, don't touch this. 881 if (isa<AllocaInst>(BCI->getOperand(0)) || 882 isMalloc(BCI->getOperand(0))) { 883 // See if the bitcast simplifies, if so, don't nuke this GEP yet. 884 if (Instruction *I = visitBitCast(*BCI)) { 885 if (I != BCI) { 886 I->takeName(BCI); 887 BCI->getParent()->getInstList().insert(BCI, I); 888 ReplaceInstUsesWith(*BCI, I); 889 } 890 return &GEP; 891 } 892 } 893 return new BitCastInst(BCI->getOperand(0), GEP.getType()); 894 } 895 896 // Otherwise, if the offset is non-zero, we need to find out if there is a 897 // field at Offset in 'A's type. If so, we can pull the cast through the 898 // GEP. 899 SmallVector<Value*, 8> NewIndices; 900 const Type *InTy = 901 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType(); 902 if (FindElementAtOffset(InTy, Offset, NewIndices)) { 903 Value *NGEP = GEP.isInBounds() ? 904 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(), 905 NewIndices.end()) : 906 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(), 907 NewIndices.end()); 908 909 if (NGEP->getType() == GEP.getType()) 910 return ReplaceInstUsesWith(GEP, NGEP); 911 NGEP->takeName(&GEP); 912 return new BitCastInst(NGEP, GEP.getType()); 913 } 914 } 915 } 916 917 return 0; 918} 919 920 921 922static bool IsOnlyNullComparedAndFreed(const Value &V) { 923 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end(); 924 UI != UE; ++UI) { 925 const User *U = *UI; 926 if (isFreeCall(U)) 927 continue; 928 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U)) 929 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) 930 continue; 931 return false; 932 } 933 return true; 934} 935 936Instruction *InstCombiner::visitMalloc(Instruction &MI) { 937 // If we have a malloc call which is only used in any amount of comparisons 938 // to null and free calls, delete the calls and replace the comparisons with 939 // true or false as appropriate. 940 if (IsOnlyNullComparedAndFreed(MI)) { 941 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end(); 942 UI != UE;) { 943 // We can assume that every remaining use is a free call or an icmp eq/ne 944 // to null, so the cast is safe. 945 Instruction *I = cast<Instruction>(*UI); 946 947 // Early increment here, as we're about to get rid of the user. 948 ++UI; 949 950 if (isFreeCall(I)) { 951 EraseInstFromFunction(*cast<CallInst>(I)); 952 continue; 953 } 954 // Again, the cast is safe. 955 ICmpInst *C = cast<ICmpInst>(I); 956 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()), 957 C->isFalseWhenEqual())); 958 EraseInstFromFunction(*C); 959 } 960 return EraseInstFromFunction(MI); 961 } 962 return 0; 963} 964 965 966 967Instruction *InstCombiner::visitFree(CallInst &FI) { 968 Value *Op = FI.getArgOperand(0); 969 970 // free undef -> unreachable. 971 if (isa<UndefValue>(Op)) { 972 // Insert a new store to null because we cannot modify the CFG here. 973 new StoreInst(ConstantInt::getTrue(FI.getContext()), 974 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI); 975 return EraseInstFromFunction(FI); 976 } 977 978 // If we have 'free null' delete the instruction. This can happen in stl code 979 // when lots of inlining happens. 980 if (isa<ConstantPointerNull>(Op)) 981 return EraseInstFromFunction(FI); 982 983 return 0; 984} 985 986 987 988Instruction *InstCombiner::visitBranchInst(BranchInst &BI) { 989 // Change br (not X), label True, label False to: br X, label False, True 990 Value *X = 0; 991 BasicBlock *TrueDest; 992 BasicBlock *FalseDest; 993 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) && 994 !isa<Constant>(X)) { 995 // Swap Destinations and condition... 996 BI.setCondition(X); 997 BI.setSuccessor(0, FalseDest); 998 BI.setSuccessor(1, TrueDest); 999 return &BI; 1000 } 1001 1002 // Cannonicalize fcmp_one -> fcmp_oeq 1003 FCmpInst::Predicate FPred; Value *Y; 1004 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 1005 TrueDest, FalseDest)) && 1006 BI.getCondition()->hasOneUse()) 1007 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE || 1008 FPred == FCmpInst::FCMP_OGE) { 1009 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition()); 1010 Cond->setPredicate(FCmpInst::getInversePredicate(FPred)); 1011 1012 // Swap Destinations and condition. 1013 BI.setSuccessor(0, FalseDest); 1014 BI.setSuccessor(1, TrueDest); 1015 Worklist.Add(Cond); 1016 return &BI; 1017 } 1018 1019 // Cannonicalize icmp_ne -> icmp_eq 1020 ICmpInst::Predicate IPred; 1021 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)), 1022 TrueDest, FalseDest)) && 1023 BI.getCondition()->hasOneUse()) 1024 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE || 1025 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE || 1026 IPred == ICmpInst::ICMP_SGE) { 1027 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition()); 1028 Cond->setPredicate(ICmpInst::getInversePredicate(IPred)); 1029 // Swap Destinations and condition. 1030 BI.setSuccessor(0, FalseDest); 1031 BI.setSuccessor(1, TrueDest); 1032 Worklist.Add(Cond); 1033 return &BI; 1034 } 1035 1036 return 0; 1037} 1038 1039Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) { 1040 Value *Cond = SI.getCondition(); 1041 if (Instruction *I = dyn_cast<Instruction>(Cond)) { 1042 if (I->getOpcode() == Instruction::Add) 1043 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) { 1044 // change 'switch (X+4) case 1:' into 'switch (X) case -3' 1045 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) 1046 SI.setOperand(i, 1047 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)), 1048 AddRHS)); 1049 SI.setOperand(0, I->getOperand(0)); 1050 Worklist.Add(I); 1051 return &SI; 1052 } 1053 } 1054 return 0; 1055} 1056 1057Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) { 1058 Value *Agg = EV.getAggregateOperand(); 1059 1060 if (!EV.hasIndices()) 1061 return ReplaceInstUsesWith(EV, Agg); 1062 1063 if (Constant *C = dyn_cast<Constant>(Agg)) { 1064 if (isa<UndefValue>(C)) 1065 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType())); 1066 1067 if (isa<ConstantAggregateZero>(C)) 1068 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType())); 1069 1070 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) { 1071 // Extract the element indexed by the first index out of the constant 1072 Value *V = C->getOperand(*EV.idx_begin()); 1073 if (EV.getNumIndices() > 1) 1074 // Extract the remaining indices out of the constant indexed by the 1075 // first index 1076 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end()); 1077 else 1078 return ReplaceInstUsesWith(EV, V); 1079 } 1080 return 0; // Can't handle other constants 1081 } 1082 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) { 1083 // We're extracting from an insertvalue instruction, compare the indices 1084 const unsigned *exti, *exte, *insi, *inse; 1085 for (exti = EV.idx_begin(), insi = IV->idx_begin(), 1086 exte = EV.idx_end(), inse = IV->idx_end(); 1087 exti != exte && insi != inse; 1088 ++exti, ++insi) { 1089 if (*insi != *exti) 1090 // The insert and extract both reference distinctly different elements. 1091 // This means the extract is not influenced by the insert, and we can 1092 // replace the aggregate operand of the extract with the aggregate 1093 // operand of the insert. i.e., replace 1094 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1095 // %E = extractvalue { i32, { i32 } } %I, 0 1096 // with 1097 // %E = extractvalue { i32, { i32 } } %A, 0 1098 return ExtractValueInst::Create(IV->getAggregateOperand(), 1099 EV.idx_begin(), EV.idx_end()); 1100 } 1101 if (exti == exte && insi == inse) 1102 // Both iterators are at the end: Index lists are identical. Replace 1103 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1104 // %C = extractvalue { i32, { i32 } } %B, 1, 0 1105 // with "i32 42" 1106 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand()); 1107 if (exti == exte) { 1108 // The extract list is a prefix of the insert list. i.e. replace 1109 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0 1110 // %E = extractvalue { i32, { i32 } } %I, 1 1111 // with 1112 // %X = extractvalue { i32, { i32 } } %A, 1 1113 // %E = insertvalue { i32 } %X, i32 42, 0 1114 // by switching the order of the insert and extract (though the 1115 // insertvalue should be left in, since it may have other uses). 1116 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(), 1117 EV.idx_begin(), EV.idx_end()); 1118 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(), 1119 insi, inse); 1120 } 1121 if (insi == inse) 1122 // The insert list is a prefix of the extract list 1123 // We can simply remove the common indices from the extract and make it 1124 // operate on the inserted value instead of the insertvalue result. 1125 // i.e., replace 1126 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1 1127 // %E = extractvalue { i32, { i32 } } %I, 1, 0 1128 // with 1129 // %E extractvalue { i32 } { i32 42 }, 0 1130 return ExtractValueInst::Create(IV->getInsertedValueOperand(), 1131 exti, exte); 1132 } 1133 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) { 1134 // We're extracting from an intrinsic, see if we're the only user, which 1135 // allows us to simplify multiple result intrinsics to simpler things that 1136 // just get one value. 1137 if (II->hasOneUse()) { 1138 // Check if we're grabbing the overflow bit or the result of a 'with 1139 // overflow' intrinsic. If it's the latter we can remove the intrinsic 1140 // and replace it with a traditional binary instruction. 1141 switch (II->getIntrinsicID()) { 1142 case Intrinsic::uadd_with_overflow: 1143 case Intrinsic::sadd_with_overflow: 1144 if (*EV.idx_begin() == 0) { // Normal result. 1145 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1146 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1147 EraseInstFromFunction(*II); 1148 return BinaryOperator::CreateAdd(LHS, RHS); 1149 } 1150 1151 // If the normal result of the add is dead, and the RHS is a constant, 1152 // we can transform this into a range comparison. 1153 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3 1154 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow) 1155 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1))) 1156 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0), 1157 ConstantExpr::getNot(CI)); 1158 break; 1159 case Intrinsic::usub_with_overflow: 1160 case Intrinsic::ssub_with_overflow: 1161 if (*EV.idx_begin() == 0) { // Normal result. 1162 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1163 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1164 EraseInstFromFunction(*II); 1165 return BinaryOperator::CreateSub(LHS, RHS); 1166 } 1167 break; 1168 case Intrinsic::umul_with_overflow: 1169 case Intrinsic::smul_with_overflow: 1170 if (*EV.idx_begin() == 0) { // Normal result. 1171 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 1172 II->replaceAllUsesWith(UndefValue::get(II->getType())); 1173 EraseInstFromFunction(*II); 1174 return BinaryOperator::CreateMul(LHS, RHS); 1175 } 1176 break; 1177 default: 1178 break; 1179 } 1180 } 1181 } 1182 if (LoadInst *L = dyn_cast<LoadInst>(Agg)) 1183 // If the (non-volatile) load only has one use, we can rewrite this to a 1184 // load from a GEP. This reduces the size of the load. 1185 // FIXME: If a load is used only by extractvalue instructions then this 1186 // could be done regardless of having multiple uses. 1187 if (!L->isVolatile() && L->hasOneUse()) { 1188 // extractvalue has integer indices, getelementptr has Value*s. Convert. 1189 SmallVector<Value*, 4> Indices; 1190 // Prefix an i32 0 since we need the first element. 1191 Indices.push_back(Builder->getInt32(0)); 1192 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end(); 1193 I != E; ++I) 1194 Indices.push_back(Builder->getInt32(*I)); 1195 1196 // We need to insert these at the location of the old load, not at that of 1197 // the extractvalue. 1198 Builder->SetInsertPoint(L->getParent(), L); 1199 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), 1200 Indices.begin(), Indices.end()); 1201 // Returning the load directly will cause the main loop to insert it in 1202 // the wrong spot, so use ReplaceInstUsesWith(). 1203 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP)); 1204 } 1205 // We could simplify extracts from other values. Note that nested extracts may 1206 // already be simplified implicitly by the above: extract (extract (insert) ) 1207 // will be translated into extract ( insert ( extract ) ) first and then just 1208 // the value inserted, if appropriate. Similarly for extracts from single-use 1209 // loads: extract (extract (load)) will be translated to extract (load (gep)) 1210 // and if again single-use then via load (gep (gep)) to load (gep). 1211 // However, double extracts from e.g. function arguments or return values 1212 // aren't handled yet. 1213 return 0; 1214} 1215 1216 1217 1218 1219/// TryToSinkInstruction - Try to move the specified instruction from its 1220/// current block into the beginning of DestBlock, which can only happen if it's 1221/// safe to move the instruction past all of the instructions between it and the 1222/// end of its block. 1223static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) { 1224 assert(I->hasOneUse() && "Invariants didn't hold!"); 1225 1226 // Cannot move control-flow-involving, volatile loads, vaarg, etc. 1227 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I)) 1228 return false; 1229 1230 // Do not sink alloca instructions out of the entry block. 1231 if (isa<AllocaInst>(I) && I->getParent() == 1232 &DestBlock->getParent()->getEntryBlock()) 1233 return false; 1234 1235 // We can only sink load instructions if there is nothing between the load and 1236 // the end of block that could change the value. 1237 if (I->mayReadFromMemory()) { 1238 for (BasicBlock::iterator Scan = I, E = I->getParent()->end(); 1239 Scan != E; ++Scan) 1240 if (Scan->mayWriteToMemory()) 1241 return false; 1242 } 1243 1244 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI(); 1245 1246 I->moveBefore(InsertPos); 1247 ++NumSunkInst; 1248 return true; 1249} 1250 1251 1252/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding 1253/// all reachable code to the worklist. 1254/// 1255/// This has a couple of tricks to make the code faster and more powerful. In 1256/// particular, we constant fold and DCE instructions as we go, to avoid adding 1257/// them to the worklist (this significantly speeds up instcombine on code where 1258/// many instructions are dead or constant). Additionally, if we find a branch 1259/// whose condition is a known constant, we only visit the reachable successors. 1260/// 1261static bool AddReachableCodeToWorklist(BasicBlock *BB, 1262 SmallPtrSet<BasicBlock*, 64> &Visited, 1263 InstCombiner &IC, 1264 const TargetData *TD) { 1265 bool MadeIRChange = false; 1266 SmallVector<BasicBlock*, 256> Worklist; 1267 Worklist.push_back(BB); 1268 1269 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist; 1270 SmallPtrSet<ConstantExpr*, 64> FoldedConstants; 1271 1272 do { 1273 BB = Worklist.pop_back_val(); 1274 1275 // We have now visited this block! If we've already been here, ignore it. 1276 if (!Visited.insert(BB)) continue; 1277 1278 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) { 1279 Instruction *Inst = BBI++; 1280 1281 // DCE instruction if trivially dead. 1282 if (isInstructionTriviallyDead(Inst)) { 1283 ++NumDeadInst; 1284 DEBUG(errs() << "IC: DCE: " << *Inst << '\n'); 1285 Inst->eraseFromParent(); 1286 continue; 1287 } 1288 1289 // ConstantProp instruction if trivially constant. 1290 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0))) 1291 if (Constant *C = ConstantFoldInstruction(Inst, TD)) { 1292 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " 1293 << *Inst << '\n'); 1294 Inst->replaceAllUsesWith(C); 1295 ++NumConstProp; 1296 Inst->eraseFromParent(); 1297 continue; 1298 } 1299 1300 if (TD) { 1301 // See if we can constant fold its operands. 1302 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); 1303 i != e; ++i) { 1304 ConstantExpr *CE = dyn_cast<ConstantExpr>(i); 1305 if (CE == 0) continue; 1306 1307 // If we already folded this constant, don't try again. 1308 if (!FoldedConstants.insert(CE)) 1309 continue; 1310 1311 Constant *NewC = ConstantFoldConstantExpression(CE, TD); 1312 if (NewC && NewC != CE) { 1313 *i = NewC; 1314 MadeIRChange = true; 1315 } 1316 } 1317 } 1318 1319 InstrsForInstCombineWorklist.push_back(Inst); 1320 } 1321 1322 // Recursively visit successors. If this is a branch or switch on a 1323 // constant, only visit the reachable successor. 1324 TerminatorInst *TI = BB->getTerminator(); 1325 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 1326 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) { 1327 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue(); 1328 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal); 1329 Worklist.push_back(ReachableBB); 1330 continue; 1331 } 1332 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 1333 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) { 1334 // See if this is an explicit destination. 1335 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) 1336 if (SI->getCaseValue(i) == Cond) { 1337 BasicBlock *ReachableBB = SI->getSuccessor(i); 1338 Worklist.push_back(ReachableBB); 1339 continue; 1340 } 1341 1342 // Otherwise it is the default destination. 1343 Worklist.push_back(SI->getSuccessor(0)); 1344 continue; 1345 } 1346 } 1347 1348 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) 1349 Worklist.push_back(TI->getSuccessor(i)); 1350 } while (!Worklist.empty()); 1351 1352 // Once we've found all of the instructions to add to instcombine's worklist, 1353 // add them in reverse order. This way instcombine will visit from the top 1354 // of the function down. This jives well with the way that it adds all uses 1355 // of instructions to the worklist after doing a transformation, thus avoiding 1356 // some N^2 behavior in pathological cases. 1357 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0], 1358 InstrsForInstCombineWorklist.size()); 1359 1360 return MadeIRChange; 1361} 1362 1363bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) { 1364 MadeIRChange = false; 1365 1366 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on " 1367 << F.getNameStr() << "\n"); 1368 1369 { 1370 // Do a depth-first traversal of the function, populate the worklist with 1371 // the reachable instructions. Ignore blocks that are not reachable. Keep 1372 // track of which blocks we visit. 1373 SmallPtrSet<BasicBlock*, 64> Visited; 1374 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD); 1375 1376 // Do a quick scan over the function. If we find any blocks that are 1377 // unreachable, remove any instructions inside of them. This prevents 1378 // the instcombine code from having to deal with some bad special cases. 1379 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1380 if (!Visited.count(BB)) { 1381 Instruction *Term = BB->getTerminator(); 1382 while (Term != BB->begin()) { // Remove instrs bottom-up 1383 BasicBlock::iterator I = Term; --I; 1384 1385 DEBUG(errs() << "IC: DCE: " << *I << '\n'); 1386 // A debug intrinsic shouldn't force another iteration if we weren't 1387 // going to do one without it. 1388 if (!isa<DbgInfoIntrinsic>(I)) { 1389 ++NumDeadInst; 1390 MadeIRChange = true; 1391 } 1392 1393 // If I is not void type then replaceAllUsesWith undef. 1394 // This allows ValueHandlers and custom metadata to adjust itself. 1395 if (!I->getType()->isVoidTy()) 1396 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1397 I->eraseFromParent(); 1398 } 1399 } 1400 } 1401 1402 while (!Worklist.isEmpty()) { 1403 Instruction *I = Worklist.RemoveOne(); 1404 if (I == 0) continue; // skip null values. 1405 1406 // Check to see if we can DCE the instruction. 1407 if (isInstructionTriviallyDead(I)) { 1408 DEBUG(errs() << "IC: DCE: " << *I << '\n'); 1409 EraseInstFromFunction(*I); 1410 ++NumDeadInst; 1411 MadeIRChange = true; 1412 continue; 1413 } 1414 1415 // Instruction isn't dead, see if we can constant propagate it. 1416 if (!I->use_empty() && isa<Constant>(I->getOperand(0))) 1417 if (Constant *C = ConstantFoldInstruction(I, TD)) { 1418 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n'); 1419 1420 // Add operands to the worklist. 1421 ReplaceInstUsesWith(*I, C); 1422 ++NumConstProp; 1423 EraseInstFromFunction(*I); 1424 MadeIRChange = true; 1425 continue; 1426 } 1427 1428 // See if we can trivially sink this instruction to a successor basic block. 1429 if (I->hasOneUse()) { 1430 BasicBlock *BB = I->getParent(); 1431 Instruction *UserInst = cast<Instruction>(I->use_back()); 1432 BasicBlock *UserParent; 1433 1434 // Get the block the use occurs in. 1435 if (PHINode *PN = dyn_cast<PHINode>(UserInst)) 1436 UserParent = PN->getIncomingBlock(I->use_begin().getUse()); 1437 else 1438 UserParent = UserInst->getParent(); 1439 1440 if (UserParent != BB) { 1441 bool UserIsSuccessor = false; 1442 // See if the user is one of our successors. 1443 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) 1444 if (*SI == UserParent) { 1445 UserIsSuccessor = true; 1446 break; 1447 } 1448 1449 // If the user is one of our immediate successors, and if that successor 1450 // only has us as a predecessors (we'd have to split the critical edge 1451 // otherwise), we can keep going. 1452 if (UserIsSuccessor && UserParent->getSinglePredecessor()) 1453 // Okay, the CFG is simple enough, try to sink this instruction. 1454 MadeIRChange |= TryToSinkInstruction(I, UserParent); 1455 } 1456 } 1457 1458 // Now that we have an instruction, try combining it to simplify it. 1459 Builder->SetInsertPoint(I->getParent(), I); 1460 1461#ifndef NDEBUG 1462 std::string OrigI; 1463#endif 1464 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();); 1465 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n'); 1466 1467 if (Instruction *Result = visit(*I)) { 1468 ++NumCombined; 1469 // Should we replace the old instruction with a new one? 1470 if (Result != I) { 1471 DEBUG(errs() << "IC: Old = " << *I << '\n' 1472 << " New = " << *Result << '\n'); 1473 1474 // Everything uses the new instruction now. 1475 I->replaceAllUsesWith(Result); 1476 1477 // Push the new instruction and any users onto the worklist. 1478 Worklist.Add(Result); 1479 Worklist.AddUsersToWorkList(*Result); 1480 1481 // Move the name to the new instruction first. 1482 Result->takeName(I); 1483 1484 // Insert the new instruction into the basic block... 1485 BasicBlock *InstParent = I->getParent(); 1486 BasicBlock::iterator InsertPos = I; 1487 1488 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert 1489 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs. 1490 ++InsertPos; 1491 1492 InstParent->getInstList().insert(InsertPos, Result); 1493 1494 EraseInstFromFunction(*I); 1495 } else { 1496#ifndef NDEBUG 1497 DEBUG(errs() << "IC: Mod = " << OrigI << '\n' 1498 << " New = " << *I << '\n'); 1499#endif 1500 1501 // If the instruction was modified, it's possible that it is now dead. 1502 // if so, remove it. 1503 if (isInstructionTriviallyDead(I)) { 1504 EraseInstFromFunction(*I); 1505 } else { 1506 Worklist.Add(I); 1507 Worklist.AddUsersToWorkList(*I); 1508 } 1509 } 1510 MadeIRChange = true; 1511 } 1512 } 1513 1514 Worklist.Zap(); 1515 return MadeIRChange; 1516} 1517 1518 1519bool InstCombiner::runOnFunction(Function &F) { 1520 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 1521 TD = getAnalysisIfAvailable<TargetData>(); 1522 1523 1524 /// Builder - This is an IRBuilder that automatically inserts new 1525 /// instructions into the worklist when they are created. 1526 IRBuilder<true, TargetFolder, InstCombineIRInserter> 1527 TheBuilder(F.getContext(), TargetFolder(TD), 1528 InstCombineIRInserter(Worklist)); 1529 Builder = &TheBuilder; 1530 1531 bool EverMadeChange = false; 1532 1533 // Iterate while there is work to do. 1534 unsigned Iteration = 0; 1535 while (DoOneIteration(F, Iteration++)) 1536 EverMadeChange = true; 1537 1538 Builder = 0; 1539 return EverMadeChange; 1540} 1541 1542FunctionPass *llvm::createInstructionCombiningPass() { 1543 return new InstCombiner(); 1544} 1545