ScalarEvolutionExpander.cpp revision 204642
1234313Sbapt//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===// 2234313Sbapt// 3234313Sbapt// The LLVM Compiler Infrastructure 4247841Sbapt// 5257573Sbdrewery// This file is distributed under the University of Illinois Open Source 6234313Sbapt// License. See LICENSE.TXT for details. 7256998Sbdrewery// 8256998Sbdrewery//===----------------------------------------------------------------------===// 9257353Sbdrewery// 10257353Sbdrewery// This file contains the implementation of the scalar evolution expander, 11257353Sbdrewery// which is used to generate the code corresponding to a given scalar evolution 12256998Sbdrewery// expression. 13234313Sbapt// 14234313Sbapt//===----------------------------------------------------------------------===// 15 16#include "llvm/Analysis/ScalarEvolutionExpander.h" 17#include "llvm/Analysis/LoopInfo.h" 18#include "llvm/LLVMContext.h" 19#include "llvm/Target/TargetData.h" 20#include "llvm/ADT/STLExtras.h" 21using namespace llvm; 22 23/// InsertNoopCastOfTo - Insert a cast of V to the specified type, 24/// which must be possible with a noop cast, doing what we can to share 25/// the casts. 26Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) { 27 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false); 28 assert((Op == Instruction::BitCast || 29 Op == Instruction::PtrToInt || 30 Op == Instruction::IntToPtr) && 31 "InsertNoopCastOfTo cannot perform non-noop casts!"); 32 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) && 33 "InsertNoopCastOfTo cannot change sizes!"); 34 35 // Short-circuit unnecessary bitcasts. 36 if (Op == Instruction::BitCast && V->getType() == Ty) 37 return V; 38 39 // Short-circuit unnecessary inttoptr<->ptrtoint casts. 40 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) && 41 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) { 42 if (CastInst *CI = dyn_cast<CastInst>(V)) 43 if ((CI->getOpcode() == Instruction::PtrToInt || 44 CI->getOpcode() == Instruction::IntToPtr) && 45 SE.getTypeSizeInBits(CI->getType()) == 46 SE.getTypeSizeInBits(CI->getOperand(0)->getType())) 47 return CI->getOperand(0); 48 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 49 if ((CE->getOpcode() == Instruction::PtrToInt || 50 CE->getOpcode() == Instruction::IntToPtr) && 51 SE.getTypeSizeInBits(CE->getType()) == 52 SE.getTypeSizeInBits(CE->getOperand(0)->getType())) 53 return CE->getOperand(0); 54 } 55 56 if (Constant *C = dyn_cast<Constant>(V)) 57 return ConstantExpr::getCast(Op, C, Ty); 58 59 if (Argument *A = dyn_cast<Argument>(V)) { 60 // Check to see if there is already a cast! 61 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); 62 UI != E; ++UI) 63 if ((*UI)->getType() == Ty) 64 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) 65 if (CI->getOpcode() == Op) { 66 // If the cast isn't the first instruction of the function, move it. 67 if (BasicBlock::iterator(CI) != 68 A->getParent()->getEntryBlock().begin()) { 69 // Recreate the cast at the beginning of the entry block. 70 // The old cast is left in place in case it is being used 71 // as an insert point. 72 Instruction *NewCI = 73 CastInst::Create(Op, V, Ty, "", 74 A->getParent()->getEntryBlock().begin()); 75 NewCI->takeName(CI); 76 CI->replaceAllUsesWith(NewCI); 77 return NewCI; 78 } 79 return CI; 80 } 81 82 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), 83 A->getParent()->getEntryBlock().begin()); 84 rememberInstruction(I); 85 return I; 86 } 87 88 Instruction *I = cast<Instruction>(V); 89 90 // Check to see if there is already a cast. If there is, use it. 91 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 92 UI != E; ++UI) { 93 if ((*UI)->getType() == Ty) 94 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) 95 if (CI->getOpcode() == Op) { 96 BasicBlock::iterator It = I; ++It; 97 if (isa<InvokeInst>(I)) 98 It = cast<InvokeInst>(I)->getNormalDest()->begin(); 99 while (isa<PHINode>(It)) ++It; 100 if (It != BasicBlock::iterator(CI)) { 101 // Recreate the cast after the user. 102 // The old cast is left in place in case it is being used 103 // as an insert point. 104 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It); 105 NewCI->takeName(CI); 106 CI->replaceAllUsesWith(NewCI); 107 rememberInstruction(NewCI); 108 return NewCI; 109 } 110 rememberInstruction(CI); 111 return CI; 112 } 113 } 114 BasicBlock::iterator IP = I; ++IP; 115 if (InvokeInst *II = dyn_cast<InvokeInst>(I)) 116 IP = II->getNormalDest()->begin(); 117 while (isa<PHINode>(IP)) ++IP; 118 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP); 119 rememberInstruction(CI); 120 return CI; 121} 122 123/// InsertBinop - Insert the specified binary operator, doing a small amount 124/// of work to avoid inserting an obviously redundant operation. 125Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, 126 Value *LHS, Value *RHS) { 127 // Fold a binop with constant operands. 128 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 129 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 130 return ConstantExpr::get(Opcode, CLHS, CRHS); 131 132 // Do a quick scan to see if we have this binop nearby. If so, reuse it. 133 unsigned ScanLimit = 6; 134 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 135 // Scanning starts from the last instruction before the insertion point. 136 BasicBlock::iterator IP = Builder.GetInsertPoint(); 137 if (IP != BlockBegin) { 138 --IP; 139 for (; ScanLimit; --IP, --ScanLimit) { 140 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS && 141 IP->getOperand(1) == RHS) 142 return IP; 143 if (IP == BlockBegin) break; 144 } 145 } 146 147 // Save the original insertion point so we can restore it when we're done. 148 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 149 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 150 151 // Move the insertion point out of as many loops as we can. 152 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) { 153 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break; 154 BasicBlock *Preheader = L->getLoopPreheader(); 155 if (!Preheader) break; 156 157 // Ok, move up a level. 158 Builder.SetInsertPoint(Preheader, Preheader->getTerminator()); 159 } 160 161 // If we haven't found this binop, insert it. 162 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp"); 163 rememberInstruction(BO); 164 165 // Restore the original insert point. 166 if (SaveInsertBB) 167 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 168 169 return BO; 170} 171 172/// FactorOutConstant - Test if S is divisible by Factor, using signed 173/// division. If so, update S with Factor divided out and return true. 174/// S need not be evenly divisible if a reasonable remainder can be 175/// computed. 176/// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made 177/// unnecessary; in its place, just signed-divide Ops[i] by the scale and 178/// check to see if the divide was folded. 179static bool FactorOutConstant(const SCEV *&S, 180 const SCEV *&Remainder, 181 const SCEV *Factor, 182 ScalarEvolution &SE, 183 const TargetData *TD) { 184 // Everything is divisible by one. 185 if (Factor->isOne()) 186 return true; 187 188 // x/x == 1. 189 if (S == Factor) { 190 S = SE.getIntegerSCEV(1, S->getType()); 191 return true; 192 } 193 194 // For a Constant, check for a multiple of the given factor. 195 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { 196 // 0/x == 0. 197 if (C->isZero()) 198 return true; 199 // Check for divisibility. 200 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) { 201 ConstantInt *CI = 202 ConstantInt::get(SE.getContext(), 203 C->getValue()->getValue().sdiv( 204 FC->getValue()->getValue())); 205 // If the quotient is zero and the remainder is non-zero, reject 206 // the value at this scale. It will be considered for subsequent 207 // smaller scales. 208 if (!CI->isZero()) { 209 const SCEV *Div = SE.getConstant(CI); 210 S = Div; 211 Remainder = 212 SE.getAddExpr(Remainder, 213 SE.getConstant(C->getValue()->getValue().srem( 214 FC->getValue()->getValue()))); 215 return true; 216 } 217 } 218 } 219 220 // In a Mul, check if there is a constant operand which is a multiple 221 // of the given factor. 222 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 223 if (TD) { 224 // With TargetData, the size is known. Check if there is a constant 225 // operand which is a multiple of the given factor. If so, we can 226 // factor it. 227 const SCEVConstant *FC = cast<SCEVConstant>(Factor); 228 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0))) 229 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) { 230 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands(); 231 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(), 232 MOperands.end()); 233 NewMulOps[0] = 234 SE.getConstant(C->getValue()->getValue().sdiv( 235 FC->getValue()->getValue())); 236 S = SE.getMulExpr(NewMulOps); 237 return true; 238 } 239 } else { 240 // Without TargetData, check if Factor can be factored out of any of the 241 // Mul's operands. If so, we can just remove it. 242 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 243 const SCEV *SOp = M->getOperand(i); 244 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType()); 245 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) && 246 Remainder->isZero()) { 247 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands(); 248 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(), 249 MOperands.end()); 250 NewMulOps[i] = SOp; 251 S = SE.getMulExpr(NewMulOps); 252 return true; 253 } 254 } 255 } 256 } 257 258 // In an AddRec, check if both start and step are divisible. 259 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 260 const SCEV *Step = A->getStepRecurrence(SE); 261 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType()); 262 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD)) 263 return false; 264 if (!StepRem->isZero()) 265 return false; 266 const SCEV *Start = A->getStart(); 267 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD)) 268 return false; 269 S = SE.getAddRecExpr(Start, Step, A->getLoop()); 270 return true; 271 } 272 273 return false; 274} 275 276/// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs 277/// is the number of SCEVAddRecExprs present, which are kept at the end of 278/// the list. 279/// 280static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops, 281 const Type *Ty, 282 ScalarEvolution &SE) { 283 unsigned NumAddRecs = 0; 284 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i) 285 ++NumAddRecs; 286 // Group Ops into non-addrecs and addrecs. 287 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs); 288 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end()); 289 // Let ScalarEvolution sort and simplify the non-addrecs list. 290 const SCEV *Sum = NoAddRecs.empty() ? 291 SE.getIntegerSCEV(0, Ty) : 292 SE.getAddExpr(NoAddRecs); 293 // If it returned an add, use the operands. Otherwise it simplified 294 // the sum into a single value, so just use that. 295 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum)) 296 Ops = Add->getOperands(); 297 else { 298 Ops.clear(); 299 if (!Sum->isZero()) 300 Ops.push_back(Sum); 301 } 302 // Then append the addrecs. 303 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end()); 304} 305 306/// SplitAddRecs - Flatten a list of add operands, moving addrec start values 307/// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}. 308/// This helps expose more opportunities for folding parts of the expressions 309/// into GEP indices. 310/// 311static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops, 312 const Type *Ty, 313 ScalarEvolution &SE) { 314 // Find the addrecs. 315 SmallVector<const SCEV *, 8> AddRecs; 316 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 317 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) { 318 const SCEV *Start = A->getStart(); 319 if (Start->isZero()) break; 320 const SCEV *Zero = SE.getIntegerSCEV(0, Ty); 321 AddRecs.push_back(SE.getAddRecExpr(Zero, 322 A->getStepRecurrence(SE), 323 A->getLoop())); 324 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) { 325 Ops[i] = Zero; 326 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end()); 327 e += Add->getNumOperands(); 328 } else { 329 Ops[i] = Start; 330 } 331 } 332 if (!AddRecs.empty()) { 333 // Add the addrecs onto the end of the list. 334 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end()); 335 // Resort the operand list, moving any constants to the front. 336 SimplifyAddOperands(Ops, Ty, SE); 337 } 338} 339 340/// expandAddToGEP - Expand an addition expression with a pointer type into 341/// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps 342/// BasicAliasAnalysis and other passes analyze the result. See the rules 343/// for getelementptr vs. inttoptr in 344/// http://llvm.org/docs/LangRef.html#pointeraliasing 345/// for details. 346/// 347/// Design note: The correctness of using getelementptr here depends on 348/// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as 349/// they may introduce pointer arithmetic which may not be safely converted 350/// into getelementptr. 351/// 352/// Design note: It might seem desirable for this function to be more 353/// loop-aware. If some of the indices are loop-invariant while others 354/// aren't, it might seem desirable to emit multiple GEPs, keeping the 355/// loop-invariant portions of the overall computation outside the loop. 356/// However, there are a few reasons this is not done here. Hoisting simple 357/// arithmetic is a low-level optimization that often isn't very 358/// important until late in the optimization process. In fact, passes 359/// like InstructionCombining will combine GEPs, even if it means 360/// pushing loop-invariant computation down into loops, so even if the 361/// GEPs were split here, the work would quickly be undone. The 362/// LoopStrengthReduction pass, which is usually run quite late (and 363/// after the last InstructionCombining pass), takes care of hoisting 364/// loop-invariant portions of expressions, after considering what 365/// can be folded using target addressing modes. 366/// 367Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin, 368 const SCEV *const *op_end, 369 const PointerType *PTy, 370 const Type *Ty, 371 Value *V) { 372 const Type *ElTy = PTy->getElementType(); 373 SmallVector<Value *, 4> GepIndices; 374 SmallVector<const SCEV *, 8> Ops(op_begin, op_end); 375 bool AnyNonZeroIndices = false; 376 377 // Split AddRecs up into parts as either of the parts may be usable 378 // without the other. 379 SplitAddRecs(Ops, Ty, SE); 380 381 // Descend down the pointer's type and attempt to convert the other 382 // operands into GEP indices, at each level. The first index in a GEP 383 // indexes into the array implied by the pointer operand; the rest of 384 // the indices index into the element or field type selected by the 385 // preceding index. 386 for (;;) { 387 // If the scale size is not 0, attempt to factor out a scale for 388 // array indexing. 389 SmallVector<const SCEV *, 8> ScaledOps; 390 if (ElTy->isSized()) { 391 const SCEV *ElSize = SE.getSizeOfExpr(ElTy); 392 if (!ElSize->isZero()) { 393 SmallVector<const SCEV *, 8> NewOps; 394 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 395 const SCEV *Op = Ops[i]; 396 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty); 397 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) { 398 // Op now has ElSize factored out. 399 ScaledOps.push_back(Op); 400 if (!Remainder->isZero()) 401 NewOps.push_back(Remainder); 402 AnyNonZeroIndices = true; 403 } else { 404 // The operand was not divisible, so add it to the list of operands 405 // we'll scan next iteration. 406 NewOps.push_back(Ops[i]); 407 } 408 } 409 // If we made any changes, update Ops. 410 if (!ScaledOps.empty()) { 411 Ops = NewOps; 412 SimplifyAddOperands(Ops, Ty, SE); 413 } 414 } 415 } 416 417 // Record the scaled array index for this level of the type. If 418 // we didn't find any operands that could be factored, tentatively 419 // assume that element zero was selected (since the zero offset 420 // would obviously be folded away). 421 Value *Scaled = ScaledOps.empty() ? 422 Constant::getNullValue(Ty) : 423 expandCodeFor(SE.getAddExpr(ScaledOps), Ty); 424 GepIndices.push_back(Scaled); 425 426 // Collect struct field index operands. 427 while (const StructType *STy = dyn_cast<StructType>(ElTy)) { 428 bool FoundFieldNo = false; 429 // An empty struct has no fields. 430 if (STy->getNumElements() == 0) break; 431 if (SE.TD) { 432 // With TargetData, field offsets are known. See if a constant offset 433 // falls within any of the struct fields. 434 if (Ops.empty()) break; 435 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0])) 436 if (SE.getTypeSizeInBits(C->getType()) <= 64) { 437 const StructLayout &SL = *SE.TD->getStructLayout(STy); 438 uint64_t FullOffset = C->getValue()->getZExtValue(); 439 if (FullOffset < SL.getSizeInBytes()) { 440 unsigned ElIdx = SL.getElementContainingOffset(FullOffset); 441 GepIndices.push_back( 442 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx)); 443 ElTy = STy->getTypeAtIndex(ElIdx); 444 Ops[0] = 445 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx)); 446 AnyNonZeroIndices = true; 447 FoundFieldNo = true; 448 } 449 } 450 } else { 451 // Without TargetData, just check for an offsetof expression of the 452 // appropriate struct type. 453 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 454 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) { 455 const Type *CTy; 456 Constant *FieldNo; 457 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) { 458 GepIndices.push_back(FieldNo); 459 ElTy = 460 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue()); 461 Ops[i] = SE.getConstant(Ty, 0); 462 AnyNonZeroIndices = true; 463 FoundFieldNo = true; 464 break; 465 } 466 } 467 } 468 // If no struct field offsets were found, tentatively assume that 469 // field zero was selected (since the zero offset would obviously 470 // be folded away). 471 if (!FoundFieldNo) { 472 ElTy = STy->getTypeAtIndex(0u); 473 GepIndices.push_back( 474 Constant::getNullValue(Type::getInt32Ty(Ty->getContext()))); 475 } 476 } 477 478 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) 479 ElTy = ATy->getElementType(); 480 else 481 break; 482 } 483 484 // If none of the operands were convertible to proper GEP indices, cast 485 // the base to i8* and do an ugly getelementptr with that. It's still 486 // better than ptrtoint+arithmetic+inttoptr at least. 487 if (!AnyNonZeroIndices) { 488 // Cast the base to i8*. 489 V = InsertNoopCastOfTo(V, 490 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace())); 491 492 // Expand the operands for a plain byte offset. 493 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty); 494 495 // Fold a GEP with constant operands. 496 if (Constant *CLHS = dyn_cast<Constant>(V)) 497 if (Constant *CRHS = dyn_cast<Constant>(Idx)) 498 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1); 499 500 // Do a quick scan to see if we have this GEP nearby. If so, reuse it. 501 unsigned ScanLimit = 6; 502 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin(); 503 // Scanning starts from the last instruction before the insertion point. 504 BasicBlock::iterator IP = Builder.GetInsertPoint(); 505 if (IP != BlockBegin) { 506 --IP; 507 for (; ScanLimit; --IP, --ScanLimit) { 508 if (IP->getOpcode() == Instruction::GetElementPtr && 509 IP->getOperand(0) == V && IP->getOperand(1) == Idx) 510 return IP; 511 if (IP == BlockBegin) break; 512 } 513 } 514 515 // Save the original insertion point so we can restore it when we're done. 516 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 517 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 518 519 // Move the insertion point out of as many loops as we can. 520 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) { 521 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break; 522 BasicBlock *Preheader = L->getLoopPreheader(); 523 if (!Preheader) break; 524 525 // Ok, move up a level. 526 Builder.SetInsertPoint(Preheader, Preheader->getTerminator()); 527 } 528 529 // Emit a GEP. 530 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep"); 531 rememberInstruction(GEP); 532 533 // Restore the original insert point. 534 if (SaveInsertBB) 535 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 536 537 return GEP; 538 } 539 540 // Save the original insertion point so we can restore it when we're done. 541 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 542 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 543 544 // Move the insertion point out of as many loops as we can. 545 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) { 546 if (!L->isLoopInvariant(V)) break; 547 548 bool AnyIndexNotLoopInvariant = false; 549 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(), 550 E = GepIndices.end(); I != E; ++I) 551 if (!L->isLoopInvariant(*I)) { 552 AnyIndexNotLoopInvariant = true; 553 break; 554 } 555 if (AnyIndexNotLoopInvariant) 556 break; 557 558 BasicBlock *Preheader = L->getLoopPreheader(); 559 if (!Preheader) break; 560 561 // Ok, move up a level. 562 Builder.SetInsertPoint(Preheader, Preheader->getTerminator()); 563 } 564 565 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds, 566 // because ScalarEvolution may have changed the address arithmetic to 567 // compute a value which is beyond the end of the allocated object. 568 Value *Casted = V; 569 if (V->getType() != PTy) 570 Casted = InsertNoopCastOfTo(Casted, PTy); 571 Value *GEP = Builder.CreateGEP(Casted, 572 GepIndices.begin(), 573 GepIndices.end(), 574 "scevgep"); 575 Ops.push_back(SE.getUnknown(GEP)); 576 rememberInstruction(GEP); 577 578 // Restore the original insert point. 579 if (SaveInsertBB) 580 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 581 582 return expand(SE.getAddExpr(Ops)); 583} 584 585/// isNonConstantNegative - Return true if the specified scev is negated, but 586/// not a constant. 587static bool isNonConstantNegative(const SCEV *F) { 588 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F); 589 if (!Mul) return false; 590 591 // If there is a constant factor, it will be first. 592 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 593 if (!SC) return false; 594 595 // Return true if the value is negative, this matches things like (-42 * V). 596 return SC->getValue()->getValue().isNegative(); 597} 598 599/// PickMostRelevantLoop - Given two loops pick the one that's most relevant for 600/// SCEV expansion. If they are nested, this is the most nested. If they are 601/// neighboring, pick the later. 602static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B, 603 DominatorTree &DT) { 604 if (!A) return B; 605 if (!B) return A; 606 if (A->contains(B)) return B; 607 if (B->contains(A)) return A; 608 if (DT.dominates(A->getHeader(), B->getHeader())) return B; 609 if (DT.dominates(B->getHeader(), A->getHeader())) return A; 610 return A; // Arbitrarily break the tie. 611} 612 613/// GetRelevantLoop - Get the most relevant loop associated with the given 614/// expression, according to PickMostRelevantLoop. 615static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI, 616 DominatorTree &DT) { 617 if (isa<SCEVConstant>(S)) 618 return 0; 619 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 620 if (const Instruction *I = dyn_cast<Instruction>(U->getValue())) 621 return LI.getLoopFor(I->getParent()); 622 return 0; 623 } 624 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) { 625 const Loop *L = 0; 626 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 627 L = AR->getLoop(); 628 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end(); 629 I != E; ++I) 630 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT); 631 return L; 632 } 633 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) 634 return GetRelevantLoop(C->getOperand(), LI, DT); 635 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) 636 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT), 637 GetRelevantLoop(D->getRHS(), LI, DT), 638 DT); 639 llvm_unreachable("Unexpected SCEV type!"); 640} 641 642/// LoopCompare - Compare loops by PickMostRelevantLoop. 643class LoopCompare { 644 DominatorTree &DT; 645public: 646 explicit LoopCompare(DominatorTree &dt) : DT(dt) {} 647 648 bool operator()(std::pair<const Loop *, const SCEV *> LHS, 649 std::pair<const Loop *, const SCEV *> RHS) const { 650 // Compare loops with PickMostRelevantLoop. 651 if (LHS.first != RHS.first) 652 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first; 653 654 // If one operand is a non-constant negative and the other is not, 655 // put the non-constant negative on the right so that a sub can 656 // be used instead of a negate and add. 657 if (isNonConstantNegative(LHS.second)) { 658 if (!isNonConstantNegative(RHS.second)) 659 return false; 660 } else if (isNonConstantNegative(RHS.second)) 661 return true; 662 663 // Otherwise they are equivalent according to this comparison. 664 return false; 665 } 666}; 667 668Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) { 669 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 670 671 // Collect all the add operands in a loop, along with their associated loops. 672 // Iterate in reverse so that constants are emitted last, all else equal, and 673 // so that pointer operands are inserted first, which the code below relies on 674 // to form more involved GEPs. 675 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 676 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()), 677 E(S->op_begin()); I != E; ++I) 678 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT), 679 *I)); 680 681 // Sort by loop. Use a stable sort so that constants follow non-constants and 682 // pointer operands precede non-pointer operands. 683 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT)); 684 685 // Emit instructions to add all the operands. Hoist as much as possible 686 // out of loops, and form meaningful getelementptrs where possible. 687 Value *Sum = 0; 688 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator 689 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) { 690 const Loop *CurLoop = I->first; 691 const SCEV *Op = I->second; 692 if (!Sum) { 693 // This is the first operand. Just expand it. 694 Sum = expand(Op); 695 ++I; 696 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) { 697 // The running sum expression is a pointer. Try to form a getelementptr 698 // at this level with that as the base. 699 SmallVector<const SCEV *, 4> NewOps; 700 for (; I != E && I->first == CurLoop; ++I) 701 NewOps.push_back(I->second); 702 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum); 703 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) { 704 // The running sum is an integer, and there's a pointer at this level. 705 // Try to form a getelementptr. 706 SmallVector<const SCEV *, 4> NewOps; 707 NewOps.push_back(SE.getUnknown(Sum)); 708 for (++I; I != E && I->first == CurLoop; ++I) 709 NewOps.push_back(I->second); 710 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op)); 711 } else if (isNonConstantNegative(Op)) { 712 // Instead of doing a negate and add, just do a subtract. 713 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty); 714 Sum = InsertNoopCastOfTo(Sum, Ty); 715 Sum = InsertBinop(Instruction::Sub, Sum, W); 716 ++I; 717 } else { 718 // A simple add. 719 Value *W = expandCodeFor(Op, Ty); 720 Sum = InsertNoopCastOfTo(Sum, Ty); 721 // Canonicalize a constant to the RHS. 722 if (isa<Constant>(Sum)) std::swap(Sum, W); 723 Sum = InsertBinop(Instruction::Add, Sum, W); 724 ++I; 725 } 726 } 727 728 return Sum; 729} 730 731Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) { 732 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 733 734 // Collect all the mul operands in a loop, along with their associated loops. 735 // Iterate in reverse so that constants are emitted last, all else equal. 736 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops; 737 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()), 738 E(S->op_begin()); I != E; ++I) 739 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT), 740 *I)); 741 742 // Sort by loop. Use a stable sort so that constants follow non-constants. 743 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT)); 744 745 // Emit instructions to mul all the operands. Hoist as much as possible 746 // out of loops. 747 Value *Prod = 0; 748 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator 749 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) { 750 const SCEV *Op = I->second; 751 if (!Prod) { 752 // This is the first operand. Just expand it. 753 Prod = expand(Op); 754 ++I; 755 } else if (Op->isAllOnesValue()) { 756 // Instead of doing a multiply by negative one, just do a negate. 757 Prod = InsertNoopCastOfTo(Prod, Ty); 758 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod); 759 ++I; 760 } else { 761 // A simple mul. 762 Value *W = expandCodeFor(Op, Ty); 763 Prod = InsertNoopCastOfTo(Prod, Ty); 764 // Canonicalize a constant to the RHS. 765 if (isa<Constant>(Prod)) std::swap(Prod, W); 766 Prod = InsertBinop(Instruction::Mul, Prod, W); 767 ++I; 768 } 769 } 770 771 return Prod; 772} 773 774Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) { 775 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 776 777 Value *LHS = expandCodeFor(S->getLHS(), Ty); 778 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) { 779 const APInt &RHS = SC->getValue()->getValue(); 780 if (RHS.isPowerOf2()) 781 return InsertBinop(Instruction::LShr, LHS, 782 ConstantInt::get(Ty, RHS.logBase2())); 783 } 784 785 Value *RHS = expandCodeFor(S->getRHS(), Ty); 786 return InsertBinop(Instruction::UDiv, LHS, RHS); 787} 788 789/// Move parts of Base into Rest to leave Base with the minimal 790/// expression that provides a pointer operand suitable for a 791/// GEP expansion. 792static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest, 793 ScalarEvolution &SE) { 794 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) { 795 Base = A->getStart(); 796 Rest = SE.getAddExpr(Rest, 797 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()), 798 A->getStepRecurrence(SE), 799 A->getLoop())); 800 } 801 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) { 802 Base = A->getOperand(A->getNumOperands()-1); 803 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end()); 804 NewAddOps.back() = Rest; 805 Rest = SE.getAddExpr(NewAddOps); 806 ExposePointerBase(Base, Rest, SE); 807 } 808} 809 810/// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand 811/// the base addrec, which is the addrec without any non-loop-dominating 812/// values, and return the PHI. 813PHINode * 814SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized, 815 const Loop *L, 816 const Type *ExpandTy, 817 const Type *IntTy) { 818 // Reuse a previously-inserted PHI, if present. 819 for (BasicBlock::iterator I = L->getHeader()->begin(); 820 PHINode *PN = dyn_cast<PHINode>(I); ++I) 821 if (SE.isSCEVable(PN->getType()) && 822 (SE.getEffectiveSCEVType(PN->getType()) == 823 SE.getEffectiveSCEVType(Normalized->getType())) && 824 SE.getSCEV(PN) == Normalized) 825 if (BasicBlock *LatchBlock = L->getLoopLatch()) { 826 Instruction *IncV = 827 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)); 828 829 // Determine if this is a well-behaved chain of instructions leading 830 // back to the PHI. It probably will be, if we're scanning an inner 831 // loop already visited by LSR for example, but it wouldn't have 832 // to be. 833 do { 834 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) { 835 IncV = 0; 836 break; 837 } 838 // If any of the operands don't dominate the insert position, bail. 839 // Addrec operands are always loop-invariant, so this can only happen 840 // if there are instructions which haven't been hoisted. 841 for (User::op_iterator OI = IncV->op_begin()+1, 842 OE = IncV->op_end(); OI != OE; ++OI) 843 if (Instruction *OInst = dyn_cast<Instruction>(OI)) 844 if (!SE.DT->dominates(OInst, IVIncInsertPos)) { 845 IncV = 0; 846 break; 847 } 848 if (!IncV) 849 break; 850 // Advance to the next instruction. 851 IncV = dyn_cast<Instruction>(IncV->getOperand(0)); 852 if (!IncV) 853 break; 854 if (IncV->mayHaveSideEffects()) { 855 IncV = 0; 856 break; 857 } 858 } while (IncV != PN); 859 860 if (IncV) { 861 // Ok, the add recurrence looks usable. 862 // Remember this PHI, even in post-inc mode. 863 InsertedValues.insert(PN); 864 // Remember the increment. 865 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)); 866 rememberInstruction(IncV); 867 if (L == IVIncInsertLoop) 868 do { 869 if (SE.DT->dominates(IncV, IVIncInsertPos)) 870 break; 871 // Make sure the increment is where we want it. But don't move it 872 // down past a potential existing post-inc user. 873 IncV->moveBefore(IVIncInsertPos); 874 IVIncInsertPos = IncV; 875 IncV = cast<Instruction>(IncV->getOperand(0)); 876 } while (IncV != PN); 877 return PN; 878 } 879 } 880 881 // Save the original insertion point so we can restore it when we're done. 882 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 883 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 884 885 // Expand code for the start value. 886 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy, 887 L->getHeader()->begin()); 888 889 // Expand code for the step value. Insert instructions right before the 890 // terminator corresponding to the back-edge. Do this before creating the PHI 891 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is 892 // negative, insert a sub instead of an add for the increment (unless it's a 893 // constant, because subtracts of constants are canonicalized to adds). 894 const SCEV *Step = Normalized->getStepRecurrence(SE); 895 bool isPointer = ExpandTy->isPointerTy(); 896 bool isNegative = !isPointer && isNonConstantNegative(Step); 897 if (isNegative) 898 Step = SE.getNegativeSCEV(Step); 899 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin()); 900 901 // Create the PHI. 902 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin()); 903 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv"); 904 rememberInstruction(PN); 905 906 // Create the step instructions and populate the PHI. 907 BasicBlock *Header = L->getHeader(); 908 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header); 909 HPI != HPE; ++HPI) { 910 BasicBlock *Pred = *HPI; 911 912 // Add a start value. 913 if (!L->contains(Pred)) { 914 PN->addIncoming(StartV, Pred); 915 continue; 916 } 917 918 // Create a step value and add it to the PHI. If IVIncInsertLoop is 919 // non-null and equal to the addrec's loop, insert the instructions 920 // at IVIncInsertPos. 921 Instruction *InsertPos = L == IVIncInsertLoop ? 922 IVIncInsertPos : Pred->getTerminator(); 923 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos); 924 Value *IncV; 925 // If the PHI is a pointer, use a GEP, otherwise use an add or sub. 926 if (isPointer) { 927 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy); 928 // If the step isn't constant, don't use an implicitly scaled GEP, because 929 // that would require a multiply inside the loop. 930 if (!isa<ConstantInt>(StepV)) 931 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()), 932 GEPPtrTy->getAddressSpace()); 933 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) }; 934 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN); 935 if (IncV->getType() != PN->getType()) { 936 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp"); 937 rememberInstruction(IncV); 938 } 939 } else { 940 IncV = isNegative ? 941 Builder.CreateSub(PN, StepV, "lsr.iv.next") : 942 Builder.CreateAdd(PN, StepV, "lsr.iv.next"); 943 rememberInstruction(IncV); 944 } 945 PN->addIncoming(IncV, Pred); 946 } 947 948 // Restore the original insert point. 949 if (SaveInsertBB) 950 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 951 952 // Remember this PHI, even in post-inc mode. 953 InsertedValues.insert(PN); 954 955 return PN; 956} 957 958Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) { 959 const Type *STy = S->getType(); 960 const Type *IntTy = SE.getEffectiveSCEVType(STy); 961 const Loop *L = S->getLoop(); 962 963 // Determine a normalized form of this expression, which is the expression 964 // before any post-inc adjustment is made. 965 const SCEVAddRecExpr *Normalized = S; 966 if (L == PostIncLoop) { 967 const SCEV *Step = S->getStepRecurrence(SE); 968 Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step)); 969 } 970 971 // Strip off any non-loop-dominating component from the addrec start. 972 const SCEV *Start = Normalized->getStart(); 973 const SCEV *PostLoopOffset = 0; 974 if (!Start->properlyDominates(L->getHeader(), SE.DT)) { 975 PostLoopOffset = Start; 976 Start = SE.getIntegerSCEV(0, Normalized->getType()); 977 Normalized = 978 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, 979 Normalized->getStepRecurrence(SE), 980 Normalized->getLoop())); 981 } 982 983 // Strip off any non-loop-dominating component from the addrec step. 984 const SCEV *Step = Normalized->getStepRecurrence(SE); 985 const SCEV *PostLoopScale = 0; 986 if (!Step->hasComputableLoopEvolution(L) && 987 !Step->dominates(L->getHeader(), SE.DT)) { 988 PostLoopScale = Step; 989 Step = SE.getIntegerSCEV(1, Normalized->getType()); 990 Normalized = 991 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step, 992 Normalized->getLoop())); 993 } 994 995 // Expand the core addrec. If we need post-loop scaling, force it to 996 // expand to an integer type to avoid the need for additional casting. 997 const Type *ExpandTy = PostLoopScale ? IntTy : STy; 998 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy); 999 1000 // Accommodate post-inc mode, if necessary. 1001 Value *Result; 1002 if (L != PostIncLoop) 1003 Result = PN; 1004 else { 1005 // In PostInc mode, use the post-incremented value. 1006 BasicBlock *LatchBlock = L->getLoopLatch(); 1007 assert(LatchBlock && "PostInc mode requires a unique loop latch!"); 1008 Result = PN->getIncomingValueForBlock(LatchBlock); 1009 } 1010 1011 // Re-apply any non-loop-dominating scale. 1012 if (PostLoopScale) { 1013 Result = InsertNoopCastOfTo(Result, IntTy); 1014 Result = Builder.CreateMul(Result, 1015 expandCodeFor(PostLoopScale, IntTy)); 1016 rememberInstruction(Result); 1017 } 1018 1019 // Re-apply any non-loop-dominating offset. 1020 if (PostLoopOffset) { 1021 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) { 1022 const SCEV *const OffsetArray[1] = { PostLoopOffset }; 1023 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result); 1024 } else { 1025 Result = InsertNoopCastOfTo(Result, IntTy); 1026 Result = Builder.CreateAdd(Result, 1027 expandCodeFor(PostLoopOffset, IntTy)); 1028 rememberInstruction(Result); 1029 } 1030 } 1031 1032 return Result; 1033} 1034 1035Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) { 1036 if (!CanonicalMode) return expandAddRecExprLiterally(S); 1037 1038 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1039 const Loop *L = S->getLoop(); 1040 1041 // First check for an existing canonical IV in a suitable type. 1042 PHINode *CanonicalIV = 0; 1043 if (PHINode *PN = L->getCanonicalInductionVariable()) 1044 if (SE.isSCEVable(PN->getType()) && 1045 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() && 1046 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty)) 1047 CanonicalIV = PN; 1048 1049 // Rewrite an AddRec in terms of the canonical induction variable, if 1050 // its type is more narrow. 1051 if (CanonicalIV && 1052 SE.getTypeSizeInBits(CanonicalIV->getType()) > 1053 SE.getTypeSizeInBits(Ty)) { 1054 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands(); 1055 SmallVector<const SCEV *, 4> NewOps(Ops.size()); 1056 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 1057 NewOps[i] = SE.getAnyExtendExpr(Ops[i], CanonicalIV->getType()); 1058 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop())); 1059 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 1060 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 1061 BasicBlock::iterator NewInsertPt = 1062 llvm::next(BasicBlock::iterator(cast<Instruction>(V))); 1063 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt; 1064 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0, 1065 NewInsertPt); 1066 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 1067 return V; 1068 } 1069 1070 // {X,+,F} --> X + {0,+,F} 1071 if (!S->getStart()->isZero()) { 1072 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands(); 1073 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end()); 1074 NewOps[0] = SE.getIntegerSCEV(0, Ty); 1075 const SCEV *Rest = SE.getAddRecExpr(NewOps, L); 1076 1077 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the 1078 // comments on expandAddToGEP for details. 1079 const SCEV *Base = S->getStart(); 1080 const SCEV *RestArray[1] = { Rest }; 1081 // Dig into the expression to find the pointer base for a GEP. 1082 ExposePointerBase(Base, RestArray[0], SE); 1083 // If we found a pointer, expand the AddRec with a GEP. 1084 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) { 1085 // Make sure the Base isn't something exotic, such as a multiplied 1086 // or divided pointer value. In those cases, the result type isn't 1087 // actually a pointer type. 1088 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) { 1089 Value *StartV = expand(Base); 1090 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!"); 1091 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV); 1092 } 1093 } 1094 1095 // Just do a normal add. Pre-expand the operands to suppress folding. 1096 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())), 1097 SE.getUnknown(expand(Rest)))); 1098 } 1099 1100 // {0,+,1} --> Insert a canonical induction variable into the loop! 1101 if (S->isAffine() && 1102 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) { 1103 // If there's a canonical IV, just use it. 1104 if (CanonicalIV) { 1105 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) && 1106 "IVs with types different from the canonical IV should " 1107 "already have been handled!"); 1108 return CanonicalIV; 1109 } 1110 1111 // Create and insert the PHI node for the induction variable in the 1112 // specified loop. 1113 BasicBlock *Header = L->getHeader(); 1114 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin()); 1115 rememberInstruction(PN); 1116 1117 Constant *One = ConstantInt::get(Ty, 1); 1118 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header); 1119 HPI != HPE; ++HPI) 1120 if (L->contains(*HPI)) { 1121 // Insert a unit add instruction right before the terminator 1122 // corresponding to the back-edge. 1123 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next", 1124 (*HPI)->getTerminator()); 1125 rememberInstruction(Add); 1126 PN->addIncoming(Add, *HPI); 1127 } else { 1128 PN->addIncoming(Constant::getNullValue(Ty), *HPI); 1129 } 1130 } 1131 1132 // {0,+,F} --> {0,+,1} * F 1133 // Get the canonical induction variable I for this loop. 1134 Value *I = CanonicalIV ? 1135 CanonicalIV : 1136 getOrInsertCanonicalInductionVariable(L, Ty); 1137 1138 // If this is a simple linear addrec, emit it now as a special case. 1139 if (S->isAffine()) // {0,+,F} --> i*F 1140 return 1141 expand(SE.getTruncateOrNoop( 1142 SE.getMulExpr(SE.getUnknown(I), 1143 SE.getNoopOrAnyExtend(S->getOperand(1), 1144 I->getType())), 1145 Ty)); 1146 1147 // If this is a chain of recurrences, turn it into a closed form, using the 1148 // folders, then expandCodeFor the closed form. This allows the folders to 1149 // simplify the expression without having to build a bunch of special code 1150 // into this folder. 1151 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV. 1152 1153 // Promote S up to the canonical IV type, if the cast is foldable. 1154 const SCEV *NewS = S; 1155 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType()); 1156 if (isa<SCEVAddRecExpr>(Ext)) 1157 NewS = Ext; 1158 1159 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE); 1160 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n"; 1161 1162 // Truncate the result down to the original type, if needed. 1163 const SCEV *T = SE.getTruncateOrNoop(V, Ty); 1164 return expand(T); 1165} 1166 1167Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) { 1168 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1169 Value *V = expandCodeFor(S->getOperand(), 1170 SE.getEffectiveSCEVType(S->getOperand()->getType())); 1171 Value *I = Builder.CreateTrunc(V, Ty, "tmp"); 1172 rememberInstruction(I); 1173 return I; 1174} 1175 1176Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) { 1177 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1178 Value *V = expandCodeFor(S->getOperand(), 1179 SE.getEffectiveSCEVType(S->getOperand()->getType())); 1180 Value *I = Builder.CreateZExt(V, Ty, "tmp"); 1181 rememberInstruction(I); 1182 return I; 1183} 1184 1185Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) { 1186 const Type *Ty = SE.getEffectiveSCEVType(S->getType()); 1187 Value *V = expandCodeFor(S->getOperand(), 1188 SE.getEffectiveSCEVType(S->getOperand()->getType())); 1189 Value *I = Builder.CreateSExt(V, Ty, "tmp"); 1190 rememberInstruction(I); 1191 return I; 1192} 1193 1194Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) { 1195 Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); 1196 const Type *Ty = LHS->getType(); 1197 for (int i = S->getNumOperands()-2; i >= 0; --i) { 1198 // In the case of mixed integer and pointer types, do the 1199 // rest of the comparisons as integer. 1200 if (S->getOperand(i)->getType() != Ty) { 1201 Ty = SE.getEffectiveSCEVType(Ty); 1202 LHS = InsertNoopCastOfTo(LHS, Ty); 1203 } 1204 Value *RHS = expandCodeFor(S->getOperand(i), Ty); 1205 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp"); 1206 rememberInstruction(ICmp); 1207 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax"); 1208 rememberInstruction(Sel); 1209 LHS = Sel; 1210 } 1211 // In the case of mixed integer and pointer types, cast the 1212 // final result back to the pointer type. 1213 if (LHS->getType() != S->getType()) 1214 LHS = InsertNoopCastOfTo(LHS, S->getType()); 1215 return LHS; 1216} 1217 1218Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) { 1219 Value *LHS = expand(S->getOperand(S->getNumOperands()-1)); 1220 const Type *Ty = LHS->getType(); 1221 for (int i = S->getNumOperands()-2; i >= 0; --i) { 1222 // In the case of mixed integer and pointer types, do the 1223 // rest of the comparisons as integer. 1224 if (S->getOperand(i)->getType() != Ty) { 1225 Ty = SE.getEffectiveSCEVType(Ty); 1226 LHS = InsertNoopCastOfTo(LHS, Ty); 1227 } 1228 Value *RHS = expandCodeFor(S->getOperand(i), Ty); 1229 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp"); 1230 rememberInstruction(ICmp); 1231 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax"); 1232 rememberInstruction(Sel); 1233 LHS = Sel; 1234 } 1235 // In the case of mixed integer and pointer types, cast the 1236 // final result back to the pointer type. 1237 if (LHS->getType() != S->getType()) 1238 LHS = InsertNoopCastOfTo(LHS, S->getType()); 1239 return LHS; 1240} 1241 1242Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) { 1243 // Expand the code for this SCEV. 1244 Value *V = expand(SH); 1245 if (Ty) { 1246 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) && 1247 "non-trivial casts should be done with the SCEVs directly!"); 1248 V = InsertNoopCastOfTo(V, Ty); 1249 } 1250 return V; 1251} 1252 1253Value *SCEVExpander::expand(const SCEV *S) { 1254 // Compute an insertion point for this SCEV object. Hoist the instructions 1255 // as far out in the loop nest as possible. 1256 Instruction *InsertPt = Builder.GetInsertPoint(); 1257 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ; 1258 L = L->getParentLoop()) 1259 if (S->isLoopInvariant(L)) { 1260 if (!L) break; 1261 if (BasicBlock *Preheader = L->getLoopPreheader()) 1262 InsertPt = Preheader->getTerminator(); 1263 } else { 1264 // If the SCEV is computable at this level, insert it into the header 1265 // after the PHIs (and after any other instructions that we've inserted 1266 // there) so that it is guaranteed to dominate any user inside the loop. 1267 if (L && S->hasComputableLoopEvolution(L) && L != PostIncLoop) 1268 InsertPt = L->getHeader()->getFirstNonPHI(); 1269 while (isInsertedInstruction(InsertPt)) 1270 InsertPt = llvm::next(BasicBlock::iterator(InsertPt)); 1271 break; 1272 } 1273 1274 // Check to see if we already expanded this here. 1275 std::map<std::pair<const SCEV *, Instruction *>, 1276 AssertingVH<Value> >::iterator I = 1277 InsertedExpressions.find(std::make_pair(S, InsertPt)); 1278 if (I != InsertedExpressions.end()) 1279 return I->second; 1280 1281 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 1282 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 1283 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt); 1284 1285 // Expand the expression into instructions. 1286 Value *V = visit(S); 1287 1288 // Remember the expanded value for this SCEV at this location. 1289 if (!PostIncLoop) 1290 InsertedExpressions[std::make_pair(S, InsertPt)] = V; 1291 1292 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 1293 return V; 1294} 1295 1296void SCEVExpander::rememberInstruction(Value *I) { 1297 if (!PostIncLoop) 1298 InsertedValues.insert(I); 1299 1300 // If we just claimed an existing instruction and that instruction had 1301 // been the insert point, adjust the insert point forward so that 1302 // subsequently inserted code will be dominated. 1303 if (Builder.GetInsertPoint() == I) { 1304 BasicBlock::iterator It = cast<Instruction>(I); 1305 do { ++It; } while (isInsertedInstruction(It)); 1306 Builder.SetInsertPoint(Builder.GetInsertBlock(), It); 1307 } 1308} 1309 1310void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) { 1311 // If we acquired more instructions since the old insert point was saved, 1312 // advance past them. 1313 while (isInsertedInstruction(I)) ++I; 1314 1315 Builder.SetInsertPoint(BB, I); 1316} 1317 1318/// getOrInsertCanonicalInductionVariable - This method returns the 1319/// canonical induction variable of the specified type for the specified 1320/// loop (inserting one if there is none). A canonical induction variable 1321/// starts at zero and steps by one on each iteration. 1322Value * 1323SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L, 1324 const Type *Ty) { 1325 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!"); 1326 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty), 1327 SE.getIntegerSCEV(1, Ty), L); 1328 BasicBlock *SaveInsertBB = Builder.GetInsertBlock(); 1329 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint(); 1330 Value *V = expandCodeFor(H, 0, L->getHeader()->begin()); 1331 if (SaveInsertBB) 1332 restoreInsertPoint(SaveInsertBB, SaveInsertPt); 1333 return V; 1334} 1335