~louis/ubuntu/trusty/clamav/lp799623_fix_logrotate

« back to all changes in this revision

Viewing changes to libclamav/c++/llvm/lib/Analysis/ScalarEvolution.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Scott Kitterman
  • Date: 2010-03-12 11:30:04 UTC
  • mfrom: (0.41.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20100312113004-b0fop4bkycszdd0z
Tags: 0.96~rc1+dfsg-0ubuntu1
* New upstream RC - FFE (LP: #537636):
  - Add OfficialDatabaseOnly option to clamav-base.postinst.in
  - Add LocalSocketGroup option to clamav-base.postinst.in
  - Add LocalSocketMode option to clamav-base.postinst.in
  - Add CrossFilesystems option to clamav-base.postinst.in
  - Add ClamukoScannerCount option to clamav-base.postinst.in
  - Add BytecodeSecurity opiton to clamav-base.postinst.in
  - Add DetectionStatsHostID option to clamav-freshclam.postinst.in
  - Add Bytecode option to clamav-freshclam.postinst.in
  - Add MilterSocketGroup option to clamav-milter.postinst.in
  - Add MilterSocketMode option to clamav-milter.postinst.in
  - Add ReportHostname option to clamav-milter.postinst.in
  - Bump libclamav SO version to 6.1.0 in libclamav6.install
  - Drop clamdmon from clamav.examples (no longer shipped by upstream)
  - Drop libclamav.a from libclamav-dev.install (not built by upstream)
  - Update SO version for lintian override for libclamav6
  - Add new Bytecode Testing Tool, usr/bin/clambc, to clamav.install
  - Add build-depends on python and python-setuptools for new test suite
  - Update debian/copyright for the embedded copy of llvm (using the system
    llvm is not currently feasible)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
 
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
// This file contains the implementation of the scalar evolution analysis
 
11
// engine, which is used primarily to analyze expressions involving induction
 
12
// variables in loops.
 
13
//
 
14
// There are several aspects to this library.  First is the representation of
 
15
// scalar expressions, which are represented as subclasses of the SCEV class.
 
16
// These classes are used to represent certain types of subexpressions that we
 
17
// can handle. We only create one SCEV of a particular shape, so
 
18
// pointer-comparisons for equality are legal.
 
19
//
 
20
// One important aspect of the SCEV objects is that they are never cyclic, even
 
21
// if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
 
22
// the PHI node is one of the idioms that we can represent (e.g., a polynomial
 
23
// recurrence) then we represent it directly as a recurrence node, otherwise we
 
24
// represent it as a SCEVUnknown node.
 
25
//
 
26
// In addition to being able to represent expressions of various types, we also
 
27
// have folders that are used to build the *canonical* representation for a
 
28
// particular expression.  These folders are capable of using a variety of
 
29
// rewrite rules to simplify the expressions.
 
30
//
 
31
// Once the folders are defined, we can implement the more interesting
 
32
// higher-level code, such as the code that recognizes PHI nodes of various
 
33
// types, computes the execution count of a loop, etc.
 
34
//
 
35
// TODO: We should use these routines and value representations to implement
 
36
// dependence analysis!
 
37
//
 
38
//===----------------------------------------------------------------------===//
 
39
//
 
40
// There are several good references for the techniques used in this analysis.
 
41
//
 
42
//  Chains of recurrences -- a method to expedite the evaluation
 
43
//  of closed-form functions
 
44
//  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
 
45
//
 
46
//  On computational properties of chains of recurrences
 
47
//  Eugene V. Zima
 
48
//
 
49
//  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
 
50
//  Robert A. van Engelen
 
51
//
 
52
//  Efficient Symbolic Analysis for Optimizing Compilers
 
53
//  Robert A. van Engelen
 
54
//
 
55
//  Using the chains of recurrences algebra for data dependence testing and
 
56
//  induction variable substitution
 
57
//  MS Thesis, Johnie Birch
 
58
//
 
59
//===----------------------------------------------------------------------===//
 
60
 
 
61
#define DEBUG_TYPE "scalar-evolution"
 
62
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
 
63
#include "llvm/Constants.h"
 
64
#include "llvm/DerivedTypes.h"
 
65
#include "llvm/GlobalVariable.h"
 
66
#include "llvm/GlobalAlias.h"
 
67
#include "llvm/Instructions.h"
 
68
#include "llvm/LLVMContext.h"
 
69
#include "llvm/Operator.h"
 
70
#include "llvm/Analysis/ConstantFolding.h"
 
71
#include "llvm/Analysis/Dominators.h"
 
72
#include "llvm/Analysis/LoopInfo.h"
 
73
#include "llvm/Analysis/ValueTracking.h"
 
74
#include "llvm/Assembly/Writer.h"
 
75
#include "llvm/Target/TargetData.h"
 
76
#include "llvm/Support/CommandLine.h"
 
77
#include "llvm/Support/ConstantRange.h"
 
78
#include "llvm/Support/Debug.h"
 
79
#include "llvm/Support/ErrorHandling.h"
 
80
#include "llvm/Support/GetElementPtrTypeIterator.h"
 
81
#include "llvm/Support/InstIterator.h"
 
82
#include "llvm/Support/MathExtras.h"
 
83
#include "llvm/Support/raw_ostream.h"
 
84
#include "llvm/ADT/Statistic.h"
 
85
#include "llvm/ADT/STLExtras.h"
 
86
#include "llvm/ADT/SmallPtrSet.h"
 
87
#include <algorithm>
 
88
using namespace llvm;
 
89
 
 
90
STATISTIC(NumArrayLenItCounts,
 
91
          "Number of trip counts computed with array length");
 
92
STATISTIC(NumTripCountsComputed,
 
93
          "Number of loops with predictable loop counts");
 
94
STATISTIC(NumTripCountsNotComputed,
 
95
          "Number of loops without predictable loop counts");
 
96
STATISTIC(NumBruteForceTripCountsComputed,
 
97
          "Number of loops with trip counts computed by force");
 
98
 
 
99
static cl::opt<unsigned>
 
100
MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
 
101
                        cl::desc("Maximum number of iterations SCEV will "
 
102
                                 "symbolically execute a constant "
 
103
                                 "derived loop"),
 
104
                        cl::init(100));
 
105
 
 
106
static RegisterPass<ScalarEvolution>
 
107
R("scalar-evolution", "Scalar Evolution Analysis", false, true);
 
108
char ScalarEvolution::ID = 0;
 
109
 
 
110
//===----------------------------------------------------------------------===//
 
111
//                           SCEV class definitions
 
112
//===----------------------------------------------------------------------===//
 
113
 
 
114
//===----------------------------------------------------------------------===//
 
115
// Implementation of the SCEV class.
 
116
//
 
117
 
 
118
SCEV::~SCEV() {}
 
119
 
 
120
void SCEV::dump() const {
 
121
  print(dbgs());
 
122
  dbgs() << '\n';
 
123
}
 
124
 
 
125
bool SCEV::isZero() const {
 
126
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
 
127
    return SC->getValue()->isZero();
 
128
  return false;
 
129
}
 
130
 
 
131
bool SCEV::isOne() const {
 
132
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
 
133
    return SC->getValue()->isOne();
 
134
  return false;
 
135
}
 
136
 
 
137
bool SCEV::isAllOnesValue() const {
 
138
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
 
139
    return SC->getValue()->isAllOnesValue();
 
140
  return false;
 
141
}
 
142
 
 
143
SCEVCouldNotCompute::SCEVCouldNotCompute() :
 
144
  SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
 
145
 
 
146
bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
 
147
  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
 
148
  return false;
 
149
}
 
150
 
 
151
const Type *SCEVCouldNotCompute::getType() const {
 
152
  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
 
153
  return 0;
 
154
}
 
155
 
 
156
bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
 
157
  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
 
158
  return false;
 
159
}
 
160
 
 
161
bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
 
162
  llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
 
163
  return false;
 
164
}
 
165
 
 
166
void SCEVCouldNotCompute::print(raw_ostream &OS) const {
 
167
  OS << "***COULDNOTCOMPUTE***";
 
168
}
 
169
 
 
170
bool SCEVCouldNotCompute::classof(const SCEV *S) {
 
171
  return S->getSCEVType() == scCouldNotCompute;
 
172
}
 
173
 
 
174
const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
 
175
  FoldingSetNodeID ID;
 
176
  ID.AddInteger(scConstant);
 
177
  ID.AddPointer(V);
 
178
  void *IP = 0;
 
179
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
180
  SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
 
181
  new (S) SCEVConstant(ID, V);
 
182
  UniqueSCEVs.InsertNode(S, IP);
 
183
  return S;
 
184
}
 
185
 
 
186
const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
 
187
  return getConstant(ConstantInt::get(getContext(), Val));
 
188
}
 
189
 
 
190
const SCEV *
 
191
ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
 
192
  return getConstant(
 
193
    ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
 
194
}
 
195
 
 
196
const Type *SCEVConstant::getType() const { return V->getType(); }
 
197
 
 
198
void SCEVConstant::print(raw_ostream &OS) const {
 
199
  WriteAsOperand(OS, V, false);
 
200
}
 
201
 
 
202
SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
 
203
                           unsigned SCEVTy, const SCEV *op, const Type *ty)
 
204
  : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
 
205
 
 
206
bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
 
207
  return Op->dominates(BB, DT);
 
208
}
 
209
 
 
210
bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
 
211
  return Op->properlyDominates(BB, DT);
 
212
}
 
213
 
 
214
SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
 
215
                                   const SCEV *op, const Type *ty)
 
216
  : SCEVCastExpr(ID, scTruncate, op, ty) {
 
217
  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
 
218
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
219
         "Cannot truncate non-integer value!");
 
220
}
 
221
 
 
222
void SCEVTruncateExpr::print(raw_ostream &OS) const {
 
223
  OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
 
224
}
 
225
 
 
226
SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
 
227
                                       const SCEV *op, const Type *ty)
 
228
  : SCEVCastExpr(ID, scZeroExtend, op, ty) {
 
229
  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
 
230
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
231
         "Cannot zero extend non-integer value!");
 
232
}
 
233
 
 
234
void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
 
235
  OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
 
236
}
 
237
 
 
238
SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
 
239
                                       const SCEV *op, const Type *ty)
 
240
  : SCEVCastExpr(ID, scSignExtend, op, ty) {
 
241
  assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
 
242
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
243
         "Cannot sign extend non-integer value!");
 
244
}
 
245
 
 
246
void SCEVSignExtendExpr::print(raw_ostream &OS) const {
 
247
  OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
 
248
}
 
249
 
 
250
void SCEVCommutativeExpr::print(raw_ostream &OS) const {
 
251
  assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
 
252
  const char *OpStr = getOperationStr();
 
253
  OS << "(" << *Operands[0];
 
254
  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
 
255
    OS << OpStr << *Operands[i];
 
256
  OS << ")";
 
257
}
 
258
 
 
259
bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
 
260
  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
 
261
    if (!getOperand(i)->dominates(BB, DT))
 
262
      return false;
 
263
  }
 
264
  return true;
 
265
}
 
266
 
 
267
bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
 
268
  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
 
269
    if (!getOperand(i)->properlyDominates(BB, DT))
 
270
      return false;
 
271
  }
 
272
  return true;
 
273
}
 
274
 
 
275
bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
 
276
  return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
 
277
}
 
278
 
 
279
bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
 
280
  return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
 
281
}
 
282
 
 
283
void SCEVUDivExpr::print(raw_ostream &OS) const {
 
284
  OS << "(" << *LHS << " /u " << *RHS << ")";
 
285
}
 
286
 
 
287
const Type *SCEVUDivExpr::getType() const {
 
288
  // In most cases the types of LHS and RHS will be the same, but in some
 
289
  // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
 
290
  // depend on the type for correctness, but handling types carefully can
 
291
  // avoid extra casts in the SCEVExpander. The LHS is more likely to be
 
292
  // a pointer type than the RHS, so use the RHS' type here.
 
293
  return RHS->getType();
 
294
}
 
295
 
 
296
bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
 
297
  // Add recurrences are never invariant in the function-body (null loop).
 
298
  if (!QueryLoop)
 
299
    return false;
 
300
 
 
301
  // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
 
302
  if (QueryLoop->contains(L))
 
303
    return false;
 
304
 
 
305
  // This recurrence is variant w.r.t. QueryLoop if any of its operands
 
306
  // are variant.
 
307
  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
 
308
    if (!getOperand(i)->isLoopInvariant(QueryLoop))
 
309
      return false;
 
310
 
 
311
  // Otherwise it's loop-invariant.
 
312
  return true;
 
313
}
 
314
 
 
315
bool
 
316
SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
 
317
  return DT->dominates(L->getHeader(), BB) &&
 
318
         SCEVNAryExpr::dominates(BB, DT);
 
319
}
 
320
 
 
321
bool
 
322
SCEVAddRecExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
 
323
  // This uses a "dominates" query instead of "properly dominates" query because
 
324
  // the instruction which produces the addrec's value is a PHI, and a PHI
 
325
  // effectively properly dominates its entire containing block.
 
326
  return DT->dominates(L->getHeader(), BB) &&
 
327
         SCEVNAryExpr::properlyDominates(BB, DT);
 
328
}
 
329
 
 
330
void SCEVAddRecExpr::print(raw_ostream &OS) const {
 
331
  OS << "{" << *Operands[0];
 
332
  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
 
333
    OS << ",+," << *Operands[i];
 
334
  OS << "}<";
 
335
  WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
 
336
  OS << ">";
 
337
}
 
338
 
 
339
bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
 
340
  // All non-instruction values are loop invariant.  All instructions are loop
 
341
  // invariant if they are not contained in the specified loop.
 
342
  // Instructions are never considered invariant in the function body
 
343
  // (null loop) because they are defined within the "loop".
 
344
  if (Instruction *I = dyn_cast<Instruction>(V))
 
345
    return L && !L->contains(I);
 
346
  return true;
 
347
}
 
348
 
 
349
bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
 
350
  if (Instruction *I = dyn_cast<Instruction>(getValue()))
 
351
    return DT->dominates(I->getParent(), BB);
 
352
  return true;
 
353
}
 
354
 
 
355
bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
 
356
  if (Instruction *I = dyn_cast<Instruction>(getValue()))
 
357
    return DT->properlyDominates(I->getParent(), BB);
 
358
  return true;
 
359
}
 
360
 
 
361
const Type *SCEVUnknown::getType() const {
 
362
  return V->getType();
 
363
}
 
364
 
 
365
bool SCEVUnknown::isSizeOf(const Type *&AllocTy) const {
 
366
  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
 
367
    if (VCE->getOpcode() == Instruction::PtrToInt)
 
368
      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
 
369
        if (CE->getOpcode() == Instruction::GetElementPtr &&
 
370
            CE->getOperand(0)->isNullValue() &&
 
371
            CE->getNumOperands() == 2)
 
372
          if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
 
373
            if (CI->isOne()) {
 
374
              AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
 
375
                                 ->getElementType();
 
376
              return true;
 
377
            }
 
378
 
 
379
  return false;
 
380
}
 
381
 
 
382
bool SCEVUnknown::isAlignOf(const Type *&AllocTy) const {
 
383
  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
 
384
    if (VCE->getOpcode() == Instruction::PtrToInt)
 
385
      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
 
386
        if (CE->getOpcode() == Instruction::GetElementPtr &&
 
387
            CE->getOperand(0)->isNullValue()) {
 
388
          const Type *Ty =
 
389
            cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
 
390
          if (const StructType *STy = dyn_cast<StructType>(Ty))
 
391
            if (!STy->isPacked() &&
 
392
                CE->getNumOperands() == 3 &&
 
393
                CE->getOperand(1)->isNullValue()) {
 
394
              if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
 
395
                if (CI->isOne() &&
 
396
                    STy->getNumElements() == 2 &&
 
397
                    STy->getElementType(0)->isIntegerTy(1)) {
 
398
                  AllocTy = STy->getElementType(1);
 
399
                  return true;
 
400
                }
 
401
            }
 
402
        }
 
403
 
 
404
  return false;
 
405
}
 
406
 
 
407
bool SCEVUnknown::isOffsetOf(const Type *&CTy, Constant *&FieldNo) const {
 
408
  if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(V))
 
409
    if (VCE->getOpcode() == Instruction::PtrToInt)
 
410
      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
 
411
        if (CE->getOpcode() == Instruction::GetElementPtr &&
 
412
            CE->getNumOperands() == 3 &&
 
413
            CE->getOperand(0)->isNullValue() &&
 
414
            CE->getOperand(1)->isNullValue()) {
 
415
          const Type *Ty =
 
416
            cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
 
417
          // Ignore vector types here so that ScalarEvolutionExpander doesn't
 
418
          // emit getelementptrs that index into vectors.
 
419
          if (Ty->isStructTy() || Ty->isArrayTy()) {
 
420
            CTy = Ty;
 
421
            FieldNo = CE->getOperand(2);
 
422
            return true;
 
423
          }
 
424
        }
 
425
 
 
426
  return false;
 
427
}
 
428
 
 
429
void SCEVUnknown::print(raw_ostream &OS) const {
 
430
  const Type *AllocTy;
 
431
  if (isSizeOf(AllocTy)) {
 
432
    OS << "sizeof(" << *AllocTy << ")";
 
433
    return;
 
434
  }
 
435
  if (isAlignOf(AllocTy)) {
 
436
    OS << "alignof(" << *AllocTy << ")";
 
437
    return;
 
438
  }
 
439
 
 
440
  const Type *CTy;
 
441
  Constant *FieldNo;
 
442
  if (isOffsetOf(CTy, FieldNo)) {
 
443
    OS << "offsetof(" << *CTy << ", ";
 
444
    WriteAsOperand(OS, FieldNo, false);
 
445
    OS << ")";
 
446
    return;
 
447
  }
 
448
 
 
449
  // Otherwise just print it normally.
 
450
  WriteAsOperand(OS, V, false);
 
451
}
 
452
 
 
453
//===----------------------------------------------------------------------===//
 
454
//                               SCEV Utilities
 
455
//===----------------------------------------------------------------------===//
 
456
 
 
457
static bool CompareTypes(const Type *A, const Type *B) {
 
458
  if (A->getTypeID() != B->getTypeID())
 
459
    return A->getTypeID() < B->getTypeID();
 
460
  if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
 
461
    const IntegerType *BI = cast<IntegerType>(B);
 
462
    return AI->getBitWidth() < BI->getBitWidth();
 
463
  }
 
464
  if (const PointerType *AI = dyn_cast<PointerType>(A)) {
 
465
    const PointerType *BI = cast<PointerType>(B);
 
466
    return CompareTypes(AI->getElementType(), BI->getElementType());
 
467
  }
 
468
  if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
 
469
    const ArrayType *BI = cast<ArrayType>(B);
 
470
    if (AI->getNumElements() != BI->getNumElements())
 
471
      return AI->getNumElements() < BI->getNumElements();
 
472
    return CompareTypes(AI->getElementType(), BI->getElementType());
 
473
  }
 
474
  if (const VectorType *AI = dyn_cast<VectorType>(A)) {
 
475
    const VectorType *BI = cast<VectorType>(B);
 
476
    if (AI->getNumElements() != BI->getNumElements())
 
477
      return AI->getNumElements() < BI->getNumElements();
 
478
    return CompareTypes(AI->getElementType(), BI->getElementType());
 
479
  }
 
480
  if (const StructType *AI = dyn_cast<StructType>(A)) {
 
481
    const StructType *BI = cast<StructType>(B);
 
482
    if (AI->getNumElements() != BI->getNumElements())
 
483
      return AI->getNumElements() < BI->getNumElements();
 
484
    for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
 
485
      if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
 
486
          CompareTypes(BI->getElementType(i), AI->getElementType(i)))
 
487
        return CompareTypes(AI->getElementType(i), BI->getElementType(i));
 
488
  }
 
489
  return false;
 
490
}
 
491
 
 
492
namespace {
 
493
  /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
 
494
  /// than the complexity of the RHS.  This comparator is used to canonicalize
 
495
  /// expressions.
 
496
  class SCEVComplexityCompare {
 
497
    LoopInfo *LI;
 
498
  public:
 
499
    explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
 
500
 
 
501
    bool operator()(const SCEV *LHS, const SCEV *RHS) const {
 
502
      // Fast-path: SCEVs are uniqued so we can do a quick equality check.
 
503
      if (LHS == RHS)
 
504
        return false;
 
505
 
 
506
      // Primarily, sort the SCEVs by their getSCEVType().
 
507
      if (LHS->getSCEVType() != RHS->getSCEVType())
 
508
        return LHS->getSCEVType() < RHS->getSCEVType();
 
509
 
 
510
      // Aside from the getSCEVType() ordering, the particular ordering
 
511
      // isn't very important except that it's beneficial to be consistent,
 
512
      // so that (a + b) and (b + a) don't end up as different expressions.
 
513
 
 
514
      // Sort SCEVUnknown values with some loose heuristics. TODO: This is
 
515
      // not as complete as it could be.
 
516
      if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
 
517
        const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
 
518
 
 
519
        // Order pointer values after integer values. This helps SCEVExpander
 
520
        // form GEPs.
 
521
        if (LU->getType()->isPointerTy() && !RU->getType()->isPointerTy())
 
522
          return false;
 
523
        if (RU->getType()->isPointerTy() && !LU->getType()->isPointerTy())
 
524
          return true;
 
525
 
 
526
        // Compare getValueID values.
 
527
        if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
 
528
          return LU->getValue()->getValueID() < RU->getValue()->getValueID();
 
529
 
 
530
        // Sort arguments by their position.
 
531
        if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
 
532
          const Argument *RA = cast<Argument>(RU->getValue());
 
533
          return LA->getArgNo() < RA->getArgNo();
 
534
        }
 
535
 
 
536
        // For instructions, compare their loop depth, and their opcode.
 
537
        // This is pretty loose.
 
538
        if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
 
539
          Instruction *RV = cast<Instruction>(RU->getValue());
 
540
 
 
541
          // Compare loop depths.
 
542
          if (LI->getLoopDepth(LV->getParent()) !=
 
543
              LI->getLoopDepth(RV->getParent()))
 
544
            return LI->getLoopDepth(LV->getParent()) <
 
545
                   LI->getLoopDepth(RV->getParent());
 
546
 
 
547
          // Compare opcodes.
 
548
          if (LV->getOpcode() != RV->getOpcode())
 
549
            return LV->getOpcode() < RV->getOpcode();
 
550
 
 
551
          // Compare the number of operands.
 
552
          if (LV->getNumOperands() != RV->getNumOperands())
 
553
            return LV->getNumOperands() < RV->getNumOperands();
 
554
        }
 
555
 
 
556
        return false;
 
557
      }
 
558
 
 
559
      // Compare constant values.
 
560
      if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
 
561
        const SCEVConstant *RC = cast<SCEVConstant>(RHS);
 
562
        if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
 
563
          return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
 
564
        return LC->getValue()->getValue().ult(RC->getValue()->getValue());
 
565
      }
 
566
 
 
567
      // Compare addrec loop depths.
 
568
      if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
 
569
        const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
 
570
        if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
 
571
          return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
 
572
      }
 
573
 
 
574
      // Lexicographically compare n-ary expressions.
 
575
      if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
 
576
        const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
 
577
        for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
 
578
          if (i >= RC->getNumOperands())
 
579
            return false;
 
580
          if (operator()(LC->getOperand(i), RC->getOperand(i)))
 
581
            return true;
 
582
          if (operator()(RC->getOperand(i), LC->getOperand(i)))
 
583
            return false;
 
584
        }
 
585
        return LC->getNumOperands() < RC->getNumOperands();
 
586
      }
 
587
 
 
588
      // Lexicographically compare udiv expressions.
 
589
      if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
 
590
        const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
 
591
        if (operator()(LC->getLHS(), RC->getLHS()))
 
592
          return true;
 
593
        if (operator()(RC->getLHS(), LC->getLHS()))
 
594
          return false;
 
595
        if (operator()(LC->getRHS(), RC->getRHS()))
 
596
          return true;
 
597
        if (operator()(RC->getRHS(), LC->getRHS()))
 
598
          return false;
 
599
        return false;
 
600
      }
 
601
 
 
602
      // Compare cast expressions by operand.
 
603
      if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
 
604
        const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
 
605
        return operator()(LC->getOperand(), RC->getOperand());
 
606
      }
 
607
 
 
608
      llvm_unreachable("Unknown SCEV kind!");
 
609
      return false;
 
610
    }
 
611
  };
 
612
}
 
613
 
 
614
/// GroupByComplexity - Given a list of SCEV objects, order them by their
 
615
/// complexity, and group objects of the same complexity together by value.
 
616
/// When this routine is finished, we know that any duplicates in the vector are
 
617
/// consecutive and that complexity is monotonically increasing.
 
618
///
 
619
/// Note that we go take special precautions to ensure that we get deterministic
 
620
/// results from this routine.  In other words, we don't want the results of
 
621
/// this to depend on where the addresses of various SCEV objects happened to
 
622
/// land in memory.
 
623
///
 
624
static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
 
625
                              LoopInfo *LI) {
 
626
  if (Ops.size() < 2) return;  // Noop
 
627
  if (Ops.size() == 2) {
 
628
    // This is the common case, which also happens to be trivially simple.
 
629
    // Special case it.
 
630
    if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
 
631
      std::swap(Ops[0], Ops[1]);
 
632
    return;
 
633
  }
 
634
 
 
635
  // Do the rough sort by complexity.
 
636
  std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
 
637
 
 
638
  // Now that we are sorted by complexity, group elements of the same
 
639
  // complexity.  Note that this is, at worst, N^2, but the vector is likely to
 
640
  // be extremely short in practice.  Note that we take this approach because we
 
641
  // do not want to depend on the addresses of the objects we are grouping.
 
642
  for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
 
643
    const SCEV *S = Ops[i];
 
644
    unsigned Complexity = S->getSCEVType();
 
645
 
 
646
    // If there are any objects of the same complexity and same value as this
 
647
    // one, group them.
 
648
    for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
 
649
      if (Ops[j] == S) { // Found a duplicate.
 
650
        // Move it to immediately after i'th element.
 
651
        std::swap(Ops[i+1], Ops[j]);
 
652
        ++i;   // no need to rescan it.
 
653
        if (i == e-2) return;  // Done!
 
654
      }
 
655
    }
 
656
  }
 
657
}
 
658
 
 
659
 
 
660
 
 
661
//===----------------------------------------------------------------------===//
 
662
//                      Simple SCEV method implementations
 
663
//===----------------------------------------------------------------------===//
 
664
 
 
665
/// BinomialCoefficient - Compute BC(It, K).  The result has width W.
 
666
/// Assume, K > 0.
 
667
static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
 
668
                                       ScalarEvolution &SE,
 
669
                                       const Type* ResultTy) {
 
670
  // Handle the simplest case efficiently.
 
671
  if (K == 1)
 
672
    return SE.getTruncateOrZeroExtend(It, ResultTy);
 
673
 
 
674
  // We are using the following formula for BC(It, K):
 
675
  //
 
676
  //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
 
677
  //
 
678
  // Suppose, W is the bitwidth of the return value.  We must be prepared for
 
679
  // overflow.  Hence, we must assure that the result of our computation is
 
680
  // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
 
681
  // safe in modular arithmetic.
 
682
  //
 
683
  // However, this code doesn't use exactly that formula; the formula it uses
 
684
  // is something like the following, where T is the number of factors of 2 in
 
685
  // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
 
686
  // exponentiation:
 
687
  //
 
688
  //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
 
689
  //
 
690
  // This formula is trivially equivalent to the previous formula.  However,
 
691
  // this formula can be implemented much more efficiently.  The trick is that
 
692
  // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
 
693
  // arithmetic.  To do exact division in modular arithmetic, all we have
 
694
  // to do is multiply by the inverse.  Therefore, this step can be done at
 
695
  // width W.
 
696
  //
 
697
  // The next issue is how to safely do the division by 2^T.  The way this
 
698
  // is done is by doing the multiplication step at a width of at least W + T
 
699
  // bits.  This way, the bottom W+T bits of the product are accurate. Then,
 
700
  // when we perform the division by 2^T (which is equivalent to a right shift
 
701
  // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
 
702
  // truncated out after the division by 2^T.
 
703
  //
 
704
  // In comparison to just directly using the first formula, this technique
 
705
  // is much more efficient; using the first formula requires W * K bits,
 
706
  // but this formula less than W + K bits. Also, the first formula requires
 
707
  // a division step, whereas this formula only requires multiplies and shifts.
 
708
  //
 
709
  // It doesn't matter whether the subtraction step is done in the calculation
 
710
  // width or the input iteration count's width; if the subtraction overflows,
 
711
  // the result must be zero anyway.  We prefer here to do it in the width of
 
712
  // the induction variable because it helps a lot for certain cases; CodeGen
 
713
  // isn't smart enough to ignore the overflow, which leads to much less
 
714
  // efficient code if the width of the subtraction is wider than the native
 
715
  // register width.
 
716
  //
 
717
  // (It's possible to not widen at all by pulling out factors of 2 before
 
718
  // the multiplication; for example, K=2 can be calculated as
 
719
  // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
 
720
  // extra arithmetic, so it's not an obvious win, and it gets
 
721
  // much more complicated for K > 3.)
 
722
 
 
723
  // Protection from insane SCEVs; this bound is conservative,
 
724
  // but it probably doesn't matter.
 
725
  if (K > 1000)
 
726
    return SE.getCouldNotCompute();
 
727
 
 
728
  unsigned W = SE.getTypeSizeInBits(ResultTy);
 
729
 
 
730
  // Calculate K! / 2^T and T; we divide out the factors of two before
 
731
  // multiplying for calculating K! / 2^T to avoid overflow.
 
732
  // Other overflow doesn't matter because we only care about the bottom
 
733
  // W bits of the result.
 
734
  APInt OddFactorial(W, 1);
 
735
  unsigned T = 1;
 
736
  for (unsigned i = 3; i <= K; ++i) {
 
737
    APInt Mult(W, i);
 
738
    unsigned TwoFactors = Mult.countTrailingZeros();
 
739
    T += TwoFactors;
 
740
    Mult = Mult.lshr(TwoFactors);
 
741
    OddFactorial *= Mult;
 
742
  }
 
743
 
 
744
  // We need at least W + T bits for the multiplication step
 
745
  unsigned CalculationBits = W + T;
 
746
 
 
747
  // Calculate 2^T, at width T+W.
 
748
  APInt DivFactor = APInt(CalculationBits, 1).shl(T);
 
749
 
 
750
  // Calculate the multiplicative inverse of K! / 2^T;
 
751
  // this multiplication factor will perform the exact division by
 
752
  // K! / 2^T.
 
753
  APInt Mod = APInt::getSignedMinValue(W+1);
 
754
  APInt MultiplyFactor = OddFactorial.zext(W+1);
 
755
  MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
 
756
  MultiplyFactor = MultiplyFactor.trunc(W);
 
757
 
 
758
  // Calculate the product, at width T+W
 
759
  const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
 
760
                                                      CalculationBits);
 
761
  const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
 
762
  for (unsigned i = 1; i != K; ++i) {
 
763
    const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
 
764
    Dividend = SE.getMulExpr(Dividend,
 
765
                             SE.getTruncateOrZeroExtend(S, CalculationTy));
 
766
  }
 
767
 
 
768
  // Divide by 2^T
 
769
  const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
 
770
 
 
771
  // Truncate the result, and divide by K! / 2^T.
 
772
 
 
773
  return SE.getMulExpr(SE.getConstant(MultiplyFactor),
 
774
                       SE.getTruncateOrZeroExtend(DivResult, ResultTy));
 
775
}
 
776
 
 
777
/// evaluateAtIteration - Return the value of this chain of recurrences at
 
778
/// the specified iteration number.  We can evaluate this recurrence by
 
779
/// multiplying each element in the chain by the binomial coefficient
 
780
/// corresponding to it.  In other words, we can evaluate {A,+,B,+,C,+,D} as:
 
781
///
 
782
///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
 
783
///
 
784
/// where BC(It, k) stands for binomial coefficient.
 
785
///
 
786
const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
 
787
                                                ScalarEvolution &SE) const {
 
788
  const SCEV *Result = getStart();
 
789
  for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
 
790
    // The computation is correct in the face of overflow provided that the
 
791
    // multiplication is performed _after_ the evaluation of the binomial
 
792
    // coefficient.
 
793
    const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
 
794
    if (isa<SCEVCouldNotCompute>(Coeff))
 
795
      return Coeff;
 
796
 
 
797
    Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
 
798
  }
 
799
  return Result;
 
800
}
 
801
 
 
802
//===----------------------------------------------------------------------===//
 
803
//                    SCEV Expression folder implementations
 
804
//===----------------------------------------------------------------------===//
 
805
 
 
806
const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
 
807
                                             const Type *Ty) {
 
808
  assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
 
809
         "This is not a truncating conversion!");
 
810
  assert(isSCEVable(Ty) &&
 
811
         "This is not a conversion to a SCEVable type!");
 
812
  Ty = getEffectiveSCEVType(Ty);
 
813
 
 
814
  FoldingSetNodeID ID;
 
815
  ID.AddInteger(scTruncate);
 
816
  ID.AddPointer(Op);
 
817
  ID.AddPointer(Ty);
 
818
  void *IP = 0;
 
819
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
820
 
 
821
  // Fold if the operand is constant.
 
822
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
 
823
    return getConstant(
 
824
      cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
 
825
 
 
826
  // trunc(trunc(x)) --> trunc(x)
 
827
  if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
 
828
    return getTruncateExpr(ST->getOperand(), Ty);
 
829
 
 
830
  // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
 
831
  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
 
832
    return getTruncateOrSignExtend(SS->getOperand(), Ty);
 
833
 
 
834
  // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
 
835
  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
 
836
    return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
 
837
 
 
838
  // If the input value is a chrec scev, truncate the chrec's operands.
 
839
  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
 
840
    SmallVector<const SCEV *, 4> Operands;
 
841
    for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
 
842
      Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
 
843
    return getAddRecExpr(Operands, AddRec->getLoop());
 
844
  }
 
845
 
 
846
  // The cast wasn't folded; create an explicit cast node.
 
847
  // Recompute the insert position, as it may have been invalidated.
 
848
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
849
  SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
 
850
  new (S) SCEVTruncateExpr(ID, Op, Ty);
 
851
  UniqueSCEVs.InsertNode(S, IP);
 
852
  return S;
 
853
}
 
854
 
 
855
const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
 
856
                                               const Type *Ty) {
 
857
  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
 
858
         "This is not an extending conversion!");
 
859
  assert(isSCEVable(Ty) &&
 
860
         "This is not a conversion to a SCEVable type!");
 
861
  Ty = getEffectiveSCEVType(Ty);
 
862
 
 
863
  // Fold if the operand is constant.
 
864
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
 
865
    const Type *IntTy = getEffectiveSCEVType(Ty);
 
866
    Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
 
867
    if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
 
868
    return getConstant(cast<ConstantInt>(C));
 
869
  }
 
870
 
 
871
  // zext(zext(x)) --> zext(x)
 
872
  if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
 
873
    return getZeroExtendExpr(SZ->getOperand(), Ty);
 
874
 
 
875
  // Before doing any expensive analysis, check to see if we've already
 
876
  // computed a SCEV for this Op and Ty.
 
877
  FoldingSetNodeID ID;
 
878
  ID.AddInteger(scZeroExtend);
 
879
  ID.AddPointer(Op);
 
880
  ID.AddPointer(Ty);
 
881
  void *IP = 0;
 
882
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
883
 
 
884
  // If the input value is a chrec scev, and we can prove that the value
 
885
  // did not overflow the old, smaller, value, we can zero extend all of the
 
886
  // operands (often constants).  This allows analysis of something like
 
887
  // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
 
888
  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
 
889
    if (AR->isAffine()) {
 
890
      const SCEV *Start = AR->getStart();
 
891
      const SCEV *Step = AR->getStepRecurrence(*this);
 
892
      unsigned BitWidth = getTypeSizeInBits(AR->getType());
 
893
      const Loop *L = AR->getLoop();
 
894
 
 
895
      // If we have special knowledge that this addrec won't overflow,
 
896
      // we don't need to do any further analysis.
 
897
      if (AR->hasNoUnsignedWrap())
 
898
        return getAddRecExpr(getZeroExtendExpr(Start, Ty),
 
899
                             getZeroExtendExpr(Step, Ty),
 
900
                             L);
 
901
 
 
902
      // Check whether the backedge-taken count is SCEVCouldNotCompute.
 
903
      // Note that this serves two purposes: It filters out loops that are
 
904
      // simply not analyzable, and it covers the case where this code is
 
905
      // being called from within backedge-taken count analysis, such that
 
906
      // attempting to ask for the backedge-taken count would likely result
 
907
      // in infinite recursion. In the later case, the analysis code will
 
908
      // cope with a conservative value, and it will take care to purge
 
909
      // that value once it has finished.
 
910
      const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
 
911
      if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
 
912
        // Manually compute the final value for AR, checking for
 
913
        // overflow.
 
914
 
 
915
        // Check whether the backedge-taken count can be losslessly casted to
 
916
        // the addrec's type. The count is always unsigned.
 
917
        const SCEV *CastedMaxBECount =
 
918
          getTruncateOrZeroExtend(MaxBECount, Start->getType());
 
919
        const SCEV *RecastedMaxBECount =
 
920
          getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
 
921
        if (MaxBECount == RecastedMaxBECount) {
 
922
          const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
 
923
          // Check whether Start+Step*MaxBECount has no unsigned overflow.
 
924
          const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
 
925
          const SCEV *Add = getAddExpr(Start, ZMul);
 
926
          const SCEV *OperandExtendedAdd =
 
927
            getAddExpr(getZeroExtendExpr(Start, WideTy),
 
928
                       getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
 
929
                                  getZeroExtendExpr(Step, WideTy)));
 
930
          if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
 
931
            // Return the expression with the addrec on the outside.
 
932
            return getAddRecExpr(getZeroExtendExpr(Start, Ty),
 
933
                                 getZeroExtendExpr(Step, Ty),
 
934
                                 L);
 
935
 
 
936
          // Similar to above, only this time treat the step value as signed.
 
937
          // This covers loops that count down.
 
938
          const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
 
939
          Add = getAddExpr(Start, SMul);
 
940
          OperandExtendedAdd =
 
941
            getAddExpr(getZeroExtendExpr(Start, WideTy),
 
942
                       getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
 
943
                                  getSignExtendExpr(Step, WideTy)));
 
944
          if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
 
945
            // Return the expression with the addrec on the outside.
 
946
            return getAddRecExpr(getZeroExtendExpr(Start, Ty),
 
947
                                 getSignExtendExpr(Step, Ty),
 
948
                                 L);
 
949
        }
 
950
 
 
951
        // If the backedge is guarded by a comparison with the pre-inc value
 
952
        // the addrec is safe. Also, if the entry is guarded by a comparison
 
953
        // with the start value and the backedge is guarded by a comparison
 
954
        // with the post-inc value, the addrec is safe.
 
955
        if (isKnownPositive(Step)) {
 
956
          const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
 
957
                                      getUnsignedRange(Step).getUnsignedMax());
 
958
          if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
 
959
              (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
 
960
               isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
 
961
                                           AR->getPostIncExpr(*this), N)))
 
962
            // Return the expression with the addrec on the outside.
 
963
            return getAddRecExpr(getZeroExtendExpr(Start, Ty),
 
964
                                 getZeroExtendExpr(Step, Ty),
 
965
                                 L);
 
966
        } else if (isKnownNegative(Step)) {
 
967
          const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
 
968
                                      getSignedRange(Step).getSignedMin());
 
969
          if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
 
970
              (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
 
971
               isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
 
972
                                           AR->getPostIncExpr(*this), N)))
 
973
            // Return the expression with the addrec on the outside.
 
974
            return getAddRecExpr(getZeroExtendExpr(Start, Ty),
 
975
                                 getSignExtendExpr(Step, Ty),
 
976
                                 L);
 
977
        }
 
978
      }
 
979
    }
 
980
 
 
981
  // The cast wasn't folded; create an explicit cast node.
 
982
  // Recompute the insert position, as it may have been invalidated.
 
983
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
984
  SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
 
985
  new (S) SCEVZeroExtendExpr(ID, Op, Ty);
 
986
  UniqueSCEVs.InsertNode(S, IP);
 
987
  return S;
 
988
}
 
989
 
 
990
const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
 
991
                                               const Type *Ty) {
 
992
  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
 
993
         "This is not an extending conversion!");
 
994
  assert(isSCEVable(Ty) &&
 
995
         "This is not a conversion to a SCEVable type!");
 
996
  Ty = getEffectiveSCEVType(Ty);
 
997
 
 
998
  // Fold if the operand is constant.
 
999
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
 
1000
    const Type *IntTy = getEffectiveSCEVType(Ty);
 
1001
    Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
 
1002
    if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
 
1003
    return getConstant(cast<ConstantInt>(C));
 
1004
  }
 
1005
 
 
1006
  // sext(sext(x)) --> sext(x)
 
1007
  if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
 
1008
    return getSignExtendExpr(SS->getOperand(), Ty);
 
1009
 
 
1010
  // Before doing any expensive analysis, check to see if we've already
 
1011
  // computed a SCEV for this Op and Ty.
 
1012
  FoldingSetNodeID ID;
 
1013
  ID.AddInteger(scSignExtend);
 
1014
  ID.AddPointer(Op);
 
1015
  ID.AddPointer(Ty);
 
1016
  void *IP = 0;
 
1017
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
1018
 
 
1019
  // If the input value is a chrec scev, and we can prove that the value
 
1020
  // did not overflow the old, smaller, value, we can sign extend all of the
 
1021
  // operands (often constants).  This allows analysis of something like
 
1022
  // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
 
1023
  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
 
1024
    if (AR->isAffine()) {
 
1025
      const SCEV *Start = AR->getStart();
 
1026
      const SCEV *Step = AR->getStepRecurrence(*this);
 
1027
      unsigned BitWidth = getTypeSizeInBits(AR->getType());
 
1028
      const Loop *L = AR->getLoop();
 
1029
 
 
1030
      // If we have special knowledge that this addrec won't overflow,
 
1031
      // we don't need to do any further analysis.
 
1032
      if (AR->hasNoSignedWrap())
 
1033
        return getAddRecExpr(getSignExtendExpr(Start, Ty),
 
1034
                             getSignExtendExpr(Step, Ty),
 
1035
                             L);
 
1036
 
 
1037
      // Check whether the backedge-taken count is SCEVCouldNotCompute.
 
1038
      // Note that this serves two purposes: It filters out loops that are
 
1039
      // simply not analyzable, and it covers the case where this code is
 
1040
      // being called from within backedge-taken count analysis, such that
 
1041
      // attempting to ask for the backedge-taken count would likely result
 
1042
      // in infinite recursion. In the later case, the analysis code will
 
1043
      // cope with a conservative value, and it will take care to purge
 
1044
      // that value once it has finished.
 
1045
      const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
 
1046
      if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
 
1047
        // Manually compute the final value for AR, checking for
 
1048
        // overflow.
 
1049
 
 
1050
        // Check whether the backedge-taken count can be losslessly casted to
 
1051
        // the addrec's type. The count is always unsigned.
 
1052
        const SCEV *CastedMaxBECount =
 
1053
          getTruncateOrZeroExtend(MaxBECount, Start->getType());
 
1054
        const SCEV *RecastedMaxBECount =
 
1055
          getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
 
1056
        if (MaxBECount == RecastedMaxBECount) {
 
1057
          const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
 
1058
          // Check whether Start+Step*MaxBECount has no signed overflow.
 
1059
          const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
 
1060
          const SCEV *Add = getAddExpr(Start, SMul);
 
1061
          const SCEV *OperandExtendedAdd =
 
1062
            getAddExpr(getSignExtendExpr(Start, WideTy),
 
1063
                       getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
 
1064
                                  getSignExtendExpr(Step, WideTy)));
 
1065
          if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
 
1066
            // Return the expression with the addrec on the outside.
 
1067
            return getAddRecExpr(getSignExtendExpr(Start, Ty),
 
1068
                                 getSignExtendExpr(Step, Ty),
 
1069
                                 L);
 
1070
 
 
1071
          // Similar to above, only this time treat the step value as unsigned.
 
1072
          // This covers loops that count up with an unsigned step.
 
1073
          const SCEV *UMul = getMulExpr(CastedMaxBECount, Step);
 
1074
          Add = getAddExpr(Start, UMul);
 
1075
          OperandExtendedAdd =
 
1076
            getAddExpr(getSignExtendExpr(Start, WideTy),
 
1077
                       getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
 
1078
                                  getZeroExtendExpr(Step, WideTy)));
 
1079
          if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
 
1080
            // Return the expression with the addrec on the outside.
 
1081
            return getAddRecExpr(getSignExtendExpr(Start, Ty),
 
1082
                                 getZeroExtendExpr(Step, Ty),
 
1083
                                 L);
 
1084
        }
 
1085
 
 
1086
        // If the backedge is guarded by a comparison with the pre-inc value
 
1087
        // the addrec is safe. Also, if the entry is guarded by a comparison
 
1088
        // with the start value and the backedge is guarded by a comparison
 
1089
        // with the post-inc value, the addrec is safe.
 
1090
        if (isKnownPositive(Step)) {
 
1091
          const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
 
1092
                                      getSignedRange(Step).getSignedMax());
 
1093
          if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
 
1094
              (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
 
1095
               isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
 
1096
                                           AR->getPostIncExpr(*this), N)))
 
1097
            // Return the expression with the addrec on the outside.
 
1098
            return getAddRecExpr(getSignExtendExpr(Start, Ty),
 
1099
                                 getSignExtendExpr(Step, Ty),
 
1100
                                 L);
 
1101
        } else if (isKnownNegative(Step)) {
 
1102
          const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
 
1103
                                      getSignedRange(Step).getSignedMin());
 
1104
          if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
 
1105
              (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
 
1106
               isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
 
1107
                                           AR->getPostIncExpr(*this), N)))
 
1108
            // Return the expression with the addrec on the outside.
 
1109
            return getAddRecExpr(getSignExtendExpr(Start, Ty),
 
1110
                                 getSignExtendExpr(Step, Ty),
 
1111
                                 L);
 
1112
        }
 
1113
      }
 
1114
    }
 
1115
 
 
1116
  // The cast wasn't folded; create an explicit cast node.
 
1117
  // Recompute the insert position, as it may have been invalidated.
 
1118
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
1119
  SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
 
1120
  new (S) SCEVSignExtendExpr(ID, Op, Ty);
 
1121
  UniqueSCEVs.InsertNode(S, IP);
 
1122
  return S;
 
1123
}
 
1124
 
 
1125
/// getAnyExtendExpr - Return a SCEV for the given operand extended with
 
1126
/// unspecified bits out to the given type.
 
1127
///
 
1128
const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
 
1129
                                              const Type *Ty) {
 
1130
  assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
 
1131
         "This is not an extending conversion!");
 
1132
  assert(isSCEVable(Ty) &&
 
1133
         "This is not a conversion to a SCEVable type!");
 
1134
  Ty = getEffectiveSCEVType(Ty);
 
1135
 
 
1136
  // Sign-extend negative constants.
 
1137
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
 
1138
    if (SC->getValue()->getValue().isNegative())
 
1139
      return getSignExtendExpr(Op, Ty);
 
1140
 
 
1141
  // Peel off a truncate cast.
 
1142
  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
 
1143
    const SCEV *NewOp = T->getOperand();
 
1144
    if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
 
1145
      return getAnyExtendExpr(NewOp, Ty);
 
1146
    return getTruncateOrNoop(NewOp, Ty);
 
1147
  }
 
1148
 
 
1149
  // Next try a zext cast. If the cast is folded, use it.
 
1150
  const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
 
1151
  if (!isa<SCEVZeroExtendExpr>(ZExt))
 
1152
    return ZExt;
 
1153
 
 
1154
  // Next try a sext cast. If the cast is folded, use it.
 
1155
  const SCEV *SExt = getSignExtendExpr(Op, Ty);
 
1156
  if (!isa<SCEVSignExtendExpr>(SExt))
 
1157
    return SExt;
 
1158
 
 
1159
  // Force the cast to be folded into the operands of an addrec.
 
1160
  if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
 
1161
    SmallVector<const SCEV *, 4> Ops;
 
1162
    for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
 
1163
         I != E; ++I)
 
1164
      Ops.push_back(getAnyExtendExpr(*I, Ty));
 
1165
    return getAddRecExpr(Ops, AR->getLoop());
 
1166
  }
 
1167
 
 
1168
  // If the expression is obviously signed, use the sext cast value.
 
1169
  if (isa<SCEVSMaxExpr>(Op))
 
1170
    return SExt;
 
1171
 
 
1172
  // Absent any other information, use the zext cast value.
 
1173
  return ZExt;
 
1174
}
 
1175
 
 
1176
/// CollectAddOperandsWithScales - Process the given Ops list, which is
 
1177
/// a list of operands to be added under the given scale, update the given
 
1178
/// map. This is a helper function for getAddRecExpr. As an example of
 
1179
/// what it does, given a sequence of operands that would form an add
 
1180
/// expression like this:
 
1181
///
 
1182
///    m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
 
1183
///
 
1184
/// where A and B are constants, update the map with these values:
 
1185
///
 
1186
///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
 
1187
///
 
1188
/// and add 13 + A*B*29 to AccumulatedConstant.
 
1189
/// This will allow getAddRecExpr to produce this:
 
1190
///
 
1191
///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
 
1192
///
 
1193
/// This form often exposes folding opportunities that are hidden in
 
1194
/// the original operand list.
 
1195
///
 
1196
/// Return true iff it appears that any interesting folding opportunities
 
1197
/// may be exposed. This helps getAddRecExpr short-circuit extra work in
 
1198
/// the common case where no interesting opportunities are present, and
 
1199
/// is also used as a check to avoid infinite recursion.
 
1200
///
 
1201
static bool
 
1202
CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
 
1203
                             SmallVector<const SCEV *, 8> &NewOps,
 
1204
                             APInt &AccumulatedConstant,
 
1205
                             const SmallVectorImpl<const SCEV *> &Ops,
 
1206
                             const APInt &Scale,
 
1207
                             ScalarEvolution &SE) {
 
1208
  bool Interesting = false;
 
1209
 
 
1210
  // Iterate over the add operands.
 
1211
  for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
1212
    const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
 
1213
    if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
 
1214
      APInt NewScale =
 
1215
        Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
 
1216
      if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
 
1217
        // A multiplication of a constant with another add; recurse.
 
1218
        Interesting |=
 
1219
          CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
 
1220
                                       cast<SCEVAddExpr>(Mul->getOperand(1))
 
1221
                                         ->getOperands(),
 
1222
                                       NewScale, SE);
 
1223
      } else {
 
1224
        // A multiplication of a constant with some other value. Update
 
1225
        // the map.
 
1226
        SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
 
1227
        const SCEV *Key = SE.getMulExpr(MulOps);
 
1228
        std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
 
1229
          M.insert(std::make_pair(Key, NewScale));
 
1230
        if (Pair.second) {
 
1231
          NewOps.push_back(Pair.first->first);
 
1232
        } else {
 
1233
          Pair.first->second += NewScale;
 
1234
          // The map already had an entry for this value, which may indicate
 
1235
          // a folding opportunity.
 
1236
          Interesting = true;
 
1237
        }
 
1238
      }
 
1239
    } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
 
1240
      // Pull a buried constant out to the outside.
 
1241
      if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
 
1242
        Interesting = true;
 
1243
      AccumulatedConstant += Scale * C->getValue()->getValue();
 
1244
    } else {
 
1245
      // An ordinary operand. Update the map.
 
1246
      std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
 
1247
        M.insert(std::make_pair(Ops[i], Scale));
 
1248
      if (Pair.second) {
 
1249
        NewOps.push_back(Pair.first->first);
 
1250
      } else {
 
1251
        Pair.first->second += Scale;
 
1252
        // The map already had an entry for this value, which may indicate
 
1253
        // a folding opportunity.
 
1254
        Interesting = true;
 
1255
      }
 
1256
    }
 
1257
  }
 
1258
 
 
1259
  return Interesting;
 
1260
}
 
1261
 
 
1262
namespace {
 
1263
  struct APIntCompare {
 
1264
    bool operator()(const APInt &LHS, const APInt &RHS) const {
 
1265
      return LHS.ult(RHS);
 
1266
    }
 
1267
  };
 
1268
}
 
1269
 
 
1270
/// getAddExpr - Get a canonical add expression, or something simpler if
 
1271
/// possible.
 
1272
const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
 
1273
                                        bool HasNUW, bool HasNSW) {
 
1274
  assert(!Ops.empty() && "Cannot get empty add!");
 
1275
  if (Ops.size() == 1) return Ops[0];
 
1276
#ifndef NDEBUG
 
1277
  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
 
1278
    assert(getEffectiveSCEVType(Ops[i]->getType()) ==
 
1279
           getEffectiveSCEVType(Ops[0]->getType()) &&
 
1280
           "SCEVAddExpr operand types don't match!");
 
1281
#endif
 
1282
 
 
1283
  // If HasNSW is true and all the operands are non-negative, infer HasNUW.
 
1284
  if (!HasNUW && HasNSW) {
 
1285
    bool All = true;
 
1286
    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1287
      if (!isKnownNonNegative(Ops[i])) {
 
1288
        All = false;
 
1289
        break;
 
1290
      }
 
1291
    if (All) HasNUW = true;
 
1292
  }
 
1293
 
 
1294
  // Sort by complexity, this groups all similar expression types together.
 
1295
  GroupByComplexity(Ops, LI);
 
1296
 
 
1297
  // If there are any constants, fold them together.
 
1298
  unsigned Idx = 0;
 
1299
  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
 
1300
    ++Idx;
 
1301
    assert(Idx < Ops.size());
 
1302
    while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
 
1303
      // We found two constants, fold them together!
 
1304
      Ops[0] = getConstant(LHSC->getValue()->getValue() +
 
1305
                           RHSC->getValue()->getValue());
 
1306
      if (Ops.size() == 2) return Ops[0];
 
1307
      Ops.erase(Ops.begin()+1);  // Erase the folded element
 
1308
      LHSC = cast<SCEVConstant>(Ops[0]);
 
1309
    }
 
1310
 
 
1311
    // If we are left with a constant zero being added, strip it off.
 
1312
    if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
 
1313
      Ops.erase(Ops.begin());
 
1314
      --Idx;
 
1315
    }
 
1316
  }
 
1317
 
 
1318
  if (Ops.size() == 1) return Ops[0];
 
1319
 
 
1320
  // Okay, check to see if the same value occurs in the operand list twice.  If
 
1321
  // so, merge them together into an multiply expression.  Since we sorted the
 
1322
  // list, these values are required to be adjacent.
 
1323
  const Type *Ty = Ops[0]->getType();
 
1324
  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
 
1325
    if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
 
1326
      // Found a match, merge the two values into a multiply, and add any
 
1327
      // remaining values to the result.
 
1328
      const SCEV *Two = getIntegerSCEV(2, Ty);
 
1329
      const SCEV *Mul = getMulExpr(Ops[i], Two);
 
1330
      if (Ops.size() == 2)
 
1331
        return Mul;
 
1332
      Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
 
1333
      Ops.push_back(Mul);
 
1334
      return getAddExpr(Ops, HasNUW, HasNSW);
 
1335
    }
 
1336
 
 
1337
  // Check for truncates. If all the operands are truncated from the same
 
1338
  // type, see if factoring out the truncate would permit the result to be
 
1339
  // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
 
1340
  // if the contents of the resulting outer trunc fold to something simple.
 
1341
  for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
 
1342
    const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
 
1343
    const Type *DstType = Trunc->getType();
 
1344
    const Type *SrcType = Trunc->getOperand()->getType();
 
1345
    SmallVector<const SCEV *, 8> LargeOps;
 
1346
    bool Ok = true;
 
1347
    // Check all the operands to see if they can be represented in the
 
1348
    // source type of the truncate.
 
1349
    for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
 
1350
      if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
 
1351
        if (T->getOperand()->getType() != SrcType) {
 
1352
          Ok = false;
 
1353
          break;
 
1354
        }
 
1355
        LargeOps.push_back(T->getOperand());
 
1356
      } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
 
1357
        // This could be either sign or zero extension, but sign extension
 
1358
        // is much more likely to be foldable here.
 
1359
        LargeOps.push_back(getSignExtendExpr(C, SrcType));
 
1360
      } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
 
1361
        SmallVector<const SCEV *, 8> LargeMulOps;
 
1362
        for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
 
1363
          if (const SCEVTruncateExpr *T =
 
1364
                dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
 
1365
            if (T->getOperand()->getType() != SrcType) {
 
1366
              Ok = false;
 
1367
              break;
 
1368
            }
 
1369
            LargeMulOps.push_back(T->getOperand());
 
1370
          } else if (const SCEVConstant *C =
 
1371
                       dyn_cast<SCEVConstant>(M->getOperand(j))) {
 
1372
            // This could be either sign or zero extension, but sign extension
 
1373
            // is much more likely to be foldable here.
 
1374
            LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
 
1375
          } else {
 
1376
            Ok = false;
 
1377
            break;
 
1378
          }
 
1379
        }
 
1380
        if (Ok)
 
1381
          LargeOps.push_back(getMulExpr(LargeMulOps));
 
1382
      } else {
 
1383
        Ok = false;
 
1384
        break;
 
1385
      }
 
1386
    }
 
1387
    if (Ok) {
 
1388
      // Evaluate the expression in the larger type.
 
1389
      const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
 
1390
      // If it folds to something simple, use it. Otherwise, don't.
 
1391
      if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
 
1392
        return getTruncateExpr(Fold, DstType);
 
1393
    }
 
1394
  }
 
1395
 
 
1396
  // Skip past any other cast SCEVs.
 
1397
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
 
1398
    ++Idx;
 
1399
 
 
1400
  // If there are add operands they would be next.
 
1401
  if (Idx < Ops.size()) {
 
1402
    bool DeletedAdd = false;
 
1403
    while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
 
1404
      // If we have an add, expand the add operands onto the end of the operands
 
1405
      // list.
 
1406
      Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
 
1407
      Ops.erase(Ops.begin()+Idx);
 
1408
      DeletedAdd = true;
 
1409
    }
 
1410
 
 
1411
    // If we deleted at least one add, we added operands to the end of the list,
 
1412
    // and they are not necessarily sorted.  Recurse to resort and resimplify
 
1413
    // any operands we just acquired.
 
1414
    if (DeletedAdd)
 
1415
      return getAddExpr(Ops);
 
1416
  }
 
1417
 
 
1418
  // Skip over the add expression until we get to a multiply.
 
1419
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
 
1420
    ++Idx;
 
1421
 
 
1422
  // Check to see if there are any folding opportunities present with
 
1423
  // operands multiplied by constant values.
 
1424
  if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
 
1425
    uint64_t BitWidth = getTypeSizeInBits(Ty);
 
1426
    DenseMap<const SCEV *, APInt> M;
 
1427
    SmallVector<const SCEV *, 8> NewOps;
 
1428
    APInt AccumulatedConstant(BitWidth, 0);
 
1429
    if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
 
1430
                                     Ops, APInt(BitWidth, 1), *this)) {
 
1431
      // Some interesting folding opportunity is present, so its worthwhile to
 
1432
      // re-generate the operands list. Group the operands by constant scale,
 
1433
      // to avoid multiplying by the same constant scale multiple times.
 
1434
      std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
 
1435
      for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
 
1436
           E = NewOps.end(); I != E; ++I)
 
1437
        MulOpLists[M.find(*I)->second].push_back(*I);
 
1438
      // Re-generate the operands list.
 
1439
      Ops.clear();
 
1440
      if (AccumulatedConstant != 0)
 
1441
        Ops.push_back(getConstant(AccumulatedConstant));
 
1442
      for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
 
1443
           I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
 
1444
        if (I->first != 0)
 
1445
          Ops.push_back(getMulExpr(getConstant(I->first),
 
1446
                                   getAddExpr(I->second)));
 
1447
      if (Ops.empty())
 
1448
        return getIntegerSCEV(0, Ty);
 
1449
      if (Ops.size() == 1)
 
1450
        return Ops[0];
 
1451
      return getAddExpr(Ops);
 
1452
    }
 
1453
  }
 
1454
 
 
1455
  // If we are adding something to a multiply expression, make sure the
 
1456
  // something is not already an operand of the multiply.  If so, merge it into
 
1457
  // the multiply.
 
1458
  for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
 
1459
    const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
 
1460
    for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
 
1461
      const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
 
1462
      for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
 
1463
        if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
 
1464
          // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
 
1465
          const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
 
1466
          if (Mul->getNumOperands() != 2) {
 
1467
            // If the multiply has more than two operands, we must get the
 
1468
            // Y*Z term.
 
1469
            SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
 
1470
            MulOps.erase(MulOps.begin()+MulOp);
 
1471
            InnerMul = getMulExpr(MulOps);
 
1472
          }
 
1473
          const SCEV *One = getIntegerSCEV(1, Ty);
 
1474
          const SCEV *AddOne = getAddExpr(InnerMul, One);
 
1475
          const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
 
1476
          if (Ops.size() == 2) return OuterMul;
 
1477
          if (AddOp < Idx) {
 
1478
            Ops.erase(Ops.begin()+AddOp);
 
1479
            Ops.erase(Ops.begin()+Idx-1);
 
1480
          } else {
 
1481
            Ops.erase(Ops.begin()+Idx);
 
1482
            Ops.erase(Ops.begin()+AddOp-1);
 
1483
          }
 
1484
          Ops.push_back(OuterMul);
 
1485
          return getAddExpr(Ops);
 
1486
        }
 
1487
 
 
1488
      // Check this multiply against other multiplies being added together.
 
1489
      for (unsigned OtherMulIdx = Idx+1;
 
1490
           OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
 
1491
           ++OtherMulIdx) {
 
1492
        const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
 
1493
        // If MulOp occurs in OtherMul, we can fold the two multiplies
 
1494
        // together.
 
1495
        for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
 
1496
             OMulOp != e; ++OMulOp)
 
1497
          if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
 
1498
            // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
 
1499
            const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
 
1500
            if (Mul->getNumOperands() != 2) {
 
1501
              SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
 
1502
                                                  Mul->op_end());
 
1503
              MulOps.erase(MulOps.begin()+MulOp);
 
1504
              InnerMul1 = getMulExpr(MulOps);
 
1505
            }
 
1506
            const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
 
1507
            if (OtherMul->getNumOperands() != 2) {
 
1508
              SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
 
1509
                                                  OtherMul->op_end());
 
1510
              MulOps.erase(MulOps.begin()+OMulOp);
 
1511
              InnerMul2 = getMulExpr(MulOps);
 
1512
            }
 
1513
            const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
 
1514
            const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
 
1515
            if (Ops.size() == 2) return OuterMul;
 
1516
            Ops.erase(Ops.begin()+Idx);
 
1517
            Ops.erase(Ops.begin()+OtherMulIdx-1);
 
1518
            Ops.push_back(OuterMul);
 
1519
            return getAddExpr(Ops);
 
1520
          }
 
1521
      }
 
1522
    }
 
1523
  }
 
1524
 
 
1525
  // If there are any add recurrences in the operands list, see if any other
 
1526
  // added values are loop invariant.  If so, we can fold them into the
 
1527
  // recurrence.
 
1528
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
 
1529
    ++Idx;
 
1530
 
 
1531
  // Scan over all recurrences, trying to fold loop invariants into them.
 
1532
  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
 
1533
    // Scan all of the other operands to this add and add them to the vector if
 
1534
    // they are loop invariant w.r.t. the recurrence.
 
1535
    SmallVector<const SCEV *, 8> LIOps;
 
1536
    const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
 
1537
    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1538
      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
 
1539
        LIOps.push_back(Ops[i]);
 
1540
        Ops.erase(Ops.begin()+i);
 
1541
        --i; --e;
 
1542
      }
 
1543
 
 
1544
    // If we found some loop invariants, fold them into the recurrence.
 
1545
    if (!LIOps.empty()) {
 
1546
      //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
 
1547
      LIOps.push_back(AddRec->getStart());
 
1548
 
 
1549
      SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
 
1550
                                             AddRec->op_end());
 
1551
      AddRecOps[0] = getAddExpr(LIOps);
 
1552
 
 
1553
      // It's tempting to propagate NUW/NSW flags here, but nuw/nsw addition
 
1554
      // is not associative so this isn't necessarily safe.
 
1555
      const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
 
1556
 
 
1557
      // If all of the other operands were loop invariant, we are done.
 
1558
      if (Ops.size() == 1) return NewRec;
 
1559
 
 
1560
      // Otherwise, add the folded AddRec by the non-liv parts.
 
1561
      for (unsigned i = 0;; ++i)
 
1562
        if (Ops[i] == AddRec) {
 
1563
          Ops[i] = NewRec;
 
1564
          break;
 
1565
        }
 
1566
      return getAddExpr(Ops);
 
1567
    }
 
1568
 
 
1569
    // Okay, if there weren't any loop invariants to be folded, check to see if
 
1570
    // there are multiple AddRec's with the same loop induction variable being
 
1571
    // added together.  If so, we can fold them.
 
1572
    for (unsigned OtherIdx = Idx+1;
 
1573
         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
 
1574
      if (OtherIdx != Idx) {
 
1575
        const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
 
1576
        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
 
1577
          // Other + {A,+,B} + {C,+,D}  -->  Other + {A+C,+,B+D}
 
1578
          SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
 
1579
                                              AddRec->op_end());
 
1580
          for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
 
1581
            if (i >= NewOps.size()) {
 
1582
              NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
 
1583
                            OtherAddRec->op_end());
 
1584
              break;
 
1585
            }
 
1586
            NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
 
1587
          }
 
1588
          const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
 
1589
 
 
1590
          if (Ops.size() == 2) return NewAddRec;
 
1591
 
 
1592
          Ops.erase(Ops.begin()+Idx);
 
1593
          Ops.erase(Ops.begin()+OtherIdx-1);
 
1594
          Ops.push_back(NewAddRec);
 
1595
          return getAddExpr(Ops);
 
1596
        }
 
1597
      }
 
1598
 
 
1599
    // Otherwise couldn't fold anything into this recurrence.  Move onto the
 
1600
    // next one.
 
1601
  }
 
1602
 
 
1603
  // Okay, it looks like we really DO need an add expr.  Check to see if we
 
1604
  // already have one, otherwise create a new one.
 
1605
  FoldingSetNodeID ID;
 
1606
  ID.AddInteger(scAddExpr);
 
1607
  ID.AddInteger(Ops.size());
 
1608
  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1609
    ID.AddPointer(Ops[i]);
 
1610
  void *IP = 0;
 
1611
  SCEVAddExpr *S =
 
1612
    static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
 
1613
  if (!S) {
 
1614
    S = SCEVAllocator.Allocate<SCEVAddExpr>();
 
1615
    new (S) SCEVAddExpr(ID, Ops);
 
1616
    UniqueSCEVs.InsertNode(S, IP);
 
1617
  }
 
1618
  if (HasNUW) S->setHasNoUnsignedWrap(true);
 
1619
  if (HasNSW) S->setHasNoSignedWrap(true);
 
1620
  return S;
 
1621
}
 
1622
 
 
1623
/// getMulExpr - Get a canonical multiply expression, or something simpler if
 
1624
/// possible.
 
1625
const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
 
1626
                                        bool HasNUW, bool HasNSW) {
 
1627
  assert(!Ops.empty() && "Cannot get empty mul!");
 
1628
  if (Ops.size() == 1) return Ops[0];
 
1629
#ifndef NDEBUG
 
1630
  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
 
1631
    assert(getEffectiveSCEVType(Ops[i]->getType()) ==
 
1632
           getEffectiveSCEVType(Ops[0]->getType()) &&
 
1633
           "SCEVMulExpr operand types don't match!");
 
1634
#endif
 
1635
 
 
1636
  // If HasNSW is true and all the operands are non-negative, infer HasNUW.
 
1637
  if (!HasNUW && HasNSW) {
 
1638
    bool All = true;
 
1639
    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1640
      if (!isKnownNonNegative(Ops[i])) {
 
1641
        All = false;
 
1642
        break;
 
1643
      }
 
1644
    if (All) HasNUW = true;
 
1645
  }
 
1646
 
 
1647
  // Sort by complexity, this groups all similar expression types together.
 
1648
  GroupByComplexity(Ops, LI);
 
1649
 
 
1650
  // If there are any constants, fold them together.
 
1651
  unsigned Idx = 0;
 
1652
  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
 
1653
 
 
1654
    // C1*(C2+V) -> C1*C2 + C1*V
 
1655
    if (Ops.size() == 2)
 
1656
      if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
 
1657
        if (Add->getNumOperands() == 2 &&
 
1658
            isa<SCEVConstant>(Add->getOperand(0)))
 
1659
          return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
 
1660
                            getMulExpr(LHSC, Add->getOperand(1)));
 
1661
 
 
1662
    ++Idx;
 
1663
    while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
 
1664
      // We found two constants, fold them together!
 
1665
      ConstantInt *Fold = ConstantInt::get(getContext(),
 
1666
                                           LHSC->getValue()->getValue() *
 
1667
                                           RHSC->getValue()->getValue());
 
1668
      Ops[0] = getConstant(Fold);
 
1669
      Ops.erase(Ops.begin()+1);  // Erase the folded element
 
1670
      if (Ops.size() == 1) return Ops[0];
 
1671
      LHSC = cast<SCEVConstant>(Ops[0]);
 
1672
    }
 
1673
 
 
1674
    // If we are left with a constant one being multiplied, strip it off.
 
1675
    if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
 
1676
      Ops.erase(Ops.begin());
 
1677
      --Idx;
 
1678
    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
 
1679
      // If we have a multiply of zero, it will always be zero.
 
1680
      return Ops[0];
 
1681
    } else if (Ops[0]->isAllOnesValue()) {
 
1682
      // If we have a mul by -1 of an add, try distributing the -1 among the
 
1683
      // add operands.
 
1684
      if (Ops.size() == 2)
 
1685
        if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
 
1686
          SmallVector<const SCEV *, 4> NewOps;
 
1687
          bool AnyFolded = false;
 
1688
          for (SCEVAddRecExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
 
1689
               I != E; ++I) {
 
1690
            const SCEV *Mul = getMulExpr(Ops[0], *I);
 
1691
            if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
 
1692
            NewOps.push_back(Mul);
 
1693
          }
 
1694
          if (AnyFolded)
 
1695
            return getAddExpr(NewOps);
 
1696
        }
 
1697
    }
 
1698
  }
 
1699
 
 
1700
  // Skip over the add expression until we get to a multiply.
 
1701
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
 
1702
    ++Idx;
 
1703
 
 
1704
  if (Ops.size() == 1)
 
1705
    return Ops[0];
 
1706
 
 
1707
  // If there are mul operands inline them all into this expression.
 
1708
  if (Idx < Ops.size()) {
 
1709
    bool DeletedMul = false;
 
1710
    while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
 
1711
      // If we have an mul, expand the mul operands onto the end of the operands
 
1712
      // list.
 
1713
      Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
 
1714
      Ops.erase(Ops.begin()+Idx);
 
1715
      DeletedMul = true;
 
1716
    }
 
1717
 
 
1718
    // If we deleted at least one mul, we added operands to the end of the list,
 
1719
    // and they are not necessarily sorted.  Recurse to resort and resimplify
 
1720
    // any operands we just acquired.
 
1721
    if (DeletedMul)
 
1722
      return getMulExpr(Ops);
 
1723
  }
 
1724
 
 
1725
  // If there are any add recurrences in the operands list, see if any other
 
1726
  // added values are loop invariant.  If so, we can fold them into the
 
1727
  // recurrence.
 
1728
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
 
1729
    ++Idx;
 
1730
 
 
1731
  // Scan over all recurrences, trying to fold loop invariants into them.
 
1732
  for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
 
1733
    // Scan all of the other operands to this mul and add them to the vector if
 
1734
    // they are loop invariant w.r.t. the recurrence.
 
1735
    SmallVector<const SCEV *, 8> LIOps;
 
1736
    const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
 
1737
    for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1738
      if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
 
1739
        LIOps.push_back(Ops[i]);
 
1740
        Ops.erase(Ops.begin()+i);
 
1741
        --i; --e;
 
1742
      }
 
1743
 
 
1744
    // If we found some loop invariants, fold them into the recurrence.
 
1745
    if (!LIOps.empty()) {
 
1746
      //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
 
1747
      SmallVector<const SCEV *, 4> NewOps;
 
1748
      NewOps.reserve(AddRec->getNumOperands());
 
1749
      if (LIOps.size() == 1) {
 
1750
        const SCEV *Scale = LIOps[0];
 
1751
        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
 
1752
          NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
 
1753
      } else {
 
1754
        for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
 
1755
          SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
 
1756
          MulOps.push_back(AddRec->getOperand(i));
 
1757
          NewOps.push_back(getMulExpr(MulOps));
 
1758
        }
 
1759
      }
 
1760
 
 
1761
      // It's tempting to propagate the NSW flag here, but nsw multiplication
 
1762
      // is not associative so this isn't necessarily safe.
 
1763
      const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
 
1764
                                         HasNUW && AddRec->hasNoUnsignedWrap(),
 
1765
                                         /*HasNSW=*/false);
 
1766
 
 
1767
      // If all of the other operands were loop invariant, we are done.
 
1768
      if (Ops.size() == 1) return NewRec;
 
1769
 
 
1770
      // Otherwise, multiply the folded AddRec by the non-liv parts.
 
1771
      for (unsigned i = 0;; ++i)
 
1772
        if (Ops[i] == AddRec) {
 
1773
          Ops[i] = NewRec;
 
1774
          break;
 
1775
        }
 
1776
      return getMulExpr(Ops);
 
1777
    }
 
1778
 
 
1779
    // Okay, if there weren't any loop invariants to be folded, check to see if
 
1780
    // there are multiple AddRec's with the same loop induction variable being
 
1781
    // multiplied together.  If so, we can fold them.
 
1782
    for (unsigned OtherIdx = Idx+1;
 
1783
         OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
 
1784
      if (OtherIdx != Idx) {
 
1785
        const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
 
1786
        if (AddRec->getLoop() == OtherAddRec->getLoop()) {
 
1787
          // F * G  -->  {A,+,B} * {C,+,D}  -->  {A*C,+,F*D + G*B + B*D}
 
1788
          const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
 
1789
          const SCEV *NewStart = getMulExpr(F->getStart(),
 
1790
                                                 G->getStart());
 
1791
          const SCEV *B = F->getStepRecurrence(*this);
 
1792
          const SCEV *D = G->getStepRecurrence(*this);
 
1793
          const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
 
1794
                                          getMulExpr(G, B),
 
1795
                                          getMulExpr(B, D));
 
1796
          const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
 
1797
                                               F->getLoop());
 
1798
          if (Ops.size() == 2) return NewAddRec;
 
1799
 
 
1800
          Ops.erase(Ops.begin()+Idx);
 
1801
          Ops.erase(Ops.begin()+OtherIdx-1);
 
1802
          Ops.push_back(NewAddRec);
 
1803
          return getMulExpr(Ops);
 
1804
        }
 
1805
      }
 
1806
 
 
1807
    // Otherwise couldn't fold anything into this recurrence.  Move onto the
 
1808
    // next one.
 
1809
  }
 
1810
 
 
1811
  // Okay, it looks like we really DO need an mul expr.  Check to see if we
 
1812
  // already have one, otherwise create a new one.
 
1813
  FoldingSetNodeID ID;
 
1814
  ID.AddInteger(scMulExpr);
 
1815
  ID.AddInteger(Ops.size());
 
1816
  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
1817
    ID.AddPointer(Ops[i]);
 
1818
  void *IP = 0;
 
1819
  SCEVMulExpr *S =
 
1820
    static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
 
1821
  if (!S) {
 
1822
    S = SCEVAllocator.Allocate<SCEVMulExpr>();
 
1823
    new (S) SCEVMulExpr(ID, Ops);
 
1824
    UniqueSCEVs.InsertNode(S, IP);
 
1825
  }
 
1826
  if (HasNUW) S->setHasNoUnsignedWrap(true);
 
1827
  if (HasNSW) S->setHasNoSignedWrap(true);
 
1828
  return S;
 
1829
}
 
1830
 
 
1831
/// getUDivExpr - Get a canonical unsigned division expression, or something
 
1832
/// simpler if possible.
 
1833
const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
 
1834
                                         const SCEV *RHS) {
 
1835
  assert(getEffectiveSCEVType(LHS->getType()) ==
 
1836
         getEffectiveSCEVType(RHS->getType()) &&
 
1837
         "SCEVUDivExpr operand types don't match!");
 
1838
 
 
1839
  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
 
1840
    if (RHSC->getValue()->equalsInt(1))
 
1841
      return LHS;                               // X udiv 1 --> x
 
1842
    if (RHSC->isZero())
 
1843
      return getIntegerSCEV(0, LHS->getType()); // value is undefined
 
1844
 
 
1845
    // Determine if the division can be folded into the operands of
 
1846
    // its operands.
 
1847
    // TODO: Generalize this to non-constants by using known-bits information.
 
1848
    const Type *Ty = LHS->getType();
 
1849
    unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
 
1850
    unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
 
1851
    // For non-power-of-two values, effectively round the value up to the
 
1852
    // nearest power of two.
 
1853
    if (!RHSC->getValue()->getValue().isPowerOf2())
 
1854
      ++MaxShiftAmt;
 
1855
    const IntegerType *ExtTy =
 
1856
      IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
 
1857
    // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
 
1858
    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
 
1859
      if (const SCEVConstant *Step =
 
1860
            dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
 
1861
        if (!Step->getValue()->getValue()
 
1862
              .urem(RHSC->getValue()->getValue()) &&
 
1863
            getZeroExtendExpr(AR, ExtTy) ==
 
1864
            getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
 
1865
                          getZeroExtendExpr(Step, ExtTy),
 
1866
                          AR->getLoop())) {
 
1867
          SmallVector<const SCEV *, 4> Operands;
 
1868
          for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
 
1869
            Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
 
1870
          return getAddRecExpr(Operands, AR->getLoop());
 
1871
        }
 
1872
    // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
 
1873
    if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
 
1874
      SmallVector<const SCEV *, 4> Operands;
 
1875
      for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
 
1876
        Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
 
1877
      if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
 
1878
        // Find an operand that's safely divisible.
 
1879
        for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
 
1880
          const SCEV *Op = M->getOperand(i);
 
1881
          const SCEV *Div = getUDivExpr(Op, RHSC);
 
1882
          if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
 
1883
            const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
 
1884
            Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
 
1885
                                                  MOperands.end());
 
1886
            Operands[i] = Div;
 
1887
            return getMulExpr(Operands);
 
1888
          }
 
1889
        }
 
1890
    }
 
1891
    // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
 
1892
    if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
 
1893
      SmallVector<const SCEV *, 4> Operands;
 
1894
      for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
 
1895
        Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
 
1896
      if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
 
1897
        Operands.clear();
 
1898
        for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
 
1899
          const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
 
1900
          if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
 
1901
            break;
 
1902
          Operands.push_back(Op);
 
1903
        }
 
1904
        if (Operands.size() == A->getNumOperands())
 
1905
          return getAddExpr(Operands);
 
1906
      }
 
1907
    }
 
1908
 
 
1909
    // Fold if both operands are constant.
 
1910
    if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
 
1911
      Constant *LHSCV = LHSC->getValue();
 
1912
      Constant *RHSCV = RHSC->getValue();
 
1913
      return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
 
1914
                                                                 RHSCV)));
 
1915
    }
 
1916
  }
 
1917
 
 
1918
  FoldingSetNodeID ID;
 
1919
  ID.AddInteger(scUDivExpr);
 
1920
  ID.AddPointer(LHS);
 
1921
  ID.AddPointer(RHS);
 
1922
  void *IP = 0;
 
1923
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
1924
  SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
 
1925
  new (S) SCEVUDivExpr(ID, LHS, RHS);
 
1926
  UniqueSCEVs.InsertNode(S, IP);
 
1927
  return S;
 
1928
}
 
1929
 
 
1930
 
 
1931
/// getAddRecExpr - Get an add recurrence expression for the specified loop.
 
1932
/// Simplify the expression as much as possible.
 
1933
const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
 
1934
                                           const SCEV *Step, const Loop *L,
 
1935
                                           bool HasNUW, bool HasNSW) {
 
1936
  SmallVector<const SCEV *, 4> Operands;
 
1937
  Operands.push_back(Start);
 
1938
  if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
 
1939
    if (StepChrec->getLoop() == L) {
 
1940
      Operands.insert(Operands.end(), StepChrec->op_begin(),
 
1941
                      StepChrec->op_end());
 
1942
      return getAddRecExpr(Operands, L);
 
1943
    }
 
1944
 
 
1945
  Operands.push_back(Step);
 
1946
  return getAddRecExpr(Operands, L, HasNUW, HasNSW);
 
1947
}
 
1948
 
 
1949
/// getAddRecExpr - Get an add recurrence expression for the specified loop.
 
1950
/// Simplify the expression as much as possible.
 
1951
const SCEV *
 
1952
ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
 
1953
                               const Loop *L,
 
1954
                               bool HasNUW, bool HasNSW) {
 
1955
  if (Operands.size() == 1) return Operands[0];
 
1956
#ifndef NDEBUG
 
1957
  for (unsigned i = 1, e = Operands.size(); i != e; ++i)
 
1958
    assert(getEffectiveSCEVType(Operands[i]->getType()) ==
 
1959
           getEffectiveSCEVType(Operands[0]->getType()) &&
 
1960
           "SCEVAddRecExpr operand types don't match!");
 
1961
#endif
 
1962
 
 
1963
  if (Operands.back()->isZero()) {
 
1964
    Operands.pop_back();
 
1965
    return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0}  -->  X
 
1966
  }
 
1967
 
 
1968
  // It's tempting to want to call getMaxBackedgeTakenCount count here and
 
1969
  // use that information to infer NUW and NSW flags. However, computing a
 
1970
  // BE count requires calling getAddRecExpr, so we may not yet have a
 
1971
  // meaningful BE count at this point (and if we don't, we'd be stuck
 
1972
  // with a SCEVCouldNotCompute as the cached BE count).
 
1973
 
 
1974
  // If HasNSW is true and all the operands are non-negative, infer HasNUW.
 
1975
  if (!HasNUW && HasNSW) {
 
1976
    bool All = true;
 
1977
    for (unsigned i = 0, e = Operands.size(); i != e; ++i)
 
1978
      if (!isKnownNonNegative(Operands[i])) {
 
1979
        All = false;
 
1980
        break;
 
1981
      }
 
1982
    if (All) HasNUW = true;
 
1983
  }
 
1984
 
 
1985
  // Canonicalize nested AddRecs in by nesting them in order of loop depth.
 
1986
  if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
 
1987
    const Loop *NestedLoop = NestedAR->getLoop();
 
1988
    if (L->contains(NestedLoop->getHeader()) ?
 
1989
        (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
 
1990
        (!NestedLoop->contains(L->getHeader()) &&
 
1991
         DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
 
1992
      SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
 
1993
                                                  NestedAR->op_end());
 
1994
      Operands[0] = NestedAR->getStart();
 
1995
      // AddRecs require their operands be loop-invariant with respect to their
 
1996
      // loops. Don't perform this transformation if it would break this
 
1997
      // requirement.
 
1998
      bool AllInvariant = true;
 
1999
      for (unsigned i = 0, e = Operands.size(); i != e; ++i)
 
2000
        if (!Operands[i]->isLoopInvariant(L)) {
 
2001
          AllInvariant = false;
 
2002
          break;
 
2003
        }
 
2004
      if (AllInvariant) {
 
2005
        NestedOperands[0] = getAddRecExpr(Operands, L);
 
2006
        AllInvariant = true;
 
2007
        for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
 
2008
          if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
 
2009
            AllInvariant = false;
 
2010
            break;
 
2011
          }
 
2012
        if (AllInvariant)
 
2013
          // Ok, both add recurrences are valid after the transformation.
 
2014
          return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
 
2015
      }
 
2016
      // Reset Operands to its original state.
 
2017
      Operands[0] = NestedAR;
 
2018
    }
 
2019
  }
 
2020
 
 
2021
  // Okay, it looks like we really DO need an addrec expr.  Check to see if we
 
2022
  // already have one, otherwise create a new one.
 
2023
  FoldingSetNodeID ID;
 
2024
  ID.AddInteger(scAddRecExpr);
 
2025
  ID.AddInteger(Operands.size());
 
2026
  for (unsigned i = 0, e = Operands.size(); i != e; ++i)
 
2027
    ID.AddPointer(Operands[i]);
 
2028
  ID.AddPointer(L);
 
2029
  void *IP = 0;
 
2030
  SCEVAddRecExpr *S =
 
2031
    static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
 
2032
  if (!S) {
 
2033
    S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
 
2034
    new (S) SCEVAddRecExpr(ID, Operands, L);
 
2035
    UniqueSCEVs.InsertNode(S, IP);
 
2036
  }
 
2037
  if (HasNUW) S->setHasNoUnsignedWrap(true);
 
2038
  if (HasNSW) S->setHasNoSignedWrap(true);
 
2039
  return S;
 
2040
}
 
2041
 
 
2042
const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
 
2043
                                         const SCEV *RHS) {
 
2044
  SmallVector<const SCEV *, 2> Ops;
 
2045
  Ops.push_back(LHS);
 
2046
  Ops.push_back(RHS);
 
2047
  return getSMaxExpr(Ops);
 
2048
}
 
2049
 
 
2050
const SCEV *
 
2051
ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
 
2052
  assert(!Ops.empty() && "Cannot get empty smax!");
 
2053
  if (Ops.size() == 1) return Ops[0];
 
2054
#ifndef NDEBUG
 
2055
  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
 
2056
    assert(getEffectiveSCEVType(Ops[i]->getType()) ==
 
2057
           getEffectiveSCEVType(Ops[0]->getType()) &&
 
2058
           "SCEVSMaxExpr operand types don't match!");
 
2059
#endif
 
2060
 
 
2061
  // Sort by complexity, this groups all similar expression types together.
 
2062
  GroupByComplexity(Ops, LI);
 
2063
 
 
2064
  // If there are any constants, fold them together.
 
2065
  unsigned Idx = 0;
 
2066
  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
 
2067
    ++Idx;
 
2068
    assert(Idx < Ops.size());
 
2069
    while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
 
2070
      // We found two constants, fold them together!
 
2071
      ConstantInt *Fold = ConstantInt::get(getContext(),
 
2072
                              APIntOps::smax(LHSC->getValue()->getValue(),
 
2073
                                             RHSC->getValue()->getValue()));
 
2074
      Ops[0] = getConstant(Fold);
 
2075
      Ops.erase(Ops.begin()+1);  // Erase the folded element
 
2076
      if (Ops.size() == 1) return Ops[0];
 
2077
      LHSC = cast<SCEVConstant>(Ops[0]);
 
2078
    }
 
2079
 
 
2080
    // If we are left with a constant minimum-int, strip it off.
 
2081
    if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
 
2082
      Ops.erase(Ops.begin());
 
2083
      --Idx;
 
2084
    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
 
2085
      // If we have an smax with a constant maximum-int, it will always be
 
2086
      // maximum-int.
 
2087
      return Ops[0];
 
2088
    }
 
2089
  }
 
2090
 
 
2091
  if (Ops.size() == 1) return Ops[0];
 
2092
 
 
2093
  // Find the first SMax
 
2094
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
 
2095
    ++Idx;
 
2096
 
 
2097
  // Check to see if one of the operands is an SMax. If so, expand its operands
 
2098
  // onto our operand list, and recurse to simplify.
 
2099
  if (Idx < Ops.size()) {
 
2100
    bool DeletedSMax = false;
 
2101
    while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
 
2102
      Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
 
2103
      Ops.erase(Ops.begin()+Idx);
 
2104
      DeletedSMax = true;
 
2105
    }
 
2106
 
 
2107
    if (DeletedSMax)
 
2108
      return getSMaxExpr(Ops);
 
2109
  }
 
2110
 
 
2111
  // Okay, check to see if the same value occurs in the operand list twice.  If
 
2112
  // so, delete one.  Since we sorted the list, these values are required to
 
2113
  // be adjacent.
 
2114
  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
 
2115
    if (Ops[i] == Ops[i+1]) {      //  X smax Y smax Y  -->  X smax Y
 
2116
      Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
 
2117
      --i; --e;
 
2118
    }
 
2119
 
 
2120
  if (Ops.size() == 1) return Ops[0];
 
2121
 
 
2122
  assert(!Ops.empty() && "Reduced smax down to nothing!");
 
2123
 
 
2124
  // Okay, it looks like we really DO need an smax expr.  Check to see if we
 
2125
  // already have one, otherwise create a new one.
 
2126
  FoldingSetNodeID ID;
 
2127
  ID.AddInteger(scSMaxExpr);
 
2128
  ID.AddInteger(Ops.size());
 
2129
  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
2130
    ID.AddPointer(Ops[i]);
 
2131
  void *IP = 0;
 
2132
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
2133
  SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
 
2134
  new (S) SCEVSMaxExpr(ID, Ops);
 
2135
  UniqueSCEVs.InsertNode(S, IP);
 
2136
  return S;
 
2137
}
 
2138
 
 
2139
const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
 
2140
                                         const SCEV *RHS) {
 
2141
  SmallVector<const SCEV *, 2> Ops;
 
2142
  Ops.push_back(LHS);
 
2143
  Ops.push_back(RHS);
 
2144
  return getUMaxExpr(Ops);
 
2145
}
 
2146
 
 
2147
const SCEV *
 
2148
ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
 
2149
  assert(!Ops.empty() && "Cannot get empty umax!");
 
2150
  if (Ops.size() == 1) return Ops[0];
 
2151
#ifndef NDEBUG
 
2152
  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
 
2153
    assert(getEffectiveSCEVType(Ops[i]->getType()) ==
 
2154
           getEffectiveSCEVType(Ops[0]->getType()) &&
 
2155
           "SCEVUMaxExpr operand types don't match!");
 
2156
#endif
 
2157
 
 
2158
  // Sort by complexity, this groups all similar expression types together.
 
2159
  GroupByComplexity(Ops, LI);
 
2160
 
 
2161
  // If there are any constants, fold them together.
 
2162
  unsigned Idx = 0;
 
2163
  if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
 
2164
    ++Idx;
 
2165
    assert(Idx < Ops.size());
 
2166
    while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
 
2167
      // We found two constants, fold them together!
 
2168
      ConstantInt *Fold = ConstantInt::get(getContext(),
 
2169
                              APIntOps::umax(LHSC->getValue()->getValue(),
 
2170
                                             RHSC->getValue()->getValue()));
 
2171
      Ops[0] = getConstant(Fold);
 
2172
      Ops.erase(Ops.begin()+1);  // Erase the folded element
 
2173
      if (Ops.size() == 1) return Ops[0];
 
2174
      LHSC = cast<SCEVConstant>(Ops[0]);
 
2175
    }
 
2176
 
 
2177
    // If we are left with a constant minimum-int, strip it off.
 
2178
    if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
 
2179
      Ops.erase(Ops.begin());
 
2180
      --Idx;
 
2181
    } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
 
2182
      // If we have an umax with a constant maximum-int, it will always be
 
2183
      // maximum-int.
 
2184
      return Ops[0];
 
2185
    }
 
2186
  }
 
2187
 
 
2188
  if (Ops.size() == 1) return Ops[0];
 
2189
 
 
2190
  // Find the first UMax
 
2191
  while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
 
2192
    ++Idx;
 
2193
 
 
2194
  // Check to see if one of the operands is a UMax. If so, expand its operands
 
2195
  // onto our operand list, and recurse to simplify.
 
2196
  if (Idx < Ops.size()) {
 
2197
    bool DeletedUMax = false;
 
2198
    while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
 
2199
      Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
 
2200
      Ops.erase(Ops.begin()+Idx);
 
2201
      DeletedUMax = true;
 
2202
    }
 
2203
 
 
2204
    if (DeletedUMax)
 
2205
      return getUMaxExpr(Ops);
 
2206
  }
 
2207
 
 
2208
  // Okay, check to see if the same value occurs in the operand list twice.  If
 
2209
  // so, delete one.  Since we sorted the list, these values are required to
 
2210
  // be adjacent.
 
2211
  for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
 
2212
    if (Ops[i] == Ops[i+1]) {      //  X umax Y umax Y  -->  X umax Y
 
2213
      Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
 
2214
      --i; --e;
 
2215
    }
 
2216
 
 
2217
  if (Ops.size() == 1) return Ops[0];
 
2218
 
 
2219
  assert(!Ops.empty() && "Reduced umax down to nothing!");
 
2220
 
 
2221
  // Okay, it looks like we really DO need a umax expr.  Check to see if we
 
2222
  // already have one, otherwise create a new one.
 
2223
  FoldingSetNodeID ID;
 
2224
  ID.AddInteger(scUMaxExpr);
 
2225
  ID.AddInteger(Ops.size());
 
2226
  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
 
2227
    ID.AddPointer(Ops[i]);
 
2228
  void *IP = 0;
 
2229
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
2230
  SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
 
2231
  new (S) SCEVUMaxExpr(ID, Ops);
 
2232
  UniqueSCEVs.InsertNode(S, IP);
 
2233
  return S;
 
2234
}
 
2235
 
 
2236
const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
 
2237
                                         const SCEV *RHS) {
 
2238
  // ~smax(~x, ~y) == smin(x, y).
 
2239
  return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
 
2240
}
 
2241
 
 
2242
const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
 
2243
                                         const SCEV *RHS) {
 
2244
  // ~umax(~x, ~y) == umin(x, y)
 
2245
  return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
 
2246
}
 
2247
 
 
2248
const SCEV *ScalarEvolution::getSizeOfExpr(const Type *AllocTy) {
 
2249
  Constant *C = ConstantExpr::getSizeOf(AllocTy);
 
2250
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
 
2251
    C = ConstantFoldConstantExpression(CE, TD);
 
2252
  const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
 
2253
  return getTruncateOrZeroExtend(getSCEV(C), Ty);
 
2254
}
 
2255
 
 
2256
const SCEV *ScalarEvolution::getAlignOfExpr(const Type *AllocTy) {
 
2257
  Constant *C = ConstantExpr::getAlignOf(AllocTy);
 
2258
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
 
2259
    C = ConstantFoldConstantExpression(CE, TD);
 
2260
  const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
 
2261
  return getTruncateOrZeroExtend(getSCEV(C), Ty);
 
2262
}
 
2263
 
 
2264
const SCEV *ScalarEvolution::getOffsetOfExpr(const StructType *STy,
 
2265
                                             unsigned FieldNo) {
 
2266
  Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
 
2267
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
 
2268
    C = ConstantFoldConstantExpression(CE, TD);
 
2269
  const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
 
2270
  return getTruncateOrZeroExtend(getSCEV(C), Ty);
 
2271
}
 
2272
 
 
2273
const SCEV *ScalarEvolution::getOffsetOfExpr(const Type *CTy,
 
2274
                                             Constant *FieldNo) {
 
2275
  Constant *C = ConstantExpr::getOffsetOf(CTy, FieldNo);
 
2276
  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
 
2277
    C = ConstantFoldConstantExpression(CE, TD);
 
2278
  const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(CTy));
 
2279
  return getTruncateOrZeroExtend(getSCEV(C), Ty);
 
2280
}
 
2281
 
 
2282
const SCEV *ScalarEvolution::getUnknown(Value *V) {
 
2283
  // Don't attempt to do anything other than create a SCEVUnknown object
 
2284
  // here.  createSCEV only calls getUnknown after checking for all other
 
2285
  // interesting possibilities, and any other code that calls getUnknown
 
2286
  // is doing so in order to hide a value from SCEV canonicalization.
 
2287
 
 
2288
  FoldingSetNodeID ID;
 
2289
  ID.AddInteger(scUnknown);
 
2290
  ID.AddPointer(V);
 
2291
  void *IP = 0;
 
2292
  if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
 
2293
  SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
 
2294
  new (S) SCEVUnknown(ID, V);
 
2295
  UniqueSCEVs.InsertNode(S, IP);
 
2296
  return S;
 
2297
}
 
2298
 
 
2299
//===----------------------------------------------------------------------===//
 
2300
//            Basic SCEV Analysis and PHI Idiom Recognition Code
 
2301
//
 
2302
 
 
2303
/// isSCEVable - Test if values of the given type are analyzable within
 
2304
/// the SCEV framework. This primarily includes integer types, and it
 
2305
/// can optionally include pointer types if the ScalarEvolution class
 
2306
/// has access to target-specific information.
 
2307
bool ScalarEvolution::isSCEVable(const Type *Ty) const {
 
2308
  // Integers and pointers are always SCEVable.
 
2309
  return Ty->isIntegerTy() || Ty->isPointerTy();
 
2310
}
 
2311
 
 
2312
/// getTypeSizeInBits - Return the size in bits of the specified type,
 
2313
/// for which isSCEVable must return true.
 
2314
uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
 
2315
  assert(isSCEVable(Ty) && "Type is not SCEVable!");
 
2316
 
 
2317
  // If we have a TargetData, use it!
 
2318
  if (TD)
 
2319
    return TD->getTypeSizeInBits(Ty);
 
2320
 
 
2321
  // Integer types have fixed sizes.
 
2322
  if (Ty->isIntegerTy())
 
2323
    return Ty->getPrimitiveSizeInBits();
 
2324
 
 
2325
  // The only other support type is pointer. Without TargetData, conservatively
 
2326
  // assume pointers are 64-bit.
 
2327
  assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
 
2328
  return 64;
 
2329
}
 
2330
 
 
2331
/// getEffectiveSCEVType - Return a type with the same bitwidth as
 
2332
/// the given type and which represents how SCEV will treat the given
 
2333
/// type, for which isSCEVable must return true. For pointer types,
 
2334
/// this is the pointer-sized integer type.
 
2335
const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
 
2336
  assert(isSCEVable(Ty) && "Type is not SCEVable!");
 
2337
 
 
2338
  if (Ty->isIntegerTy())
 
2339
    return Ty;
 
2340
 
 
2341
  // The only other support type is pointer.
 
2342
  assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
 
2343
  if (TD) return TD->getIntPtrType(getContext());
 
2344
 
 
2345
  // Without TargetData, conservatively assume pointers are 64-bit.
 
2346
  return Type::getInt64Ty(getContext());
 
2347
}
 
2348
 
 
2349
const SCEV *ScalarEvolution::getCouldNotCompute() {
 
2350
  return &CouldNotCompute;
 
2351
}
 
2352
 
 
2353
/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
 
2354
/// expression and create a new one.
 
2355
const SCEV *ScalarEvolution::getSCEV(Value *V) {
 
2356
  assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
 
2357
 
 
2358
  std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
 
2359
  if (I != Scalars.end()) return I->second;
 
2360
  const SCEV *S = createSCEV(V);
 
2361
  Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
 
2362
  return S;
 
2363
}
 
2364
 
 
2365
/// getIntegerSCEV - Given a SCEVable type, create a constant for the
 
2366
/// specified signed integer value and return a SCEV for the constant.
 
2367
const SCEV *ScalarEvolution::getIntegerSCEV(int64_t Val, const Type *Ty) {
 
2368
  const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
 
2369
  return getConstant(ConstantInt::get(ITy, Val));
 
2370
}
 
2371
 
 
2372
/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
 
2373
///
 
2374
const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
 
2375
  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
 
2376
    return getConstant(
 
2377
               cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
 
2378
 
 
2379
  const Type *Ty = V->getType();
 
2380
  Ty = getEffectiveSCEVType(Ty);
 
2381
  return getMulExpr(V,
 
2382
                  getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
 
2383
}
 
2384
 
 
2385
/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
 
2386
const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
 
2387
  if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
 
2388
    return getConstant(
 
2389
                cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
 
2390
 
 
2391
  const Type *Ty = V->getType();
 
2392
  Ty = getEffectiveSCEVType(Ty);
 
2393
  const SCEV *AllOnes =
 
2394
                   getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
 
2395
  return getMinusSCEV(AllOnes, V);
 
2396
}
 
2397
 
 
2398
/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
 
2399
///
 
2400
const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
 
2401
                                          const SCEV *RHS) {
 
2402
  // X - Y --> X + -Y
 
2403
  return getAddExpr(LHS, getNegativeSCEV(RHS));
 
2404
}
 
2405
 
 
2406
/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
 
2407
/// input value to the specified type.  If the type must be extended, it is zero
 
2408
/// extended.
 
2409
const SCEV *
 
2410
ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
 
2411
                                         const Type *Ty) {
 
2412
  const Type *SrcTy = V->getType();
 
2413
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2414
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2415
         "Cannot truncate or zero extend with non-integer arguments!");
 
2416
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2417
    return V;  // No conversion
 
2418
  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
 
2419
    return getTruncateExpr(V, Ty);
 
2420
  return getZeroExtendExpr(V, Ty);
 
2421
}
 
2422
 
 
2423
/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
 
2424
/// input value to the specified type.  If the type must be extended, it is sign
 
2425
/// extended.
 
2426
const SCEV *
 
2427
ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
 
2428
                                         const Type *Ty) {
 
2429
  const Type *SrcTy = V->getType();
 
2430
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2431
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2432
         "Cannot truncate or zero extend with non-integer arguments!");
 
2433
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2434
    return V;  // No conversion
 
2435
  if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
 
2436
    return getTruncateExpr(V, Ty);
 
2437
  return getSignExtendExpr(V, Ty);
 
2438
}
 
2439
 
 
2440
/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
 
2441
/// input value to the specified type.  If the type must be extended, it is zero
 
2442
/// extended.  The conversion must not be narrowing.
 
2443
const SCEV *
 
2444
ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
 
2445
  const Type *SrcTy = V->getType();
 
2446
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2447
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2448
         "Cannot noop or zero extend with non-integer arguments!");
 
2449
  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
 
2450
         "getNoopOrZeroExtend cannot truncate!");
 
2451
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2452
    return V;  // No conversion
 
2453
  return getZeroExtendExpr(V, Ty);
 
2454
}
 
2455
 
 
2456
/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
 
2457
/// input value to the specified type.  If the type must be extended, it is sign
 
2458
/// extended.  The conversion must not be narrowing.
 
2459
const SCEV *
 
2460
ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
 
2461
  const Type *SrcTy = V->getType();
 
2462
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2463
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2464
         "Cannot noop or sign extend with non-integer arguments!");
 
2465
  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
 
2466
         "getNoopOrSignExtend cannot truncate!");
 
2467
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2468
    return V;  // No conversion
 
2469
  return getSignExtendExpr(V, Ty);
 
2470
}
 
2471
 
 
2472
/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
 
2473
/// the input value to the specified type. If the type must be extended,
 
2474
/// it is extended with unspecified bits. The conversion must not be
 
2475
/// narrowing.
 
2476
const SCEV *
 
2477
ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
 
2478
  const Type *SrcTy = V->getType();
 
2479
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2480
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2481
         "Cannot noop or any extend with non-integer arguments!");
 
2482
  assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
 
2483
         "getNoopOrAnyExtend cannot truncate!");
 
2484
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2485
    return V;  // No conversion
 
2486
  return getAnyExtendExpr(V, Ty);
 
2487
}
 
2488
 
 
2489
/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
 
2490
/// input value to the specified type.  The conversion must not be widening.
 
2491
const SCEV *
 
2492
ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
 
2493
  const Type *SrcTy = V->getType();
 
2494
  assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
 
2495
         (Ty->isIntegerTy() || Ty->isPointerTy()) &&
 
2496
         "Cannot truncate or noop with non-integer arguments!");
 
2497
  assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
 
2498
         "getTruncateOrNoop cannot extend!");
 
2499
  if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
 
2500
    return V;  // No conversion
 
2501
  return getTruncateExpr(V, Ty);
 
2502
}
 
2503
 
 
2504
/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
 
2505
/// the types using zero-extension, and then perform a umax operation
 
2506
/// with them.
 
2507
const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
 
2508
                                                        const SCEV *RHS) {
 
2509
  const SCEV *PromotedLHS = LHS;
 
2510
  const SCEV *PromotedRHS = RHS;
 
2511
 
 
2512
  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
 
2513
    PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
 
2514
  else
 
2515
    PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
 
2516
 
 
2517
  return getUMaxExpr(PromotedLHS, PromotedRHS);
 
2518
}
 
2519
 
 
2520
/// getUMinFromMismatchedTypes - Promote the operands to the wider of
 
2521
/// the types using zero-extension, and then perform a umin operation
 
2522
/// with them.
 
2523
const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
 
2524
                                                        const SCEV *RHS) {
 
2525
  const SCEV *PromotedLHS = LHS;
 
2526
  const SCEV *PromotedRHS = RHS;
 
2527
 
 
2528
  if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
 
2529
    PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
 
2530
  else
 
2531
    PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
 
2532
 
 
2533
  return getUMinExpr(PromotedLHS, PromotedRHS);
 
2534
}
 
2535
 
 
2536
/// PushDefUseChildren - Push users of the given Instruction
 
2537
/// onto the given Worklist.
 
2538
static void
 
2539
PushDefUseChildren(Instruction *I,
 
2540
                   SmallVectorImpl<Instruction *> &Worklist) {
 
2541
  // Push the def-use children onto the Worklist stack.
 
2542
  for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
 
2543
       UI != UE; ++UI)
 
2544
    Worklist.push_back(cast<Instruction>(UI));
 
2545
}
 
2546
 
 
2547
/// ForgetSymbolicValue - This looks up computed SCEV values for all
 
2548
/// instructions that depend on the given instruction and removes them from
 
2549
/// the Scalars map if they reference SymName. This is used during PHI
 
2550
/// resolution.
 
2551
void
 
2552
ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
 
2553
  SmallVector<Instruction *, 16> Worklist;
 
2554
  PushDefUseChildren(PN, Worklist);
 
2555
 
 
2556
  SmallPtrSet<Instruction *, 8> Visited;
 
2557
  Visited.insert(PN);
 
2558
  while (!Worklist.empty()) {
 
2559
    Instruction *I = Worklist.pop_back_val();
 
2560
    if (!Visited.insert(I)) continue;
 
2561
 
 
2562
    std::map<SCEVCallbackVH, const SCEV *>::iterator It =
 
2563
      Scalars.find(static_cast<Value *>(I));
 
2564
    if (It != Scalars.end()) {
 
2565
      // Short-circuit the def-use traversal if the symbolic name
 
2566
      // ceases to appear in expressions.
 
2567
      if (It->second != SymName && !It->second->hasOperand(SymName))
 
2568
        continue;
 
2569
 
 
2570
      // SCEVUnknown for a PHI either means that it has an unrecognized
 
2571
      // structure, it's a PHI that's in the progress of being computed
 
2572
      // by createNodeForPHI, or it's a single-value PHI. In the first case,
 
2573
      // additional loop trip count information isn't going to change anything.
 
2574
      // In the second case, createNodeForPHI will perform the necessary
 
2575
      // updates on its own when it gets to that point. In the third, we do
 
2576
      // want to forget the SCEVUnknown.
 
2577
      if (!isa<PHINode>(I) ||
 
2578
          !isa<SCEVUnknown>(It->second) ||
 
2579
          (I != PN && It->second == SymName)) {
 
2580
        ValuesAtScopes.erase(It->second);
 
2581
        Scalars.erase(It);
 
2582
      }
 
2583
    }
 
2584
 
 
2585
    PushDefUseChildren(I, Worklist);
 
2586
  }
 
2587
}
 
2588
 
 
2589
/// createNodeForPHI - PHI nodes have two cases.  Either the PHI node exists in
 
2590
/// a loop header, making it a potential recurrence, or it doesn't.
 
2591
///
 
2592
const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
 
2593
  if (PN->getNumIncomingValues() == 2)  // The loops have been canonicalized.
 
2594
    if (const Loop *L = LI->getLoopFor(PN->getParent()))
 
2595
      if (L->getHeader() == PN->getParent()) {
 
2596
        // If it lives in the loop header, it has two incoming values, one
 
2597
        // from outside the loop, and one from inside.
 
2598
        unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
 
2599
        unsigned BackEdge     = IncomingEdge^1;
 
2600
 
 
2601
        // While we are analyzing this PHI node, handle its value symbolically.
 
2602
        const SCEV *SymbolicName = getUnknown(PN);
 
2603
        assert(Scalars.find(PN) == Scalars.end() &&
 
2604
               "PHI node already processed?");
 
2605
        Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
 
2606
 
 
2607
        // Using this symbolic name for the PHI, analyze the value coming around
 
2608
        // the back-edge.
 
2609
        Value *BEValueV = PN->getIncomingValue(BackEdge);
 
2610
        const SCEV *BEValue = getSCEV(BEValueV);
 
2611
 
 
2612
        // NOTE: If BEValue is loop invariant, we know that the PHI node just
 
2613
        // has a special value for the first iteration of the loop.
 
2614
 
 
2615
        // If the value coming around the backedge is an add with the symbolic
 
2616
        // value we just inserted, then we found a simple induction variable!
 
2617
        if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
 
2618
          // If there is a single occurrence of the symbolic value, replace it
 
2619
          // with a recurrence.
 
2620
          unsigned FoundIndex = Add->getNumOperands();
 
2621
          for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
 
2622
            if (Add->getOperand(i) == SymbolicName)
 
2623
              if (FoundIndex == e) {
 
2624
                FoundIndex = i;
 
2625
                break;
 
2626
              }
 
2627
 
 
2628
          if (FoundIndex != Add->getNumOperands()) {
 
2629
            // Create an add with everything but the specified operand.
 
2630
            SmallVector<const SCEV *, 8> Ops;
 
2631
            for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
 
2632
              if (i != FoundIndex)
 
2633
                Ops.push_back(Add->getOperand(i));
 
2634
            const SCEV *Accum = getAddExpr(Ops);
 
2635
 
 
2636
            // This is not a valid addrec if the step amount is varying each
 
2637
            // loop iteration, but is not itself an addrec in this loop.
 
2638
            if (Accum->isLoopInvariant(L) ||
 
2639
                (isa<SCEVAddRecExpr>(Accum) &&
 
2640
                 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
 
2641
              bool HasNUW = false;
 
2642
              bool HasNSW = false;
 
2643
 
 
2644
              // If the increment doesn't overflow, then neither the addrec nor
 
2645
              // the post-increment will overflow.
 
2646
              if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
 
2647
                if (OBO->hasNoUnsignedWrap())
 
2648
                  HasNUW = true;
 
2649
                if (OBO->hasNoSignedWrap())
 
2650
                  HasNSW = true;
 
2651
              }
 
2652
 
 
2653
              const SCEV *StartVal =
 
2654
                getSCEV(PN->getIncomingValue(IncomingEdge));
 
2655
              const SCEV *PHISCEV =
 
2656
                getAddRecExpr(StartVal, Accum, L, HasNUW, HasNSW);
 
2657
 
 
2658
              // Since the no-wrap flags are on the increment, they apply to the
 
2659
              // post-incremented value as well.
 
2660
              if (Accum->isLoopInvariant(L))
 
2661
                (void)getAddRecExpr(getAddExpr(StartVal, Accum),
 
2662
                                    Accum, L, HasNUW, HasNSW);
 
2663
 
 
2664
              // Okay, for the entire analysis of this edge we assumed the PHI
 
2665
              // to be symbolic.  We now need to go back and purge all of the
 
2666
              // entries for the scalars that use the symbolic expression.
 
2667
              ForgetSymbolicName(PN, SymbolicName);
 
2668
              Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
 
2669
              return PHISCEV;
 
2670
            }
 
2671
          }
 
2672
        } else if (const SCEVAddRecExpr *AddRec =
 
2673
                     dyn_cast<SCEVAddRecExpr>(BEValue)) {
 
2674
          // Otherwise, this could be a loop like this:
 
2675
          //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
 
2676
          // In this case, j = {1,+,1}  and BEValue is j.
 
2677
          // Because the other in-value of i (0) fits the evolution of BEValue
 
2678
          // i really is an addrec evolution.
 
2679
          if (AddRec->getLoop() == L && AddRec->isAffine()) {
 
2680
            const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
 
2681
 
 
2682
            // If StartVal = j.start - j.stride, we can use StartVal as the
 
2683
            // initial step of the addrec evolution.
 
2684
            if (StartVal == getMinusSCEV(AddRec->getOperand(0),
 
2685
                                            AddRec->getOperand(1))) {
 
2686
              const SCEV *PHISCEV =
 
2687
                 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
 
2688
 
 
2689
              // Okay, for the entire analysis of this edge we assumed the PHI
 
2690
              // to be symbolic.  We now need to go back and purge all of the
 
2691
              // entries for the scalars that use the symbolic expression.
 
2692
              ForgetSymbolicName(PN, SymbolicName);
 
2693
              Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
 
2694
              return PHISCEV;
 
2695
            }
 
2696
          }
 
2697
        }
 
2698
 
 
2699
        return SymbolicName;
 
2700
      }
 
2701
 
 
2702
  // If the PHI has a single incoming value, follow that value, unless the
 
2703
  // PHI's incoming blocks are in a different loop, in which case doing so
 
2704
  // risks breaking LCSSA form. Instcombine would normally zap these, but
 
2705
  // it doesn't have DominatorTree information, so it may miss cases.
 
2706
  if (Value *V = PN->hasConstantValue(DT)) {
 
2707
    bool AllSameLoop = true;
 
2708
    Loop *PNLoop = LI->getLoopFor(PN->getParent());
 
2709
    for (size_t i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
 
2710
      if (LI->getLoopFor(PN->getIncomingBlock(i)) != PNLoop) {
 
2711
        AllSameLoop = false;
 
2712
        break;
 
2713
      }
 
2714
    if (AllSameLoop)
 
2715
      return getSCEV(V);
 
2716
  }
 
2717
 
 
2718
  // If it's not a loop phi, we can't handle it yet.
 
2719
  return getUnknown(PN);
 
2720
}
 
2721
 
 
2722
/// createNodeForGEP - Expand GEP instructions into add and multiply
 
2723
/// operations. This allows them to be analyzed by regular SCEV code.
 
2724
///
 
2725
const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
 
2726
 
 
2727
  bool InBounds = GEP->isInBounds();
 
2728
  const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
 
2729
  Value *Base = GEP->getOperand(0);
 
2730
  // Don't attempt to analyze GEPs over unsized objects.
 
2731
  if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
 
2732
    return getUnknown(GEP);
 
2733
  const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
 
2734
  gep_type_iterator GTI = gep_type_begin(GEP);
 
2735
  for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
 
2736
                                      E = GEP->op_end();
 
2737
       I != E; ++I) {
 
2738
    Value *Index = *I;
 
2739
    // Compute the (potentially symbolic) offset in bytes for this index.
 
2740
    if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
 
2741
      // For a struct, add the member offset.
 
2742
      unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
 
2743
      TotalOffset = getAddExpr(TotalOffset,
 
2744
                               getOffsetOfExpr(STy, FieldNo),
 
2745
                               /*HasNUW=*/false, /*HasNSW=*/InBounds);
 
2746
    } else {
 
2747
      // For an array, add the element offset, explicitly scaled.
 
2748
      const SCEV *LocalOffset = getSCEV(Index);
 
2749
      // Getelementptr indices are signed.
 
2750
      LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
 
2751
      // Lower "inbounds" GEPs to NSW arithmetic.
 
2752
      LocalOffset = getMulExpr(LocalOffset, getSizeOfExpr(*GTI),
 
2753
                               /*HasNUW=*/false, /*HasNSW=*/InBounds);
 
2754
      TotalOffset = getAddExpr(TotalOffset, LocalOffset,
 
2755
                               /*HasNUW=*/false, /*HasNSW=*/InBounds);
 
2756
    }
 
2757
  }
 
2758
  return getAddExpr(getSCEV(Base), TotalOffset,
 
2759
                    /*HasNUW=*/false, /*HasNSW=*/InBounds);
 
2760
}
 
2761
 
 
2762
/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
 
2763
/// guaranteed to end in (at every loop iteration).  It is, at the same time,
 
2764
/// the minimum number of times S is divisible by 2.  For example, given {4,+,8}
 
2765
/// it returns 2.  If S is guaranteed to be 0, it returns the bitwidth of S.
 
2766
uint32_t
 
2767
ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
 
2768
  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
 
2769
    return C->getValue()->getValue().countTrailingZeros();
 
2770
 
 
2771
  if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
 
2772
    return std::min(GetMinTrailingZeros(T->getOperand()),
 
2773
                    (uint32_t)getTypeSizeInBits(T->getType()));
 
2774
 
 
2775
  if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
 
2776
    uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
 
2777
    return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
 
2778
             getTypeSizeInBits(E->getType()) : OpRes;
 
2779
  }
 
2780
 
 
2781
  if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
 
2782
    uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
 
2783
    return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
 
2784
             getTypeSizeInBits(E->getType()) : OpRes;
 
2785
  }
 
2786
 
 
2787
  if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
 
2788
    // The result is the min of all operands results.
 
2789
    uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
 
2790
    for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
 
2791
      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
 
2792
    return MinOpRes;
 
2793
  }
 
2794
 
 
2795
  if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
 
2796
    // The result is the sum of all operands results.
 
2797
    uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
 
2798
    uint32_t BitWidth = getTypeSizeInBits(M->getType());
 
2799
    for (unsigned i = 1, e = M->getNumOperands();
 
2800
         SumOpRes != BitWidth && i != e; ++i)
 
2801
      SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
 
2802
                          BitWidth);
 
2803
    return SumOpRes;
 
2804
  }
 
2805
 
 
2806
  if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
 
2807
    // The result is the min of all operands results.
 
2808
    uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
 
2809
    for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
 
2810
      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
 
2811
    return MinOpRes;
 
2812
  }
 
2813
 
 
2814
  if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
 
2815
    // The result is the min of all operands results.
 
2816
    uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
 
2817
    for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
 
2818
      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
 
2819
    return MinOpRes;
 
2820
  }
 
2821
 
 
2822
  if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
 
2823
    // The result is the min of all operands results.
 
2824
    uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
 
2825
    for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
 
2826
      MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
 
2827
    return MinOpRes;
 
2828
  }
 
2829
 
 
2830
  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
 
2831
    // For a SCEVUnknown, ask ValueTracking.
 
2832
    unsigned BitWidth = getTypeSizeInBits(U->getType());
 
2833
    APInt Mask = APInt::getAllOnesValue(BitWidth);
 
2834
    APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
 
2835
    ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
 
2836
    return Zeros.countTrailingOnes();
 
2837
  }
 
2838
 
 
2839
  // SCEVUDivExpr
 
2840
  return 0;
 
2841
}
 
2842
 
 
2843
/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
 
2844
///
 
2845
ConstantRange
 
2846
ScalarEvolution::getUnsignedRange(const SCEV *S) {
 
2847
 
 
2848
  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
 
2849
    return ConstantRange(C->getValue()->getValue());
 
2850
 
 
2851
  unsigned BitWidth = getTypeSizeInBits(S->getType());
 
2852
  ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
 
2853
 
 
2854
  // If the value has known zeros, the maximum unsigned value will have those
 
2855
  // known zeros as well.
 
2856
  uint32_t TZ = GetMinTrailingZeros(S);
 
2857
  if (TZ != 0)
 
2858
    ConservativeResult =
 
2859
      ConstantRange(APInt::getMinValue(BitWidth),
 
2860
                    APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
 
2861
 
 
2862
  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
 
2863
    ConstantRange X = getUnsignedRange(Add->getOperand(0));
 
2864
    for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
 
2865
      X = X.add(getUnsignedRange(Add->getOperand(i)));
 
2866
    return ConservativeResult.intersectWith(X);
 
2867
  }
 
2868
 
 
2869
  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
 
2870
    ConstantRange X = getUnsignedRange(Mul->getOperand(0));
 
2871
    for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
 
2872
      X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
 
2873
    return ConservativeResult.intersectWith(X);
 
2874
  }
 
2875
 
 
2876
  if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
 
2877
    ConstantRange X = getUnsignedRange(SMax->getOperand(0));
 
2878
    for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
 
2879
      X = X.smax(getUnsignedRange(SMax->getOperand(i)));
 
2880
    return ConservativeResult.intersectWith(X);
 
2881
  }
 
2882
 
 
2883
  if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
 
2884
    ConstantRange X = getUnsignedRange(UMax->getOperand(0));
 
2885
    for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
 
2886
      X = X.umax(getUnsignedRange(UMax->getOperand(i)));
 
2887
    return ConservativeResult.intersectWith(X);
 
2888
  }
 
2889
 
 
2890
  if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
 
2891
    ConstantRange X = getUnsignedRange(UDiv->getLHS());
 
2892
    ConstantRange Y = getUnsignedRange(UDiv->getRHS());
 
2893
    return ConservativeResult.intersectWith(X.udiv(Y));
 
2894
  }
 
2895
 
 
2896
  if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
 
2897
    ConstantRange X = getUnsignedRange(ZExt->getOperand());
 
2898
    return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
 
2899
  }
 
2900
 
 
2901
  if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
 
2902
    ConstantRange X = getUnsignedRange(SExt->getOperand());
 
2903
    return ConservativeResult.intersectWith(X.signExtend(BitWidth));
 
2904
  }
 
2905
 
 
2906
  if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
 
2907
    ConstantRange X = getUnsignedRange(Trunc->getOperand());
 
2908
    return ConservativeResult.intersectWith(X.truncate(BitWidth));
 
2909
  }
 
2910
 
 
2911
  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
 
2912
    // If there's no unsigned wrap, the value will never be less than its
 
2913
    // initial value.
 
2914
    if (AddRec->hasNoUnsignedWrap())
 
2915
      if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
 
2916
        ConservativeResult =
 
2917
          ConstantRange(C->getValue()->getValue(),
 
2918
                        APInt(getTypeSizeInBits(C->getType()), 0));
 
2919
 
 
2920
    // TODO: non-affine addrec
 
2921
    if (AddRec->isAffine()) {
 
2922
      const Type *Ty = AddRec->getType();
 
2923
      const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
 
2924
      if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
 
2925
          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
 
2926
        MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
 
2927
 
 
2928
        const SCEV *Start = AddRec->getStart();
 
2929
        const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
 
2930
 
 
2931
        // Check for overflow.
 
2932
        if (!AddRec->hasNoUnsignedWrap())
 
2933
          return ConservativeResult;
 
2934
 
 
2935
        ConstantRange StartRange = getUnsignedRange(Start);
 
2936
        ConstantRange EndRange = getUnsignedRange(End);
 
2937
        APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
 
2938
                                   EndRange.getUnsignedMin());
 
2939
        APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
 
2940
                                   EndRange.getUnsignedMax());
 
2941
        if (Min.isMinValue() && Max.isMaxValue())
 
2942
          return ConservativeResult;
 
2943
        return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
 
2944
      }
 
2945
    }
 
2946
 
 
2947
    return ConservativeResult;
 
2948
  }
 
2949
 
 
2950
  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
 
2951
    // For a SCEVUnknown, ask ValueTracking.
 
2952
    APInt Mask = APInt::getAllOnesValue(BitWidth);
 
2953
    APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
 
2954
    ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
 
2955
    if (Ones == ~Zeros + 1)
 
2956
      return ConservativeResult;
 
2957
    return ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
 
2958
  }
 
2959
 
 
2960
  return ConservativeResult;
 
2961
}
 
2962
 
 
2963
/// getSignedRange - Determine the signed range for a particular SCEV.
 
2964
///
 
2965
ConstantRange
 
2966
ScalarEvolution::getSignedRange(const SCEV *S) {
 
2967
 
 
2968
  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
 
2969
    return ConstantRange(C->getValue()->getValue());
 
2970
 
 
2971
  unsigned BitWidth = getTypeSizeInBits(S->getType());
 
2972
  ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
 
2973
 
 
2974
  // If the value has known zeros, the maximum signed value will have those
 
2975
  // known zeros as well.
 
2976
  uint32_t TZ = GetMinTrailingZeros(S);
 
2977
  if (TZ != 0)
 
2978
    ConservativeResult =
 
2979
      ConstantRange(APInt::getSignedMinValue(BitWidth),
 
2980
                    APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
 
2981
 
 
2982
  if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
 
2983
    ConstantRange X = getSignedRange(Add->getOperand(0));
 
2984
    for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
 
2985
      X = X.add(getSignedRange(Add->getOperand(i)));
 
2986
    return ConservativeResult.intersectWith(X);
 
2987
  }
 
2988
 
 
2989
  if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
 
2990
    ConstantRange X = getSignedRange(Mul->getOperand(0));
 
2991
    for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
 
2992
      X = X.multiply(getSignedRange(Mul->getOperand(i)));
 
2993
    return ConservativeResult.intersectWith(X);
 
2994
  }
 
2995
 
 
2996
  if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
 
2997
    ConstantRange X = getSignedRange(SMax->getOperand(0));
 
2998
    for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
 
2999
      X = X.smax(getSignedRange(SMax->getOperand(i)));
 
3000
    return ConservativeResult.intersectWith(X);
 
3001
  }
 
3002
 
 
3003
  if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
 
3004
    ConstantRange X = getSignedRange(UMax->getOperand(0));
 
3005
    for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
 
3006
      X = X.umax(getSignedRange(UMax->getOperand(i)));
 
3007
    return ConservativeResult.intersectWith(X);
 
3008
  }
 
3009
 
 
3010
  if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
 
3011
    ConstantRange X = getSignedRange(UDiv->getLHS());
 
3012
    ConstantRange Y = getSignedRange(UDiv->getRHS());
 
3013
    return ConservativeResult.intersectWith(X.udiv(Y));
 
3014
  }
 
3015
 
 
3016
  if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
 
3017
    ConstantRange X = getSignedRange(ZExt->getOperand());
 
3018
    return ConservativeResult.intersectWith(X.zeroExtend(BitWidth));
 
3019
  }
 
3020
 
 
3021
  if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
 
3022
    ConstantRange X = getSignedRange(SExt->getOperand());
 
3023
    return ConservativeResult.intersectWith(X.signExtend(BitWidth));
 
3024
  }
 
3025
 
 
3026
  if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
 
3027
    ConstantRange X = getSignedRange(Trunc->getOperand());
 
3028
    return ConservativeResult.intersectWith(X.truncate(BitWidth));
 
3029
  }
 
3030
 
 
3031
  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
 
3032
    // If there's no signed wrap, and all the operands have the same sign or
 
3033
    // zero, the value won't ever change sign.
 
3034
    if (AddRec->hasNoSignedWrap()) {
 
3035
      bool AllNonNeg = true;
 
3036
      bool AllNonPos = true;
 
3037
      for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
 
3038
        if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
 
3039
        if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
 
3040
      }
 
3041
      if (AllNonNeg)
 
3042
        ConservativeResult = ConservativeResult.intersectWith(
 
3043
          ConstantRange(APInt(BitWidth, 0),
 
3044
                        APInt::getSignedMinValue(BitWidth)));
 
3045
      else if (AllNonPos)
 
3046
        ConservativeResult = ConservativeResult.intersectWith(
 
3047
          ConstantRange(APInt::getSignedMinValue(BitWidth),
 
3048
                        APInt(BitWidth, 1)));
 
3049
    }
 
3050
 
 
3051
    // TODO: non-affine addrec
 
3052
    if (AddRec->isAffine()) {
 
3053
      const Type *Ty = AddRec->getType();
 
3054
      const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
 
3055
      if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
 
3056
          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
 
3057
        MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
 
3058
 
 
3059
        const SCEV *Start = AddRec->getStart();
 
3060
        const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
 
3061
 
 
3062
        // Check for overflow.
 
3063
        if (!AddRec->hasNoSignedWrap())
 
3064
          return ConservativeResult;
 
3065
 
 
3066
        ConstantRange StartRange = getSignedRange(Start);
 
3067
        ConstantRange EndRange = getSignedRange(End);
 
3068
        APInt Min = APIntOps::smin(StartRange.getSignedMin(),
 
3069
                                   EndRange.getSignedMin());
 
3070
        APInt Max = APIntOps::smax(StartRange.getSignedMax(),
 
3071
                                   EndRange.getSignedMax());
 
3072
        if (Min.isMinSignedValue() && Max.isMaxSignedValue())
 
3073
          return ConservativeResult;
 
3074
        return ConservativeResult.intersectWith(ConstantRange(Min, Max+1));
 
3075
      }
 
3076
    }
 
3077
 
 
3078
    return ConservativeResult;
 
3079
  }
 
3080
 
 
3081
  if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
 
3082
    // For a SCEVUnknown, ask ValueTracking.
 
3083
    if (!U->getValue()->getType()->isIntegerTy() && !TD)
 
3084
      return ConservativeResult;
 
3085
    unsigned NS = ComputeNumSignBits(U->getValue(), TD);
 
3086
    if (NS == 1)
 
3087
      return ConservativeResult;
 
3088
    return ConservativeResult.intersectWith(
 
3089
      ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
 
3090
                    APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1));
 
3091
  }
 
3092
 
 
3093
  return ConservativeResult;
 
3094
}
 
3095
 
 
3096
/// createSCEV - We know that there is no SCEV for the specified value.
 
3097
/// Analyze the expression.
 
3098
///
 
3099
const SCEV *ScalarEvolution::createSCEV(Value *V) {
 
3100
  if (!isSCEVable(V->getType()))
 
3101
    return getUnknown(V);
 
3102
 
 
3103
  unsigned Opcode = Instruction::UserOp1;
 
3104
  if (Instruction *I = dyn_cast<Instruction>(V))
 
3105
    Opcode = I->getOpcode();
 
3106
  else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
 
3107
    Opcode = CE->getOpcode();
 
3108
  else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
 
3109
    return getConstant(CI);
 
3110
  else if (isa<ConstantPointerNull>(V))
 
3111
    return getIntegerSCEV(0, V->getType());
 
3112
  else if (isa<UndefValue>(V))
 
3113
    return getIntegerSCEV(0, V->getType());
 
3114
  else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
 
3115
    return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
 
3116
  else
 
3117
    return getUnknown(V);
 
3118
 
 
3119
  Operator *U = cast<Operator>(V);
 
3120
  switch (Opcode) {
 
3121
  case Instruction::Add:
 
3122
    // Don't transfer the NSW and NUW bits from the Add instruction to the
 
3123
    // Add expression, because the Instruction may be guarded by control
 
3124
    // flow and the no-overflow bits may not be valid for the expression in
 
3125
    // any context.
 
3126
    return getAddExpr(getSCEV(U->getOperand(0)),
 
3127
                      getSCEV(U->getOperand(1)));
 
3128
  case Instruction::Mul:
 
3129
    // Don't transfer the NSW and NUW bits from the Mul instruction to the
 
3130
    // Mul expression, as with Add.
 
3131
    return getMulExpr(getSCEV(U->getOperand(0)),
 
3132
                      getSCEV(U->getOperand(1)));
 
3133
  case Instruction::UDiv:
 
3134
    return getUDivExpr(getSCEV(U->getOperand(0)),
 
3135
                       getSCEV(U->getOperand(1)));
 
3136
  case Instruction::Sub:
 
3137
    return getMinusSCEV(getSCEV(U->getOperand(0)),
 
3138
                        getSCEV(U->getOperand(1)));
 
3139
  case Instruction::And:
 
3140
    // For an expression like x&255 that merely masks off the high bits,
 
3141
    // use zext(trunc(x)) as the SCEV expression.
 
3142
    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
 
3143
      if (CI->isNullValue())
 
3144
        return getSCEV(U->getOperand(1));
 
3145
      if (CI->isAllOnesValue())
 
3146
        return getSCEV(U->getOperand(0));
 
3147
      const APInt &A = CI->getValue();
 
3148
 
 
3149
      // Instcombine's ShrinkDemandedConstant may strip bits out of
 
3150
      // constants, obscuring what would otherwise be a low-bits mask.
 
3151
      // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
 
3152
      // knew about to reconstruct a low-bits mask value.
 
3153
      unsigned LZ = A.countLeadingZeros();
 
3154
      unsigned BitWidth = A.getBitWidth();
 
3155
      APInt AllOnes = APInt::getAllOnesValue(BitWidth);
 
3156
      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
 
3157
      ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
 
3158
 
 
3159
      APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
 
3160
 
 
3161
      if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
 
3162
        return
 
3163
          getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
 
3164
                                IntegerType::get(getContext(), BitWidth - LZ)),
 
3165
                            U->getType());
 
3166
    }
 
3167
    break;
 
3168
 
 
3169
  case Instruction::Or:
 
3170
    // If the RHS of the Or is a constant, we may have something like:
 
3171
    // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
 
3172
    // optimizations will transparently handle this case.
 
3173
    //
 
3174
    // In order for this transformation to be safe, the LHS must be of the
 
3175
    // form X*(2^n) and the Or constant must be less than 2^n.
 
3176
    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
 
3177
      const SCEV *LHS = getSCEV(U->getOperand(0));
 
3178
      const APInt &CIVal = CI->getValue();
 
3179
      if (GetMinTrailingZeros(LHS) >=
 
3180
          (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
 
3181
        // Build a plain add SCEV.
 
3182
        const SCEV *S = getAddExpr(LHS, getSCEV(CI));
 
3183
        // If the LHS of the add was an addrec and it has no-wrap flags,
 
3184
        // transfer the no-wrap flags, since an or won't introduce a wrap.
 
3185
        if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
 
3186
          const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
 
3187
          if (OldAR->hasNoUnsignedWrap())
 
3188
            const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
 
3189
          if (OldAR->hasNoSignedWrap())
 
3190
            const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
 
3191
        }
 
3192
        return S;
 
3193
      }
 
3194
    }
 
3195
    break;
 
3196
  case Instruction::Xor:
 
3197
    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
 
3198
      // If the RHS of the xor is a signbit, then this is just an add.
 
3199
      // Instcombine turns add of signbit into xor as a strength reduction step.
 
3200
      if (CI->getValue().isSignBit())
 
3201
        return getAddExpr(getSCEV(U->getOperand(0)),
 
3202
                          getSCEV(U->getOperand(1)));
 
3203
 
 
3204
      // If the RHS of xor is -1, then this is a not operation.
 
3205
      if (CI->isAllOnesValue())
 
3206
        return getNotSCEV(getSCEV(U->getOperand(0)));
 
3207
 
 
3208
      // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
 
3209
      // This is a variant of the check for xor with -1, and it handles
 
3210
      // the case where instcombine has trimmed non-demanded bits out
 
3211
      // of an xor with -1.
 
3212
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
 
3213
        if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
 
3214
          if (BO->getOpcode() == Instruction::And &&
 
3215
              LCI->getValue() == CI->getValue())
 
3216
            if (const SCEVZeroExtendExpr *Z =
 
3217
                  dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
 
3218
              const Type *UTy = U->getType();
 
3219
              const SCEV *Z0 = Z->getOperand();
 
3220
              const Type *Z0Ty = Z0->getType();
 
3221
              unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
 
3222
 
 
3223
              // If C is a low-bits mask, the zero extend is serving to
 
3224
              // mask off the high bits. Complement the operand and
 
3225
              // re-apply the zext.
 
3226
              if (APIntOps::isMask(Z0TySize, CI->getValue()))
 
3227
                return getZeroExtendExpr(getNotSCEV(Z0), UTy);
 
3228
 
 
3229
              // If C is a single bit, it may be in the sign-bit position
 
3230
              // before the zero-extend. In this case, represent the xor
 
3231
              // using an add, which is equivalent, and re-apply the zext.
 
3232
              APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
 
3233
              if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
 
3234
                  Trunc.isSignBit())
 
3235
                return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
 
3236
                                         UTy);
 
3237
            }
 
3238
    }
 
3239
    break;
 
3240
 
 
3241
  case Instruction::Shl:
 
3242
    // Turn shift left of a constant amount into a multiply.
 
3243
    if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
 
3244
      uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
 
3245
      Constant *X = ConstantInt::get(getContext(),
 
3246
        APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
 
3247
      return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
 
3248
    }
 
3249
    break;
 
3250
 
 
3251
  case Instruction::LShr:
 
3252
    // Turn logical shift right of a constant into a unsigned divide.
 
3253
    if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
 
3254
      uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
 
3255
      Constant *X = ConstantInt::get(getContext(),
 
3256
        APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
 
3257
      return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
 
3258
    }
 
3259
    break;
 
3260
 
 
3261
  case Instruction::AShr:
 
3262
    // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
 
3263
    if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
 
3264
      if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
 
3265
        if (L->getOpcode() == Instruction::Shl &&
 
3266
            L->getOperand(1) == U->getOperand(1)) {
 
3267
          unsigned BitWidth = getTypeSizeInBits(U->getType());
 
3268
          uint64_t Amt = BitWidth - CI->getZExtValue();
 
3269
          if (Amt == BitWidth)
 
3270
            return getSCEV(L->getOperand(0));       // shift by zero --> noop
 
3271
          if (Amt > BitWidth)
 
3272
            return getIntegerSCEV(0, U->getType()); // value is undefined
 
3273
          return
 
3274
            getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
 
3275
                                           IntegerType::get(getContext(), Amt)),
 
3276
                                 U->getType());
 
3277
        }
 
3278
    break;
 
3279
 
 
3280
  case Instruction::Trunc:
 
3281
    return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
 
3282
 
 
3283
  case Instruction::ZExt:
 
3284
    return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
 
3285
 
 
3286
  case Instruction::SExt:
 
3287
    return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
 
3288
 
 
3289
  case Instruction::BitCast:
 
3290
    // BitCasts are no-op casts so we just eliminate the cast.
 
3291
    if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
 
3292
      return getSCEV(U->getOperand(0));
 
3293
    break;
 
3294
 
 
3295
  // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
 
3296
  // lead to pointer expressions which cannot safely be expanded to GEPs,
 
3297
  // because ScalarEvolution doesn't respect the GEP aliasing rules when
 
3298
  // simplifying integer expressions.
 
3299
 
 
3300
  case Instruction::GetElementPtr:
 
3301
    return createNodeForGEP(cast<GEPOperator>(U));
 
3302
 
 
3303
  case Instruction::PHI:
 
3304
    return createNodeForPHI(cast<PHINode>(U));
 
3305
 
 
3306
  case Instruction::Select:
 
3307
    // This could be a smax or umax that was lowered earlier.
 
3308
    // Try to recover it.
 
3309
    if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
 
3310
      Value *LHS = ICI->getOperand(0);
 
3311
      Value *RHS = ICI->getOperand(1);
 
3312
      switch (ICI->getPredicate()) {
 
3313
      case ICmpInst::ICMP_SLT:
 
3314
      case ICmpInst::ICMP_SLE:
 
3315
        std::swap(LHS, RHS);
 
3316
        // fall through
 
3317
      case ICmpInst::ICMP_SGT:
 
3318
      case ICmpInst::ICMP_SGE:
 
3319
        if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
 
3320
          return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
 
3321
        else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
 
3322
          return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
 
3323
        break;
 
3324
      case ICmpInst::ICMP_ULT:
 
3325
      case ICmpInst::ICMP_ULE:
 
3326
        std::swap(LHS, RHS);
 
3327
        // fall through
 
3328
      case ICmpInst::ICMP_UGT:
 
3329
      case ICmpInst::ICMP_UGE:
 
3330
        if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
 
3331
          return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
 
3332
        else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
 
3333
          return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
 
3334
        break;
 
3335
      case ICmpInst::ICMP_NE:
 
3336
        // n != 0 ? n : 1  ->  umax(n, 1)
 
3337
        if (LHS == U->getOperand(1) &&
 
3338
            isa<ConstantInt>(U->getOperand(2)) &&
 
3339
            cast<ConstantInt>(U->getOperand(2))->isOne() &&
 
3340
            isa<ConstantInt>(RHS) &&
 
3341
            cast<ConstantInt>(RHS)->isZero())
 
3342
          return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
 
3343
        break;
 
3344
      case ICmpInst::ICMP_EQ:
 
3345
        // n == 0 ? 1 : n  ->  umax(n, 1)
 
3346
        if (LHS == U->getOperand(2) &&
 
3347
            isa<ConstantInt>(U->getOperand(1)) &&
 
3348
            cast<ConstantInt>(U->getOperand(1))->isOne() &&
 
3349
            isa<ConstantInt>(RHS) &&
 
3350
            cast<ConstantInt>(RHS)->isZero())
 
3351
          return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
 
3352
        break;
 
3353
      default:
 
3354
        break;
 
3355
      }
 
3356
    }
 
3357
 
 
3358
  default: // We cannot analyze this expression.
 
3359
    break;
 
3360
  }
 
3361
 
 
3362
  return getUnknown(V);
 
3363
}
 
3364
 
 
3365
 
 
3366
 
 
3367
//===----------------------------------------------------------------------===//
 
3368
//                   Iteration Count Computation Code
 
3369
//
 
3370
 
 
3371
/// getBackedgeTakenCount - If the specified loop has a predictable
 
3372
/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
 
3373
/// object. The backedge-taken count is the number of times the loop header
 
3374
/// will be branched to from within the loop. This is one less than the
 
3375
/// trip count of the loop, since it doesn't count the first iteration,
 
3376
/// when the header is branched to from outside the loop.
 
3377
///
 
3378
/// Note that it is not valid to call this method on a loop without a
 
3379
/// loop-invariant backedge-taken count (see
 
3380
/// hasLoopInvariantBackedgeTakenCount).
 
3381
///
 
3382
const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
 
3383
  return getBackedgeTakenInfo(L).Exact;
 
3384
}
 
3385
 
 
3386
/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
 
3387
/// return the least SCEV value that is known never to be less than the
 
3388
/// actual backedge taken count.
 
3389
const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
 
3390
  return getBackedgeTakenInfo(L).Max;
 
3391
}
 
3392
 
 
3393
/// PushLoopPHIs - Push PHI nodes in the header of the given loop
 
3394
/// onto the given Worklist.
 
3395
static void
 
3396
PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
 
3397
  BasicBlock *Header = L->getHeader();
 
3398
 
 
3399
  // Push all Loop-header PHIs onto the Worklist stack.
 
3400
  for (BasicBlock::iterator I = Header->begin();
 
3401
       PHINode *PN = dyn_cast<PHINode>(I); ++I)
 
3402
    Worklist.push_back(PN);
 
3403
}
 
3404
 
 
3405
const ScalarEvolution::BackedgeTakenInfo &
 
3406
ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
 
3407
  // Initially insert a CouldNotCompute for this loop. If the insertion
 
3408
  // succeeds, proceed to actually compute a backedge-taken count and
 
3409
  // update the value. The temporary CouldNotCompute value tells SCEV
 
3410
  // code elsewhere that it shouldn't attempt to request a new
 
3411
  // backedge-taken count, which could result in infinite recursion.
 
3412
  std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
 
3413
    BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
 
3414
  if (Pair.second) {
 
3415
    BackedgeTakenInfo BECount = ComputeBackedgeTakenCount(L);
 
3416
    if (BECount.Exact != getCouldNotCompute()) {
 
3417
      assert(BECount.Exact->isLoopInvariant(L) &&
 
3418
             BECount.Max->isLoopInvariant(L) &&
 
3419
             "Computed backedge-taken count isn't loop invariant for loop!");
 
3420
      ++NumTripCountsComputed;
 
3421
 
 
3422
      // Update the value in the map.
 
3423
      Pair.first->second = BECount;
 
3424
    } else {
 
3425
      if (BECount.Max != getCouldNotCompute())
 
3426
        // Update the value in the map.
 
3427
        Pair.first->second = BECount;
 
3428
      if (isa<PHINode>(L->getHeader()->begin()))
 
3429
        // Only count loops that have phi nodes as not being computable.
 
3430
        ++NumTripCountsNotComputed;
 
3431
    }
 
3432
 
 
3433
    // Now that we know more about the trip count for this loop, forget any
 
3434
    // existing SCEV values for PHI nodes in this loop since they are only
 
3435
    // conservative estimates made without the benefit of trip count
 
3436
    // information. This is similar to the code in forgetLoop, except that
 
3437
    // it handles SCEVUnknown PHI nodes specially.
 
3438
    if (BECount.hasAnyInfo()) {
 
3439
      SmallVector<Instruction *, 16> Worklist;
 
3440
      PushLoopPHIs(L, Worklist);
 
3441
 
 
3442
      SmallPtrSet<Instruction *, 8> Visited;
 
3443
      while (!Worklist.empty()) {
 
3444
        Instruction *I = Worklist.pop_back_val();
 
3445
        if (!Visited.insert(I)) continue;
 
3446
 
 
3447
        std::map<SCEVCallbackVH, const SCEV *>::iterator It =
 
3448
          Scalars.find(static_cast<Value *>(I));
 
3449
        if (It != Scalars.end()) {
 
3450
          // SCEVUnknown for a PHI either means that it has an unrecognized
 
3451
          // structure, or it's a PHI that's in the progress of being computed
 
3452
          // by createNodeForPHI.  In the former case, additional loop trip
 
3453
          // count information isn't going to change anything. In the later
 
3454
          // case, createNodeForPHI will perform the necessary updates on its
 
3455
          // own when it gets to that point.
 
3456
          if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
 
3457
            ValuesAtScopes.erase(It->second);
 
3458
            Scalars.erase(It);
 
3459
          }
 
3460
          if (PHINode *PN = dyn_cast<PHINode>(I))
 
3461
            ConstantEvolutionLoopExitValue.erase(PN);
 
3462
        }
 
3463
 
 
3464
        PushDefUseChildren(I, Worklist);
 
3465
      }
 
3466
    }
 
3467
  }
 
3468
  return Pair.first->second;
 
3469
}
 
3470
 
 
3471
/// forgetLoop - This method should be called by the client when it has
 
3472
/// changed a loop in a way that may effect ScalarEvolution's ability to
 
3473
/// compute a trip count, or if the loop is deleted.
 
3474
void ScalarEvolution::forgetLoop(const Loop *L) {
 
3475
  // Drop any stored trip count value.
 
3476
  BackedgeTakenCounts.erase(L);
 
3477
 
 
3478
  // Drop information about expressions based on loop-header PHIs.
 
3479
  SmallVector<Instruction *, 16> Worklist;
 
3480
  PushLoopPHIs(L, Worklist);
 
3481
 
 
3482
  SmallPtrSet<Instruction *, 8> Visited;
 
3483
  while (!Worklist.empty()) {
 
3484
    Instruction *I = Worklist.pop_back_val();
 
3485
    if (!Visited.insert(I)) continue;
 
3486
 
 
3487
    std::map<SCEVCallbackVH, const SCEV *>::iterator It =
 
3488
      Scalars.find(static_cast<Value *>(I));
 
3489
    if (It != Scalars.end()) {
 
3490
      ValuesAtScopes.erase(It->second);
 
3491
      Scalars.erase(It);
 
3492
      if (PHINode *PN = dyn_cast<PHINode>(I))
 
3493
        ConstantEvolutionLoopExitValue.erase(PN);
 
3494
    }
 
3495
 
 
3496
    PushDefUseChildren(I, Worklist);
 
3497
  }
 
3498
}
 
3499
 
 
3500
/// forgetValue - This method should be called by the client when it has
 
3501
/// changed a value in a way that may effect its value, or which may
 
3502
/// disconnect it from a def-use chain linking it to a loop.
 
3503
void ScalarEvolution::forgetValue(Value *V) {
 
3504
  Instruction *I = dyn_cast<Instruction>(V);
 
3505
  if (!I) return;
 
3506
 
 
3507
  // Drop information about expressions based on loop-header PHIs.
 
3508
  SmallVector<Instruction *, 16> Worklist;
 
3509
  Worklist.push_back(I);
 
3510
 
 
3511
  SmallPtrSet<Instruction *, 8> Visited;
 
3512
  while (!Worklist.empty()) {
 
3513
    I = Worklist.pop_back_val();
 
3514
    if (!Visited.insert(I)) continue;
 
3515
 
 
3516
    std::map<SCEVCallbackVH, const SCEV *>::iterator It =
 
3517
      Scalars.find(static_cast<Value *>(I));
 
3518
    if (It != Scalars.end()) {
 
3519
      ValuesAtScopes.erase(It->second);
 
3520
      Scalars.erase(It);
 
3521
      if (PHINode *PN = dyn_cast<PHINode>(I))
 
3522
        ConstantEvolutionLoopExitValue.erase(PN);
 
3523
    }
 
3524
 
 
3525
    PushDefUseChildren(I, Worklist);
 
3526
  }
 
3527
}
 
3528
 
 
3529
/// ComputeBackedgeTakenCount - Compute the number of times the backedge
 
3530
/// of the specified loop will execute.
 
3531
ScalarEvolution::BackedgeTakenInfo
 
3532
ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
 
3533
  SmallVector<BasicBlock *, 8> ExitingBlocks;
 
3534
  L->getExitingBlocks(ExitingBlocks);
 
3535
 
 
3536
  // Examine all exits and pick the most conservative values.
 
3537
  const SCEV *BECount = getCouldNotCompute();
 
3538
  const SCEV *MaxBECount = getCouldNotCompute();
 
3539
  bool CouldNotComputeBECount = false;
 
3540
  for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
 
3541
    BackedgeTakenInfo NewBTI =
 
3542
      ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
 
3543
 
 
3544
    if (NewBTI.Exact == getCouldNotCompute()) {
 
3545
      // We couldn't compute an exact value for this exit, so
 
3546
      // we won't be able to compute an exact value for the loop.
 
3547
      CouldNotComputeBECount = true;
 
3548
      BECount = getCouldNotCompute();
 
3549
    } else if (!CouldNotComputeBECount) {
 
3550
      if (BECount == getCouldNotCompute())
 
3551
        BECount = NewBTI.Exact;
 
3552
      else
 
3553
        BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
 
3554
    }
 
3555
    if (MaxBECount == getCouldNotCompute())
 
3556
      MaxBECount = NewBTI.Max;
 
3557
    else if (NewBTI.Max != getCouldNotCompute())
 
3558
      MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
 
3559
  }
 
3560
 
 
3561
  return BackedgeTakenInfo(BECount, MaxBECount);
 
3562
}
 
3563
 
 
3564
/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
 
3565
/// of the specified loop will execute if it exits via the specified block.
 
3566
ScalarEvolution::BackedgeTakenInfo
 
3567
ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
 
3568
                                                   BasicBlock *ExitingBlock) {
 
3569
 
 
3570
  // Okay, we've chosen an exiting block.  See what condition causes us to
 
3571
  // exit at this block.
 
3572
  //
 
3573
  // FIXME: we should be able to handle switch instructions (with a single exit)
 
3574
  BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
 
3575
  if (ExitBr == 0) return getCouldNotCompute();
 
3576
  assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
 
3577
 
 
3578
  // At this point, we know we have a conditional branch that determines whether
 
3579
  // the loop is exited.  However, we don't know if the branch is executed each
 
3580
  // time through the loop.  If not, then the execution count of the branch will
 
3581
  // not be equal to the trip count of the loop.
 
3582
  //
 
3583
  // Currently we check for this by checking to see if the Exit branch goes to
 
3584
  // the loop header.  If so, we know it will always execute the same number of
 
3585
  // times as the loop.  We also handle the case where the exit block *is* the
 
3586
  // loop header.  This is common for un-rotated loops.
 
3587
  //
 
3588
  // If both of those tests fail, walk up the unique predecessor chain to the
 
3589
  // header, stopping if there is an edge that doesn't exit the loop. If the
 
3590
  // header is reached, the execution count of the branch will be equal to the
 
3591
  // trip count of the loop.
 
3592
  //
 
3593
  //  More extensive analysis could be done to handle more cases here.
 
3594
  //
 
3595
  if (ExitBr->getSuccessor(0) != L->getHeader() &&
 
3596
      ExitBr->getSuccessor(1) != L->getHeader() &&
 
3597
      ExitBr->getParent() != L->getHeader()) {
 
3598
    // The simple checks failed, try climbing the unique predecessor chain
 
3599
    // up to the header.
 
3600
    bool Ok = false;
 
3601
    for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
 
3602
      BasicBlock *Pred = BB->getUniquePredecessor();
 
3603
      if (!Pred)
 
3604
        return getCouldNotCompute();
 
3605
      TerminatorInst *PredTerm = Pred->getTerminator();
 
3606
      for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
 
3607
        BasicBlock *PredSucc = PredTerm->getSuccessor(i);
 
3608
        if (PredSucc == BB)
 
3609
          continue;
 
3610
        // If the predecessor has a successor that isn't BB and isn't
 
3611
        // outside the loop, assume the worst.
 
3612
        if (L->contains(PredSucc))
 
3613
          return getCouldNotCompute();
 
3614
      }
 
3615
      if (Pred == L->getHeader()) {
 
3616
        Ok = true;
 
3617
        break;
 
3618
      }
 
3619
      BB = Pred;
 
3620
    }
 
3621
    if (!Ok)
 
3622
      return getCouldNotCompute();
 
3623
  }
 
3624
 
 
3625
  // Proceed to the next level to examine the exit condition expression.
 
3626
  return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
 
3627
                                               ExitBr->getSuccessor(0),
 
3628
                                               ExitBr->getSuccessor(1));
 
3629
}
 
3630
 
 
3631
/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
 
3632
/// backedge of the specified loop will execute if its exit condition
 
3633
/// were a conditional branch of ExitCond, TBB, and FBB.
 
3634
ScalarEvolution::BackedgeTakenInfo
 
3635
ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
 
3636
                                                       Value *ExitCond,
 
3637
                                                       BasicBlock *TBB,
 
3638
                                                       BasicBlock *FBB) {
 
3639
  // Check if the controlling expression for this loop is an And or Or.
 
3640
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
 
3641
    if (BO->getOpcode() == Instruction::And) {
 
3642
      // Recurse on the operands of the and.
 
3643
      BackedgeTakenInfo BTI0 =
 
3644
        ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
 
3645
      BackedgeTakenInfo BTI1 =
 
3646
        ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
 
3647
      const SCEV *BECount = getCouldNotCompute();
 
3648
      const SCEV *MaxBECount = getCouldNotCompute();
 
3649
      if (L->contains(TBB)) {
 
3650
        // Both conditions must be true for the loop to continue executing.
 
3651
        // Choose the less conservative count.
 
3652
        if (BTI0.Exact == getCouldNotCompute() ||
 
3653
            BTI1.Exact == getCouldNotCompute())
 
3654
          BECount = getCouldNotCompute();
 
3655
        else
 
3656
          BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
 
3657
        if (BTI0.Max == getCouldNotCompute())
 
3658
          MaxBECount = BTI1.Max;
 
3659
        else if (BTI1.Max == getCouldNotCompute())
 
3660
          MaxBECount = BTI0.Max;
 
3661
        else
 
3662
          MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
 
3663
      } else {
 
3664
        // Both conditions must be true for the loop to exit.
 
3665
        assert(L->contains(FBB) && "Loop block has no successor in loop!");
 
3666
        if (BTI0.Exact != getCouldNotCompute() &&
 
3667
            BTI1.Exact != getCouldNotCompute())
 
3668
          BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
 
3669
        if (BTI0.Max != getCouldNotCompute() &&
 
3670
            BTI1.Max != getCouldNotCompute())
 
3671
          MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
 
3672
      }
 
3673
 
 
3674
      return BackedgeTakenInfo(BECount, MaxBECount);
 
3675
    }
 
3676
    if (BO->getOpcode() == Instruction::Or) {
 
3677
      // Recurse on the operands of the or.
 
3678
      BackedgeTakenInfo BTI0 =
 
3679
        ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
 
3680
      BackedgeTakenInfo BTI1 =
 
3681
        ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
 
3682
      const SCEV *BECount = getCouldNotCompute();
 
3683
      const SCEV *MaxBECount = getCouldNotCompute();
 
3684
      if (L->contains(FBB)) {
 
3685
        // Both conditions must be false for the loop to continue executing.
 
3686
        // Choose the less conservative count.
 
3687
        if (BTI0.Exact == getCouldNotCompute() ||
 
3688
            BTI1.Exact == getCouldNotCompute())
 
3689
          BECount = getCouldNotCompute();
 
3690
        else
 
3691
          BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
 
3692
        if (BTI0.Max == getCouldNotCompute())
 
3693
          MaxBECount = BTI1.Max;
 
3694
        else if (BTI1.Max == getCouldNotCompute())
 
3695
          MaxBECount = BTI0.Max;
 
3696
        else
 
3697
          MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
 
3698
      } else {
 
3699
        // Both conditions must be false for the loop to exit.
 
3700
        assert(L->contains(TBB) && "Loop block has no successor in loop!");
 
3701
        if (BTI0.Exact != getCouldNotCompute() &&
 
3702
            BTI1.Exact != getCouldNotCompute())
 
3703
          BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
 
3704
        if (BTI0.Max != getCouldNotCompute() &&
 
3705
            BTI1.Max != getCouldNotCompute())
 
3706
          MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
 
3707
      }
 
3708
 
 
3709
      return BackedgeTakenInfo(BECount, MaxBECount);
 
3710
    }
 
3711
  }
 
3712
 
 
3713
  // With an icmp, it may be feasible to compute an exact backedge-taken count.
 
3714
  // Proceed to the next level to examine the icmp.
 
3715
  if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
 
3716
    return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
 
3717
 
 
3718
  // Check for a constant condition. These are normally stripped out by
 
3719
  // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
 
3720
  // preserve the CFG and is temporarily leaving constant conditions
 
3721
  // in place.
 
3722
  if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
 
3723
    if (L->contains(FBB) == !CI->getZExtValue())
 
3724
      // The backedge is always taken.
 
3725
      return getCouldNotCompute();
 
3726
    else
 
3727
      // The backedge is never taken.
 
3728
      return getIntegerSCEV(0, CI->getType());
 
3729
  }
 
3730
 
 
3731
  // If it's not an integer or pointer comparison then compute it the hard way.
 
3732
  return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
 
3733
}
 
3734
 
 
3735
/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
 
3736
/// backedge of the specified loop will execute if its exit condition
 
3737
/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
 
3738
ScalarEvolution::BackedgeTakenInfo
 
3739
ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
 
3740
                                                           ICmpInst *ExitCond,
 
3741
                                                           BasicBlock *TBB,
 
3742
                                                           BasicBlock *FBB) {
 
3743
 
 
3744
  // If the condition was exit on true, convert the condition to exit on false
 
3745
  ICmpInst::Predicate Cond;
 
3746
  if (!L->contains(FBB))
 
3747
    Cond = ExitCond->getPredicate();
 
3748
  else
 
3749
    Cond = ExitCond->getInversePredicate();
 
3750
 
 
3751
  // Handle common loops like: for (X = "string"; *X; ++X)
 
3752
  if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
 
3753
    if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
 
3754
      BackedgeTakenInfo ItCnt =
 
3755
        ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
 
3756
      if (ItCnt.hasAnyInfo())
 
3757
        return ItCnt;
 
3758
    }
 
3759
 
 
3760
  const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
 
3761
  const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
 
3762
 
 
3763
  // Try to evaluate any dependencies out of the loop.
 
3764
  LHS = getSCEVAtScope(LHS, L);
 
3765
  RHS = getSCEVAtScope(RHS, L);
 
3766
 
 
3767
  // At this point, we would like to compute how many iterations of the
 
3768
  // loop the predicate will return true for these inputs.
 
3769
  if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
 
3770
    // If there is a loop-invariant, force it into the RHS.
 
3771
    std::swap(LHS, RHS);
 
3772
    Cond = ICmpInst::getSwappedPredicate(Cond);
 
3773
  }
 
3774
 
 
3775
  // If we have a comparison of a chrec against a constant, try to use value
 
3776
  // ranges to answer this query.
 
3777
  if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
 
3778
    if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
 
3779
      if (AddRec->getLoop() == L) {
 
3780
        // Form the constant range.
 
3781
        ConstantRange CompRange(
 
3782
            ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
 
3783
 
 
3784
        const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
 
3785
        if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
 
3786
      }
 
3787
 
 
3788
  switch (Cond) {
 
3789
  case ICmpInst::ICMP_NE: {                     // while (X != Y)
 
3790
    // Convert to: while (X-Y != 0)
 
3791
    BackedgeTakenInfo BTI = HowFarToZero(getMinusSCEV(LHS, RHS), L);
 
3792
    if (BTI.hasAnyInfo()) return BTI;
 
3793
    break;
 
3794
  }
 
3795
  case ICmpInst::ICMP_EQ: {                     // while (X == Y)
 
3796
    // Convert to: while (X-Y == 0)
 
3797
    BackedgeTakenInfo BTI = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
 
3798
    if (BTI.hasAnyInfo()) return BTI;
 
3799
    break;
 
3800
  }
 
3801
  case ICmpInst::ICMP_SLT: {
 
3802
    BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
 
3803
    if (BTI.hasAnyInfo()) return BTI;
 
3804
    break;
 
3805
  }
 
3806
  case ICmpInst::ICMP_SGT: {
 
3807
    BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
 
3808
                                             getNotSCEV(RHS), L, true);
 
3809
    if (BTI.hasAnyInfo()) return BTI;
 
3810
    break;
 
3811
  }
 
3812
  case ICmpInst::ICMP_ULT: {
 
3813
    BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
 
3814
    if (BTI.hasAnyInfo()) return BTI;
 
3815
    break;
 
3816
  }
 
3817
  case ICmpInst::ICMP_UGT: {
 
3818
    BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
 
3819
                                             getNotSCEV(RHS), L, false);
 
3820
    if (BTI.hasAnyInfo()) return BTI;
 
3821
    break;
 
3822
  }
 
3823
  default:
 
3824
#if 0
 
3825
    dbgs() << "ComputeBackedgeTakenCount ";
 
3826
    if (ExitCond->getOperand(0)->getType()->isUnsigned())
 
3827
      dbgs() << "[unsigned] ";
 
3828
    dbgs() << *LHS << "   "
 
3829
         << Instruction::getOpcodeName(Instruction::ICmp)
 
3830
         << "   " << *RHS << "\n";
 
3831
#endif
 
3832
    break;
 
3833
  }
 
3834
  return
 
3835
    ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
 
3836
}
 
3837
 
 
3838
static ConstantInt *
 
3839
EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
 
3840
                                ScalarEvolution &SE) {
 
3841
  const SCEV *InVal = SE.getConstant(C);
 
3842
  const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
 
3843
  assert(isa<SCEVConstant>(Val) &&
 
3844
         "Evaluation of SCEV at constant didn't fold correctly?");
 
3845
  return cast<SCEVConstant>(Val)->getValue();
 
3846
}
 
3847
 
 
3848
/// GetAddressedElementFromGlobal - Given a global variable with an initializer
 
3849
/// and a GEP expression (missing the pointer index) indexing into it, return
 
3850
/// the addressed element of the initializer or null if the index expression is
 
3851
/// invalid.
 
3852
static Constant *
 
3853
GetAddressedElementFromGlobal(GlobalVariable *GV,
 
3854
                              const std::vector<ConstantInt*> &Indices) {
 
3855
  Constant *Init = GV->getInitializer();
 
3856
  for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
 
3857
    uint64_t Idx = Indices[i]->getZExtValue();
 
3858
    if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
 
3859
      assert(Idx < CS->getNumOperands() && "Bad struct index!");
 
3860
      Init = cast<Constant>(CS->getOperand(Idx));
 
3861
    } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
 
3862
      if (Idx >= CA->getNumOperands()) return 0;  // Bogus program
 
3863
      Init = cast<Constant>(CA->getOperand(Idx));
 
3864
    } else if (isa<ConstantAggregateZero>(Init)) {
 
3865
      if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
 
3866
        assert(Idx < STy->getNumElements() && "Bad struct index!");
 
3867
        Init = Constant::getNullValue(STy->getElementType(Idx));
 
3868
      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
 
3869
        if (Idx >= ATy->getNumElements()) return 0;  // Bogus program
 
3870
        Init = Constant::getNullValue(ATy->getElementType());
 
3871
      } else {
 
3872
        llvm_unreachable("Unknown constant aggregate type!");
 
3873
      }
 
3874
      return 0;
 
3875
    } else {
 
3876
      return 0; // Unknown initializer type
 
3877
    }
 
3878
  }
 
3879
  return Init;
 
3880
}
 
3881
 
 
3882
/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
 
3883
/// 'icmp op load X, cst', try to see if we can compute the backedge
 
3884
/// execution count.
 
3885
ScalarEvolution::BackedgeTakenInfo
 
3886
ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
 
3887
                                                LoadInst *LI,
 
3888
                                                Constant *RHS,
 
3889
                                                const Loop *L,
 
3890
                                                ICmpInst::Predicate predicate) {
 
3891
  if (LI->isVolatile()) return getCouldNotCompute();
 
3892
 
 
3893
  // Check to see if the loaded pointer is a getelementptr of a global.
 
3894
  // TODO: Use SCEV instead of manually grubbing with GEPs.
 
3895
  GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
 
3896
  if (!GEP) return getCouldNotCompute();
 
3897
 
 
3898
  // Make sure that it is really a constant global we are gepping, with an
 
3899
  // initializer, and make sure the first IDX is really 0.
 
3900
  GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
 
3901
  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
 
3902
      GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
 
3903
      !cast<Constant>(GEP->getOperand(1))->isNullValue())
 
3904
    return getCouldNotCompute();
 
3905
 
 
3906
  // Okay, we allow one non-constant index into the GEP instruction.
 
3907
  Value *VarIdx = 0;
 
3908
  std::vector<ConstantInt*> Indexes;
 
3909
  unsigned VarIdxNum = 0;
 
3910
  for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
 
3911
    if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
 
3912
      Indexes.push_back(CI);
 
3913
    } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
 
3914
      if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
 
3915
      VarIdx = GEP->getOperand(i);
 
3916
      VarIdxNum = i-2;
 
3917
      Indexes.push_back(0);
 
3918
    }
 
3919
 
 
3920
  // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
 
3921
  // Check to see if X is a loop variant variable value now.
 
3922
  const SCEV *Idx = getSCEV(VarIdx);
 
3923
  Idx = getSCEVAtScope(Idx, L);
 
3924
 
 
3925
  // We can only recognize very limited forms of loop index expressions, in
 
3926
  // particular, only affine AddRec's like {C1,+,C2}.
 
3927
  const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
 
3928
  if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
 
3929
      !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
 
3930
      !isa<SCEVConstant>(IdxExpr->getOperand(1)))
 
3931
    return getCouldNotCompute();
 
3932
 
 
3933
  unsigned MaxSteps = MaxBruteForceIterations;
 
3934
  for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
 
3935
    ConstantInt *ItCst = ConstantInt::get(
 
3936
                           cast<IntegerType>(IdxExpr->getType()), IterationNum);
 
3937
    ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
 
3938
 
 
3939
    // Form the GEP offset.
 
3940
    Indexes[VarIdxNum] = Val;
 
3941
 
 
3942
    Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
 
3943
    if (Result == 0) break;  // Cannot compute!
 
3944
 
 
3945
    // Evaluate the condition for this iteration.
 
3946
    Result = ConstantExpr::getICmp(predicate, Result, RHS);
 
3947
    if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
 
3948
    if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
 
3949
#if 0
 
3950
      dbgs() << "\n***\n*** Computed loop count " << *ItCst
 
3951
             << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
 
3952
             << "***\n";
 
3953
#endif
 
3954
      ++NumArrayLenItCounts;
 
3955
      return getConstant(ItCst);   // Found terminating iteration!
 
3956
    }
 
3957
  }
 
3958
  return getCouldNotCompute();
 
3959
}
 
3960
 
 
3961
 
 
3962
/// CanConstantFold - Return true if we can constant fold an instruction of the
 
3963
/// specified type, assuming that all operands were constants.
 
3964
static bool CanConstantFold(const Instruction *I) {
 
3965
  if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
 
3966
      isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
 
3967
    return true;
 
3968
 
 
3969
  if (const CallInst *CI = dyn_cast<CallInst>(I))
 
3970
    if (const Function *F = CI->getCalledFunction())
 
3971
      return canConstantFoldCallTo(F);
 
3972
  return false;
 
3973
}
 
3974
 
 
3975
/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
 
3976
/// in the loop that V is derived from.  We allow arbitrary operations along the
 
3977
/// way, but the operands of an operation must either be constants or a value
 
3978
/// derived from a constant PHI.  If this expression does not fit with these
 
3979
/// constraints, return null.
 
3980
static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
 
3981
  // If this is not an instruction, or if this is an instruction outside of the
 
3982
  // loop, it can't be derived from a loop PHI.
 
3983
  Instruction *I = dyn_cast<Instruction>(V);
 
3984
  if (I == 0 || !L->contains(I)) return 0;
 
3985
 
 
3986
  if (PHINode *PN = dyn_cast<PHINode>(I)) {
 
3987
    if (L->getHeader() == I->getParent())
 
3988
      return PN;
 
3989
    else
 
3990
      // We don't currently keep track of the control flow needed to evaluate
 
3991
      // PHIs, so we cannot handle PHIs inside of loops.
 
3992
      return 0;
 
3993
  }
 
3994
 
 
3995
  // If we won't be able to constant fold this expression even if the operands
 
3996
  // are constants, return early.
 
3997
  if (!CanConstantFold(I)) return 0;
 
3998
 
 
3999
  // Otherwise, we can evaluate this instruction if all of its operands are
 
4000
  // constant or derived from a PHI node themselves.
 
4001
  PHINode *PHI = 0;
 
4002
  for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
 
4003
    if (!(isa<Constant>(I->getOperand(Op)) ||
 
4004
          isa<GlobalValue>(I->getOperand(Op)))) {
 
4005
      PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
 
4006
      if (P == 0) return 0;  // Not evolving from PHI
 
4007
      if (PHI == 0)
 
4008
        PHI = P;
 
4009
      else if (PHI != P)
 
4010
        return 0;  // Evolving from multiple different PHIs.
 
4011
    }
 
4012
 
 
4013
  // This is a expression evolving from a constant PHI!
 
4014
  return PHI;
 
4015
}
 
4016
 
 
4017
/// EvaluateExpression - Given an expression that passes the
 
4018
/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
 
4019
/// in the loop has the value PHIVal.  If we can't fold this expression for some
 
4020
/// reason, return null.
 
4021
static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
 
4022
                                    const TargetData *TD) {
 
4023
  if (isa<PHINode>(V)) return PHIVal;
 
4024
  if (Constant *C = dyn_cast<Constant>(V)) return C;
 
4025
  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
 
4026
  Instruction *I = cast<Instruction>(V);
 
4027
 
 
4028
  std::vector<Constant*> Operands;
 
4029
  Operands.resize(I->getNumOperands());
 
4030
 
 
4031
  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
 
4032
    Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
 
4033
    if (Operands[i] == 0) return 0;
 
4034
  }
 
4035
 
 
4036
  if (const CmpInst *CI = dyn_cast<CmpInst>(I))
 
4037
    return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
 
4038
                                           Operands[1], TD);
 
4039
  return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
 
4040
                                  &Operands[0], Operands.size(), TD);
 
4041
}
 
4042
 
 
4043
/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
 
4044
/// in the header of its containing loop, we know the loop executes a
 
4045
/// constant number of times, and the PHI node is just a recurrence
 
4046
/// involving constants, fold it.
 
4047
Constant *
 
4048
ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
 
4049
                                                   const APInt &BEs,
 
4050
                                                   const Loop *L) {
 
4051
  std::map<PHINode*, Constant*>::iterator I =
 
4052
    ConstantEvolutionLoopExitValue.find(PN);
 
4053
  if (I != ConstantEvolutionLoopExitValue.end())
 
4054
    return I->second;
 
4055
 
 
4056
  if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
 
4057
    return ConstantEvolutionLoopExitValue[PN] = 0;  // Not going to evaluate it.
 
4058
 
 
4059
  Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
 
4060
 
 
4061
  // Since the loop is canonicalized, the PHI node must have two entries.  One
 
4062
  // entry must be a constant (coming in from outside of the loop), and the
 
4063
  // second must be derived from the same PHI.
 
4064
  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
 
4065
  Constant *StartCST =
 
4066
    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
 
4067
  if (StartCST == 0)
 
4068
    return RetVal = 0;  // Must be a constant.
 
4069
 
 
4070
  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
 
4071
  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
 
4072
  if (PN2 != PN)
 
4073
    return RetVal = 0;  // Not derived from same PHI.
 
4074
 
 
4075
  // Execute the loop symbolically to determine the exit value.
 
4076
  if (BEs.getActiveBits() >= 32)
 
4077
    return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
 
4078
 
 
4079
  unsigned NumIterations = BEs.getZExtValue(); // must be in range
 
4080
  unsigned IterationNum = 0;
 
4081
  for (Constant *PHIVal = StartCST; ; ++IterationNum) {
 
4082
    if (IterationNum == NumIterations)
 
4083
      return RetVal = PHIVal;  // Got exit value!
 
4084
 
 
4085
    // Compute the value of the PHI node for the next iteration.
 
4086
    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
 
4087
    if (NextPHI == PHIVal)
 
4088
      return RetVal = NextPHI;  // Stopped evolving!
 
4089
    if (NextPHI == 0)
 
4090
      return 0;        // Couldn't evaluate!
 
4091
    PHIVal = NextPHI;
 
4092
  }
 
4093
}
 
4094
 
 
4095
/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
 
4096
/// constant number of times (the condition evolves only from constants),
 
4097
/// try to evaluate a few iterations of the loop until we get the exit
 
4098
/// condition gets a value of ExitWhen (true or false).  If we cannot
 
4099
/// evaluate the trip count of the loop, return getCouldNotCompute().
 
4100
const SCEV *
 
4101
ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
 
4102
                                                       Value *Cond,
 
4103
                                                       bool ExitWhen) {
 
4104
  PHINode *PN = getConstantEvolvingPHI(Cond, L);
 
4105
  if (PN == 0) return getCouldNotCompute();
 
4106
 
 
4107
  // Since the loop is canonicalized, the PHI node must have two entries.  One
 
4108
  // entry must be a constant (coming in from outside of the loop), and the
 
4109
  // second must be derived from the same PHI.
 
4110
  bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
 
4111
  Constant *StartCST =
 
4112
    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
 
4113
  if (StartCST == 0) return getCouldNotCompute();  // Must be a constant.
 
4114
 
 
4115
  Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
 
4116
  PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
 
4117
  if (PN2 != PN) return getCouldNotCompute();  // Not derived from same PHI.
 
4118
 
 
4119
  // Okay, we find a PHI node that defines the trip count of this loop.  Execute
 
4120
  // the loop symbolically to determine when the condition gets a value of
 
4121
  // "ExitWhen".
 
4122
  unsigned IterationNum = 0;
 
4123
  unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
 
4124
  for (Constant *PHIVal = StartCST;
 
4125
       IterationNum != MaxIterations; ++IterationNum) {
 
4126
    ConstantInt *CondVal =
 
4127
      dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
 
4128
 
 
4129
    // Couldn't symbolically evaluate.
 
4130
    if (!CondVal) return getCouldNotCompute();
 
4131
 
 
4132
    if (CondVal->getValue() == uint64_t(ExitWhen)) {
 
4133
      ++NumBruteForceTripCountsComputed;
 
4134
      return getConstant(Type::getInt32Ty(getContext()), IterationNum);
 
4135
    }
 
4136
 
 
4137
    // Compute the value of the PHI node for the next iteration.
 
4138
    Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
 
4139
    if (NextPHI == 0 || NextPHI == PHIVal)
 
4140
      return getCouldNotCompute();// Couldn't evaluate or not making progress...
 
4141
    PHIVal = NextPHI;
 
4142
  }
 
4143
 
 
4144
  // Too many iterations were needed to evaluate.
 
4145
  return getCouldNotCompute();
 
4146
}
 
4147
 
 
4148
/// getSCEVAtScope - Return a SCEV expression for the specified value
 
4149
/// at the specified scope in the program.  The L value specifies a loop
 
4150
/// nest to evaluate the expression at, where null is the top-level or a
 
4151
/// specified loop is immediately inside of the loop.
 
4152
///
 
4153
/// This method can be used to compute the exit value for a variable defined
 
4154
/// in a loop by querying what the value will hold in the parent loop.
 
4155
///
 
4156
/// In the case that a relevant loop exit value cannot be computed, the
 
4157
/// original value V is returned.
 
4158
const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
 
4159
  // Check to see if we've folded this expression at this loop before.
 
4160
  std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
 
4161
  std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
 
4162
    Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
 
4163
  if (!Pair.second)
 
4164
    return Pair.first->second ? Pair.first->second : V;
 
4165
 
 
4166
  // Otherwise compute it.
 
4167
  const SCEV *C = computeSCEVAtScope(V, L);
 
4168
  ValuesAtScopes[V][L] = C;
 
4169
  return C;
 
4170
}
 
4171
 
 
4172
const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
 
4173
  if (isa<SCEVConstant>(V)) return V;
 
4174
 
 
4175
  // If this instruction is evolved from a constant-evolving PHI, compute the
 
4176
  // exit value from the loop without using SCEVs.
 
4177
  if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
 
4178
    if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
 
4179
      const Loop *LI = (*this->LI)[I->getParent()];
 
4180
      if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
 
4181
        if (PHINode *PN = dyn_cast<PHINode>(I))
 
4182
          if (PN->getParent() == LI->getHeader()) {
 
4183
            // Okay, there is no closed form solution for the PHI node.  Check
 
4184
            // to see if the loop that contains it has a known backedge-taken
 
4185
            // count.  If so, we may be able to force computation of the exit
 
4186
            // value.
 
4187
            const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
 
4188
            if (const SCEVConstant *BTCC =
 
4189
                  dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
 
4190
              // Okay, we know how many times the containing loop executes.  If
 
4191
              // this is a constant evolving PHI node, get the final value at
 
4192
              // the specified iteration number.
 
4193
              Constant *RV = getConstantEvolutionLoopExitValue(PN,
 
4194
                                                   BTCC->getValue()->getValue(),
 
4195
                                                               LI);
 
4196
              if (RV) return getSCEV(RV);
 
4197
            }
 
4198
          }
 
4199
 
 
4200
      // Okay, this is an expression that we cannot symbolically evaluate
 
4201
      // into a SCEV.  Check to see if it's possible to symbolically evaluate
 
4202
      // the arguments into constants, and if so, try to constant propagate the
 
4203
      // result.  This is particularly useful for computing loop exit values.
 
4204
      if (CanConstantFold(I)) {
 
4205
        std::vector<Constant*> Operands;
 
4206
        Operands.reserve(I->getNumOperands());
 
4207
        for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
 
4208
          Value *Op = I->getOperand(i);
 
4209
          if (Constant *C = dyn_cast<Constant>(Op)) {
 
4210
            Operands.push_back(C);
 
4211
          } else {
 
4212
            // If any of the operands is non-constant and if they are
 
4213
            // non-integer and non-pointer, don't even try to analyze them
 
4214
            // with scev techniques.
 
4215
            if (!isSCEVable(Op->getType()))
 
4216
              return V;
 
4217
 
 
4218
            const SCEV *OpV = getSCEVAtScope(Op, L);
 
4219
            if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
 
4220
              Constant *C = SC->getValue();
 
4221
              if (C->getType() != Op->getType())
 
4222
                C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
 
4223
                                                                  Op->getType(),
 
4224
                                                                  false),
 
4225
                                          C, Op->getType());
 
4226
              Operands.push_back(C);
 
4227
            } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
 
4228
              if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
 
4229
                if (C->getType() != Op->getType())
 
4230
                  C =
 
4231
                    ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
 
4232
                                                                  Op->getType(),
 
4233
                                                                  false),
 
4234
                                          C, Op->getType());
 
4235
                Operands.push_back(C);
 
4236
              } else
 
4237
                return V;
 
4238
            } else {
 
4239
              return V;
 
4240
            }
 
4241
          }
 
4242
        }
 
4243
 
 
4244
        Constant *C = 0;
 
4245
        if (const CmpInst *CI = dyn_cast<CmpInst>(I))
 
4246
          C = ConstantFoldCompareInstOperands(CI->getPredicate(),
 
4247
                                              Operands[0], Operands[1], TD);
 
4248
        else
 
4249
          C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
 
4250
                                       &Operands[0], Operands.size(), TD);
 
4251
        if (C)
 
4252
          return getSCEV(C);
 
4253
      }
 
4254
    }
 
4255
 
 
4256
    // This is some other type of SCEVUnknown, just return it.
 
4257
    return V;
 
4258
  }
 
4259
 
 
4260
  if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
 
4261
    // Avoid performing the look-up in the common case where the specified
 
4262
    // expression has no loop-variant portions.
 
4263
    for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
 
4264
      const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
 
4265
      if (OpAtScope != Comm->getOperand(i)) {
 
4266
        // Okay, at least one of these operands is loop variant but might be
 
4267
        // foldable.  Build a new instance of the folded commutative expression.
 
4268
        SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
 
4269
                                            Comm->op_begin()+i);
 
4270
        NewOps.push_back(OpAtScope);
 
4271
 
 
4272
        for (++i; i != e; ++i) {
 
4273
          OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
 
4274
          NewOps.push_back(OpAtScope);
 
4275
        }
 
4276
        if (isa<SCEVAddExpr>(Comm))
 
4277
          return getAddExpr(NewOps);
 
4278
        if (isa<SCEVMulExpr>(Comm))
 
4279
          return getMulExpr(NewOps);
 
4280
        if (isa<SCEVSMaxExpr>(Comm))
 
4281
          return getSMaxExpr(NewOps);
 
4282
        if (isa<SCEVUMaxExpr>(Comm))
 
4283
          return getUMaxExpr(NewOps);
 
4284
        llvm_unreachable("Unknown commutative SCEV type!");
 
4285
      }
 
4286
    }
 
4287
    // If we got here, all operands are loop invariant.
 
4288
    return Comm;
 
4289
  }
 
4290
 
 
4291
  if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
 
4292
    const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
 
4293
    const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
 
4294
    if (LHS == Div->getLHS() && RHS == Div->getRHS())
 
4295
      return Div;   // must be loop invariant
 
4296
    return getUDivExpr(LHS, RHS);
 
4297
  }
 
4298
 
 
4299
  // If this is a loop recurrence for a loop that does not contain L, then we
 
4300
  // are dealing with the final value computed by the loop.
 
4301
  if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
 
4302
    if (!L || !AddRec->getLoop()->contains(L)) {
 
4303
      // To evaluate this recurrence, we need to know how many times the AddRec
 
4304
      // loop iterates.  Compute this now.
 
4305
      const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
 
4306
      if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
 
4307
 
 
4308
      // Then, evaluate the AddRec.
 
4309
      return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
 
4310
    }
 
4311
    return AddRec;
 
4312
  }
 
4313
 
 
4314
  if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
 
4315
    const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
 
4316
    if (Op == Cast->getOperand())
 
4317
      return Cast;  // must be loop invariant
 
4318
    return getZeroExtendExpr(Op, Cast->getType());
 
4319
  }
 
4320
 
 
4321
  if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
 
4322
    const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
 
4323
    if (Op == Cast->getOperand())
 
4324
      return Cast;  // must be loop invariant
 
4325
    return getSignExtendExpr(Op, Cast->getType());
 
4326
  }
 
4327
 
 
4328
  if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
 
4329
    const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
 
4330
    if (Op == Cast->getOperand())
 
4331
      return Cast;  // must be loop invariant
 
4332
    return getTruncateExpr(Op, Cast->getType());
 
4333
  }
 
4334
 
 
4335
  llvm_unreachable("Unknown SCEV type!");
 
4336
  return 0;
 
4337
}
 
4338
 
 
4339
/// getSCEVAtScope - This is a convenience function which does
 
4340
/// getSCEVAtScope(getSCEV(V), L).
 
4341
const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
 
4342
  return getSCEVAtScope(getSCEV(V), L);
 
4343
}
 
4344
 
 
4345
/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
 
4346
/// following equation:
 
4347
///
 
4348
///     A * X = B (mod N)
 
4349
///
 
4350
/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
 
4351
/// A and B isn't important.
 
4352
///
 
4353
/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
 
4354
static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
 
4355
                                               ScalarEvolution &SE) {
 
4356
  uint32_t BW = A.getBitWidth();
 
4357
  assert(BW == B.getBitWidth() && "Bit widths must be the same.");
 
4358
  assert(A != 0 && "A must be non-zero.");
 
4359
 
 
4360
  // 1. D = gcd(A, N)
 
4361
  //
 
4362
  // The gcd of A and N may have only one prime factor: 2. The number of
 
4363
  // trailing zeros in A is its multiplicity
 
4364
  uint32_t Mult2 = A.countTrailingZeros();
 
4365
  // D = 2^Mult2
 
4366
 
 
4367
  // 2. Check if B is divisible by D.
 
4368
  //
 
4369
  // B is divisible by D if and only if the multiplicity of prime factor 2 for B
 
4370
  // is not less than multiplicity of this prime factor for D.
 
4371
  if (B.countTrailingZeros() < Mult2)
 
4372
    return SE.getCouldNotCompute();
 
4373
 
 
4374
  // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
 
4375
  // modulo (N / D).
 
4376
  //
 
4377
  // (N / D) may need BW+1 bits in its representation.  Hence, we'll use this
 
4378
  // bit width during computations.
 
4379
  APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
 
4380
  APInt Mod(BW + 1, 0);
 
4381
  Mod.set(BW - Mult2);  // Mod = N / D
 
4382
  APInt I = AD.multiplicativeInverse(Mod);
 
4383
 
 
4384
  // 4. Compute the minimum unsigned root of the equation:
 
4385
  // I * (B / D) mod (N / D)
 
4386
  APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
 
4387
 
 
4388
  // The result is guaranteed to be less than 2^BW so we may truncate it to BW
 
4389
  // bits.
 
4390
  return SE.getConstant(Result.trunc(BW));
 
4391
}
 
4392
 
 
4393
/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
 
4394
/// given quadratic chrec {L,+,M,+,N}.  This returns either the two roots (which
 
4395
/// might be the same) or two SCEVCouldNotCompute objects.
 
4396
///
 
4397
static std::pair<const SCEV *,const SCEV *>
 
4398
SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
 
4399
  assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
 
4400
  const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
 
4401
  const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
 
4402
  const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
 
4403
 
 
4404
  // We currently can only solve this if the coefficients are constants.
 
4405
  if (!LC || !MC || !NC) {
 
4406
    const SCEV *CNC = SE.getCouldNotCompute();
 
4407
    return std::make_pair(CNC, CNC);
 
4408
  }
 
4409
 
 
4410
  uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
 
4411
  const APInt &L = LC->getValue()->getValue();
 
4412
  const APInt &M = MC->getValue()->getValue();
 
4413
  const APInt &N = NC->getValue()->getValue();
 
4414
  APInt Two(BitWidth, 2);
 
4415
  APInt Four(BitWidth, 4);
 
4416
 
 
4417
  {
 
4418
    using namespace APIntOps;
 
4419
    const APInt& C = L;
 
4420
    // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
 
4421
    // The B coefficient is M-N/2
 
4422
    APInt B(M);
 
4423
    B -= sdiv(N,Two);
 
4424
 
 
4425
    // The A coefficient is N/2
 
4426
    APInt A(N.sdiv(Two));
 
4427
 
 
4428
    // Compute the B^2-4ac term.
 
4429
    APInt SqrtTerm(B);
 
4430
    SqrtTerm *= B;
 
4431
    SqrtTerm -= Four * (A * C);
 
4432
 
 
4433
    // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
 
4434
    // integer value or else APInt::sqrt() will assert.
 
4435
    APInt SqrtVal(SqrtTerm.sqrt());
 
4436
 
 
4437
    // Compute the two solutions for the quadratic formula.
 
4438
    // The divisions must be performed as signed divisions.
 
4439
    APInt NegB(-B);
 
4440
    APInt TwoA( A << 1 );
 
4441
    if (TwoA.isMinValue()) {
 
4442
      const SCEV *CNC = SE.getCouldNotCompute();
 
4443
      return std::make_pair(CNC, CNC);
 
4444
    }
 
4445
 
 
4446
    LLVMContext &Context = SE.getContext();
 
4447
 
 
4448
    ConstantInt *Solution1 =
 
4449
      ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
 
4450
    ConstantInt *Solution2 =
 
4451
      ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
 
4452
 
 
4453
    return std::make_pair(SE.getConstant(Solution1),
 
4454
                          SE.getConstant(Solution2));
 
4455
    } // end APIntOps namespace
 
4456
}
 
4457
 
 
4458
/// HowFarToZero - Return the number of times a backedge comparing the specified
 
4459
/// value to zero will execute.  If not computable, return CouldNotCompute.
 
4460
ScalarEvolution::BackedgeTakenInfo
 
4461
ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
 
4462
  // If the value is a constant
 
4463
  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
 
4464
    // If the value is already zero, the branch will execute zero times.
 
4465
    if (C->getValue()->isZero()) return C;
 
4466
    return getCouldNotCompute();  // Otherwise it will loop infinitely.
 
4467
  }
 
4468
 
 
4469
  const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
 
4470
  if (!AddRec || AddRec->getLoop() != L)
 
4471
    return getCouldNotCompute();
 
4472
 
 
4473
  if (AddRec->isAffine()) {
 
4474
    // If this is an affine expression, the execution count of this branch is
 
4475
    // the minimum unsigned root of the following equation:
 
4476
    //
 
4477
    //     Start + Step*N = 0 (mod 2^BW)
 
4478
    //
 
4479
    // equivalent to:
 
4480
    //
 
4481
    //             Step*N = -Start (mod 2^BW)
 
4482
    //
 
4483
    // where BW is the common bit width of Start and Step.
 
4484
 
 
4485
    // Get the initial value for the loop.
 
4486
    const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
 
4487
                                       L->getParentLoop());
 
4488
    const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
 
4489
                                      L->getParentLoop());
 
4490
 
 
4491
    if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
 
4492
      // For now we handle only constant steps.
 
4493
 
 
4494
      // First, handle unitary steps.
 
4495
      if (StepC->getValue()->equalsInt(1))      // 1*N = -Start (mod 2^BW), so:
 
4496
        return getNegativeSCEV(Start);          //   N = -Start (as unsigned)
 
4497
      if (StepC->getValue()->isAllOnesValue())  // -1*N = -Start (mod 2^BW), so:
 
4498
        return Start;                           //    N = Start (as unsigned)
 
4499
 
 
4500
      // Then, try to solve the above equation provided that Start is constant.
 
4501
      if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
 
4502
        return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
 
4503
                                            -StartC->getValue()->getValue(),
 
4504
                                            *this);
 
4505
    }
 
4506
  } else if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
 
4507
    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
 
4508
    // the quadratic equation to solve it.
 
4509
    std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
 
4510
                                                                    *this);
 
4511
    const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
 
4512
    const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
 
4513
    if (R1) {
 
4514
#if 0
 
4515
      dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
 
4516
             << "  sol#2: " << *R2 << "\n";
 
4517
#endif
 
4518
      // Pick the smallest positive root value.
 
4519
      if (ConstantInt *CB =
 
4520
          dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
 
4521
                                   R1->getValue(), R2->getValue()))) {
 
4522
        if (CB->getZExtValue() == false)
 
4523
          std::swap(R1, R2);   // R1 is the minimum root now.
 
4524
 
 
4525
        // We can only use this value if the chrec ends up with an exact zero
 
4526
        // value at this index.  When solving for "X*X != 5", for example, we
 
4527
        // should not accept a root of 2.
 
4528
        const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
 
4529
        if (Val->isZero())
 
4530
          return R1;  // We found a quadratic root!
 
4531
      }
 
4532
    }
 
4533
  }
 
4534
 
 
4535
  return getCouldNotCompute();
 
4536
}
 
4537
 
 
4538
/// HowFarToNonZero - Return the number of times a backedge checking the
 
4539
/// specified value for nonzero will execute.  If not computable, return
 
4540
/// CouldNotCompute
 
4541
ScalarEvolution::BackedgeTakenInfo
 
4542
ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
 
4543
  // Loops that look like: while (X == 0) are very strange indeed.  We don't
 
4544
  // handle them yet except for the trivial case.  This could be expanded in the
 
4545
  // future as needed.
 
4546
 
 
4547
  // If the value is a constant, check to see if it is known to be non-zero
 
4548
  // already.  If so, the backedge will execute zero times.
 
4549
  if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
 
4550
    if (!C->getValue()->isNullValue())
 
4551
      return getIntegerSCEV(0, C->getType());
 
4552
    return getCouldNotCompute();  // Otherwise it will loop infinitely.
 
4553
  }
 
4554
 
 
4555
  // We could implement others, but I really doubt anyone writes loops like
 
4556
  // this, and if they did, they would already be constant folded.
 
4557
  return getCouldNotCompute();
 
4558
}
 
4559
 
 
4560
/// getLoopPredecessor - If the given loop's header has exactly one unique
 
4561
/// predecessor outside the loop, return it. Otherwise return null.
 
4562
///
 
4563
BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
 
4564
  BasicBlock *Header = L->getHeader();
 
4565
  BasicBlock *Pred = 0;
 
4566
  for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
 
4567
       PI != E; ++PI)
 
4568
    if (!L->contains(*PI)) {
 
4569
      if (Pred && Pred != *PI) return 0; // Multiple predecessors.
 
4570
      Pred = *PI;
 
4571
    }
 
4572
  return Pred;
 
4573
}
 
4574
 
 
4575
/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
 
4576
/// (which may not be an immediate predecessor) which has exactly one
 
4577
/// successor from which BB is reachable, or null if no such block is
 
4578
/// found.
 
4579
///
 
4580
BasicBlock *
 
4581
ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
 
4582
  // If the block has a unique predecessor, then there is no path from the
 
4583
  // predecessor to the block that does not go through the direct edge
 
4584
  // from the predecessor to the block.
 
4585
  if (BasicBlock *Pred = BB->getSinglePredecessor())
 
4586
    return Pred;
 
4587
 
 
4588
  // A loop's header is defined to be a block that dominates the loop.
 
4589
  // If the header has a unique predecessor outside the loop, it must be
 
4590
  // a block that has exactly one successor that can reach the loop.
 
4591
  if (Loop *L = LI->getLoopFor(BB))
 
4592
    return getLoopPredecessor(L);
 
4593
 
 
4594
  return 0;
 
4595
}
 
4596
 
 
4597
/// HasSameValue - SCEV structural equivalence is usually sufficient for
 
4598
/// testing whether two expressions are equal, however for the purposes of
 
4599
/// looking for a condition guarding a loop, it can be useful to be a little
 
4600
/// more general, since a front-end may have replicated the controlling
 
4601
/// expression.
 
4602
///
 
4603
static bool HasSameValue(const SCEV *A, const SCEV *B) {
 
4604
  // Quick check to see if they are the same SCEV.
 
4605
  if (A == B) return true;
 
4606
 
 
4607
  // Otherwise, if they're both SCEVUnknown, it's possible that they hold
 
4608
  // two different instructions with the same value. Check for this case.
 
4609
  if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
 
4610
    if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
 
4611
      if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
 
4612
        if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
 
4613
          if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
 
4614
            return true;
 
4615
 
 
4616
  // Otherwise assume they may have a different value.
 
4617
  return false;
 
4618
}
 
4619
 
 
4620
bool ScalarEvolution::isKnownNegative(const SCEV *S) {
 
4621
  return getSignedRange(S).getSignedMax().isNegative();
 
4622
}
 
4623
 
 
4624
bool ScalarEvolution::isKnownPositive(const SCEV *S) {
 
4625
  return getSignedRange(S).getSignedMin().isStrictlyPositive();
 
4626
}
 
4627
 
 
4628
bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
 
4629
  return !getSignedRange(S).getSignedMin().isNegative();
 
4630
}
 
4631
 
 
4632
bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
 
4633
  return !getSignedRange(S).getSignedMax().isStrictlyPositive();
 
4634
}
 
4635
 
 
4636
bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
 
4637
  return isKnownNegative(S) || isKnownPositive(S);
 
4638
}
 
4639
 
 
4640
bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
 
4641
                                       const SCEV *LHS, const SCEV *RHS) {
 
4642
 
 
4643
  if (HasSameValue(LHS, RHS))
 
4644
    return ICmpInst::isTrueWhenEqual(Pred);
 
4645
 
 
4646
  switch (Pred) {
 
4647
  default:
 
4648
    llvm_unreachable("Unexpected ICmpInst::Predicate value!");
 
4649
    break;
 
4650
  case ICmpInst::ICMP_SGT:
 
4651
    Pred = ICmpInst::ICMP_SLT;
 
4652
    std::swap(LHS, RHS);
 
4653
  case ICmpInst::ICMP_SLT: {
 
4654
    ConstantRange LHSRange = getSignedRange(LHS);
 
4655
    ConstantRange RHSRange = getSignedRange(RHS);
 
4656
    if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
 
4657
      return true;
 
4658
    if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
 
4659
      return false;
 
4660
    break;
 
4661
  }
 
4662
  case ICmpInst::ICMP_SGE:
 
4663
    Pred = ICmpInst::ICMP_SLE;
 
4664
    std::swap(LHS, RHS);
 
4665
  case ICmpInst::ICMP_SLE: {
 
4666
    ConstantRange LHSRange = getSignedRange(LHS);
 
4667
    ConstantRange RHSRange = getSignedRange(RHS);
 
4668
    if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
 
4669
      return true;
 
4670
    if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
 
4671
      return false;
 
4672
    break;
 
4673
  }
 
4674
  case ICmpInst::ICMP_UGT:
 
4675
    Pred = ICmpInst::ICMP_ULT;
 
4676
    std::swap(LHS, RHS);
 
4677
  case ICmpInst::ICMP_ULT: {
 
4678
    ConstantRange LHSRange = getUnsignedRange(LHS);
 
4679
    ConstantRange RHSRange = getUnsignedRange(RHS);
 
4680
    if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
 
4681
      return true;
 
4682
    if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
 
4683
      return false;
 
4684
    break;
 
4685
  }
 
4686
  case ICmpInst::ICMP_UGE:
 
4687
    Pred = ICmpInst::ICMP_ULE;
 
4688
    std::swap(LHS, RHS);
 
4689
  case ICmpInst::ICMP_ULE: {
 
4690
    ConstantRange LHSRange = getUnsignedRange(LHS);
 
4691
    ConstantRange RHSRange = getUnsignedRange(RHS);
 
4692
    if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
 
4693
      return true;
 
4694
    if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
 
4695
      return false;
 
4696
    break;
 
4697
  }
 
4698
  case ICmpInst::ICMP_NE: {
 
4699
    if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
 
4700
      return true;
 
4701
    if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
 
4702
      return true;
 
4703
 
 
4704
    const SCEV *Diff = getMinusSCEV(LHS, RHS);
 
4705
    if (isKnownNonZero(Diff))
 
4706
      return true;
 
4707
    break;
 
4708
  }
 
4709
  case ICmpInst::ICMP_EQ:
 
4710
    // The check at the top of the function catches the case where
 
4711
    // the values are known to be equal.
 
4712
    break;
 
4713
  }
 
4714
  return false;
 
4715
}
 
4716
 
 
4717
/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
 
4718
/// protected by a conditional between LHS and RHS.  This is used to
 
4719
/// to eliminate casts.
 
4720
bool
 
4721
ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
 
4722
                                             ICmpInst::Predicate Pred,
 
4723
                                             const SCEV *LHS, const SCEV *RHS) {
 
4724
  // Interpret a null as meaning no loop, where there is obviously no guard
 
4725
  // (interprocedural conditions notwithstanding).
 
4726
  if (!L) return true;
 
4727
 
 
4728
  BasicBlock *Latch = L->getLoopLatch();
 
4729
  if (!Latch)
 
4730
    return false;
 
4731
 
 
4732
  BranchInst *LoopContinuePredicate =
 
4733
    dyn_cast<BranchInst>(Latch->getTerminator());
 
4734
  if (!LoopContinuePredicate ||
 
4735
      LoopContinuePredicate->isUnconditional())
 
4736
    return false;
 
4737
 
 
4738
  return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
 
4739
                       LoopContinuePredicate->getSuccessor(0) != L->getHeader());
 
4740
}
 
4741
 
 
4742
/// isLoopGuardedByCond - Test whether entry to the loop is protected
 
4743
/// by a conditional between LHS and RHS.  This is used to help avoid max
 
4744
/// expressions in loop trip counts, and to eliminate casts.
 
4745
bool
 
4746
ScalarEvolution::isLoopGuardedByCond(const Loop *L,
 
4747
                                     ICmpInst::Predicate Pred,
 
4748
                                     const SCEV *LHS, const SCEV *RHS) {
 
4749
  // Interpret a null as meaning no loop, where there is obviously no guard
 
4750
  // (interprocedural conditions notwithstanding).
 
4751
  if (!L) return false;
 
4752
 
 
4753
  BasicBlock *Predecessor = getLoopPredecessor(L);
 
4754
  BasicBlock *PredecessorDest = L->getHeader();
 
4755
 
 
4756
  // Starting at the loop predecessor, climb up the predecessor chain, as long
 
4757
  // as there are predecessors that can be found that have unique successors
 
4758
  // leading to the original header.
 
4759
  for (; Predecessor;
 
4760
       PredecessorDest = Predecessor,
 
4761
       Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
 
4762
 
 
4763
    BranchInst *LoopEntryPredicate =
 
4764
      dyn_cast<BranchInst>(Predecessor->getTerminator());
 
4765
    if (!LoopEntryPredicate ||
 
4766
        LoopEntryPredicate->isUnconditional())
 
4767
      continue;
 
4768
 
 
4769
    if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
 
4770
                      LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
 
4771
      return true;
 
4772
  }
 
4773
 
 
4774
  return false;
 
4775
}
 
4776
 
 
4777
/// isImpliedCond - Test whether the condition described by Pred, LHS,
 
4778
/// and RHS is true whenever the given Cond value evaluates to true.
 
4779
bool ScalarEvolution::isImpliedCond(Value *CondValue,
 
4780
                                    ICmpInst::Predicate Pred,
 
4781
                                    const SCEV *LHS, const SCEV *RHS,
 
4782
                                    bool Inverse) {
 
4783
  // Recursively handle And and Or conditions.
 
4784
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
 
4785
    if (BO->getOpcode() == Instruction::And) {
 
4786
      if (!Inverse)
 
4787
        return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
 
4788
               isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
 
4789
    } else if (BO->getOpcode() == Instruction::Or) {
 
4790
      if (Inverse)
 
4791
        return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
 
4792
               isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
 
4793
    }
 
4794
  }
 
4795
 
 
4796
  ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
 
4797
  if (!ICI) return false;
 
4798
 
 
4799
  // Bail if the ICmp's operands' types are wider than the needed type
 
4800
  // before attempting to call getSCEV on them. This avoids infinite
 
4801
  // recursion, since the analysis of widening casts can require loop
 
4802
  // exit condition information for overflow checking, which would
 
4803
  // lead back here.
 
4804
  if (getTypeSizeInBits(LHS->getType()) <
 
4805
      getTypeSizeInBits(ICI->getOperand(0)->getType()))
 
4806
    return false;
 
4807
 
 
4808
  // Now that we found a conditional branch that dominates the loop, check to
 
4809
  // see if it is the comparison we are looking for.
 
4810
  ICmpInst::Predicate FoundPred;
 
4811
  if (Inverse)
 
4812
    FoundPred = ICI->getInversePredicate();
 
4813
  else
 
4814
    FoundPred = ICI->getPredicate();
 
4815
 
 
4816
  const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
 
4817
  const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
 
4818
 
 
4819
  // Balance the types. The case where FoundLHS' type is wider than
 
4820
  // LHS' type is checked for above.
 
4821
  if (getTypeSizeInBits(LHS->getType()) >
 
4822
      getTypeSizeInBits(FoundLHS->getType())) {
 
4823
    if (CmpInst::isSigned(Pred)) {
 
4824
      FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
 
4825
      FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
 
4826
    } else {
 
4827
      FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
 
4828
      FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
 
4829
    }
 
4830
  }
 
4831
 
 
4832
  // Canonicalize the query to match the way instcombine will have
 
4833
  // canonicalized the comparison.
 
4834
  // First, put a constant operand on the right.
 
4835
  if (isa<SCEVConstant>(LHS)) {
 
4836
    std::swap(LHS, RHS);
 
4837
    Pred = ICmpInst::getSwappedPredicate(Pred);
 
4838
  }
 
4839
  // Then, canonicalize comparisons with boundary cases.
 
4840
  if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
 
4841
    const APInt &RA = RC->getValue()->getValue();
 
4842
    switch (Pred) {
 
4843
    default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
 
4844
    case ICmpInst::ICMP_EQ:
 
4845
    case ICmpInst::ICMP_NE:
 
4846
      break;
 
4847
    case ICmpInst::ICMP_UGE:
 
4848
      if ((RA - 1).isMinValue()) {
 
4849
        Pred = ICmpInst::ICMP_NE;
 
4850
        RHS = getConstant(RA - 1);
 
4851
        break;
 
4852
      }
 
4853
      if (RA.isMaxValue()) {
 
4854
        Pred = ICmpInst::ICMP_EQ;
 
4855
        break;
 
4856
      }
 
4857
      if (RA.isMinValue()) return true;
 
4858
      break;
 
4859
    case ICmpInst::ICMP_ULE:
 
4860
      if ((RA + 1).isMaxValue()) {
 
4861
        Pred = ICmpInst::ICMP_NE;
 
4862
        RHS = getConstant(RA + 1);
 
4863
        break;
 
4864
      }
 
4865
      if (RA.isMinValue()) {
 
4866
        Pred = ICmpInst::ICMP_EQ;
 
4867
        break;
 
4868
      }
 
4869
      if (RA.isMaxValue()) return true;
 
4870
      break;
 
4871
    case ICmpInst::ICMP_SGE:
 
4872
      if ((RA - 1).isMinSignedValue()) {
 
4873
        Pred = ICmpInst::ICMP_NE;
 
4874
        RHS = getConstant(RA - 1);
 
4875
        break;
 
4876
      }
 
4877
      if (RA.isMaxSignedValue()) {
 
4878
        Pred = ICmpInst::ICMP_EQ;
 
4879
        break;
 
4880
      }
 
4881
      if (RA.isMinSignedValue()) return true;
 
4882
      break;
 
4883
    case ICmpInst::ICMP_SLE:
 
4884
      if ((RA + 1).isMaxSignedValue()) {
 
4885
        Pred = ICmpInst::ICMP_NE;
 
4886
        RHS = getConstant(RA + 1);
 
4887
        break;
 
4888
      }
 
4889
      if (RA.isMinSignedValue()) {
 
4890
        Pred = ICmpInst::ICMP_EQ;
 
4891
        break;
 
4892
      }
 
4893
      if (RA.isMaxSignedValue()) return true;
 
4894
      break;
 
4895
    case ICmpInst::ICMP_UGT:
 
4896
      if (RA.isMinValue()) {
 
4897
        Pred = ICmpInst::ICMP_NE;
 
4898
        break;
 
4899
      }
 
4900
      if ((RA + 1).isMaxValue()) {
 
4901
        Pred = ICmpInst::ICMP_EQ;
 
4902
        RHS = getConstant(RA + 1);
 
4903
        break;
 
4904
      }
 
4905
      if (RA.isMaxValue()) return false;
 
4906
      break;
 
4907
    case ICmpInst::ICMP_ULT:
 
4908
      if (RA.isMaxValue()) {
 
4909
        Pred = ICmpInst::ICMP_NE;
 
4910
        break;
 
4911
      }
 
4912
      if ((RA - 1).isMinValue()) {
 
4913
        Pred = ICmpInst::ICMP_EQ;
 
4914
        RHS = getConstant(RA - 1);
 
4915
        break;
 
4916
      }
 
4917
      if (RA.isMinValue()) return false;
 
4918
      break;
 
4919
    case ICmpInst::ICMP_SGT:
 
4920
      if (RA.isMinSignedValue()) {
 
4921
        Pred = ICmpInst::ICMP_NE;
 
4922
        break;
 
4923
      }
 
4924
      if ((RA + 1).isMaxSignedValue()) {
 
4925
        Pred = ICmpInst::ICMP_EQ;
 
4926
        RHS = getConstant(RA + 1);
 
4927
        break;
 
4928
      }
 
4929
      if (RA.isMaxSignedValue()) return false;
 
4930
      break;
 
4931
    case ICmpInst::ICMP_SLT:
 
4932
      if (RA.isMaxSignedValue()) {
 
4933
        Pred = ICmpInst::ICMP_NE;
 
4934
        break;
 
4935
      }
 
4936
      if ((RA - 1).isMinSignedValue()) {
 
4937
       Pred = ICmpInst::ICMP_EQ;
 
4938
       RHS = getConstant(RA - 1);
 
4939
       break;
 
4940
      }
 
4941
      if (RA.isMinSignedValue()) return false;
 
4942
      break;
 
4943
    }
 
4944
  }
 
4945
 
 
4946
  // Check to see if we can make the LHS or RHS match.
 
4947
  if (LHS == FoundRHS || RHS == FoundLHS) {
 
4948
    if (isa<SCEVConstant>(RHS)) {
 
4949
      std::swap(FoundLHS, FoundRHS);
 
4950
      FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
 
4951
    } else {
 
4952
      std::swap(LHS, RHS);
 
4953
      Pred = ICmpInst::getSwappedPredicate(Pred);
 
4954
    }
 
4955
  }
 
4956
 
 
4957
  // Check whether the found predicate is the same as the desired predicate.
 
4958
  if (FoundPred == Pred)
 
4959
    return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
 
4960
 
 
4961
  // Check whether swapping the found predicate makes it the same as the
 
4962
  // desired predicate.
 
4963
  if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
 
4964
    if (isa<SCEVConstant>(RHS))
 
4965
      return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
 
4966
    else
 
4967
      return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
 
4968
                                   RHS, LHS, FoundLHS, FoundRHS);
 
4969
  }
 
4970
 
 
4971
  // Check whether the actual condition is beyond sufficient.
 
4972
  if (FoundPred == ICmpInst::ICMP_EQ)
 
4973
    if (ICmpInst::isTrueWhenEqual(Pred))
 
4974
      if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
 
4975
        return true;
 
4976
  if (Pred == ICmpInst::ICMP_NE)
 
4977
    if (!ICmpInst::isTrueWhenEqual(FoundPred))
 
4978
      if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
 
4979
        return true;
 
4980
 
 
4981
  // Otherwise assume the worst.
 
4982
  return false;
 
4983
}
 
4984
 
 
4985
/// isImpliedCondOperands - Test whether the condition described by Pred,
 
4986
/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
 
4987
/// and FoundRHS is true.
 
4988
bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
 
4989
                                            const SCEV *LHS, const SCEV *RHS,
 
4990
                                            const SCEV *FoundLHS,
 
4991
                                            const SCEV *FoundRHS) {
 
4992
  return isImpliedCondOperandsHelper(Pred, LHS, RHS,
 
4993
                                     FoundLHS, FoundRHS) ||
 
4994
         // ~x < ~y --> x > y
 
4995
         isImpliedCondOperandsHelper(Pred, LHS, RHS,
 
4996
                                     getNotSCEV(FoundRHS),
 
4997
                                     getNotSCEV(FoundLHS));
 
4998
}
 
4999
 
 
5000
/// isImpliedCondOperandsHelper - Test whether the condition described by
 
5001
/// Pred, LHS, and RHS is true whenever the condition described by Pred,
 
5002
/// FoundLHS, and FoundRHS is true.
 
5003
bool
 
5004
ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
 
5005
                                             const SCEV *LHS, const SCEV *RHS,
 
5006
                                             const SCEV *FoundLHS,
 
5007
                                             const SCEV *FoundRHS) {
 
5008
  switch (Pred) {
 
5009
  default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
 
5010
  case ICmpInst::ICMP_EQ:
 
5011
  case ICmpInst::ICMP_NE:
 
5012
    if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
 
5013
      return true;
 
5014
    break;
 
5015
  case ICmpInst::ICMP_SLT:
 
5016
  case ICmpInst::ICMP_SLE:
 
5017
    if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
 
5018
        isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
 
5019
      return true;
 
5020
    break;
 
5021
  case ICmpInst::ICMP_SGT:
 
5022
  case ICmpInst::ICMP_SGE:
 
5023
    if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
 
5024
        isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
 
5025
      return true;
 
5026
    break;
 
5027
  case ICmpInst::ICMP_ULT:
 
5028
  case ICmpInst::ICMP_ULE:
 
5029
    if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
 
5030
        isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
 
5031
      return true;
 
5032
    break;
 
5033
  case ICmpInst::ICMP_UGT:
 
5034
  case ICmpInst::ICMP_UGE:
 
5035
    if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
 
5036
        isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
 
5037
      return true;
 
5038
    break;
 
5039
  }
 
5040
 
 
5041
  return false;
 
5042
}
 
5043
 
 
5044
/// getBECount - Subtract the end and start values and divide by the step,
 
5045
/// rounding up, to get the number of times the backedge is executed. Return
 
5046
/// CouldNotCompute if an intermediate computation overflows.
 
5047
const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
 
5048
                                        const SCEV *End,
 
5049
                                        const SCEV *Step,
 
5050
                                        bool NoWrap) {
 
5051
  assert(!isKnownNegative(Step) &&
 
5052
         "This code doesn't handle negative strides yet!");
 
5053
 
 
5054
  const Type *Ty = Start->getType();
 
5055
  const SCEV *NegOne = getIntegerSCEV(-1, Ty);
 
5056
  const SCEV *Diff = getMinusSCEV(End, Start);
 
5057
  const SCEV *RoundUp = getAddExpr(Step, NegOne);
 
5058
 
 
5059
  // Add an adjustment to the difference between End and Start so that
 
5060
  // the division will effectively round up.
 
5061
  const SCEV *Add = getAddExpr(Diff, RoundUp);
 
5062
 
 
5063
  if (!NoWrap) {
 
5064
    // Check Add for unsigned overflow.
 
5065
    // TODO: More sophisticated things could be done here.
 
5066
    const Type *WideTy = IntegerType::get(getContext(),
 
5067
                                          getTypeSizeInBits(Ty) + 1);
 
5068
    const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
 
5069
    const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
 
5070
    const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
 
5071
    if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
 
5072
      return getCouldNotCompute();
 
5073
  }
 
5074
 
 
5075
  return getUDivExpr(Add, Step);
 
5076
}
 
5077
 
 
5078
/// HowManyLessThans - Return the number of times a backedge containing the
 
5079
/// specified less-than comparison will execute.  If not computable, return
 
5080
/// CouldNotCompute.
 
5081
ScalarEvolution::BackedgeTakenInfo
 
5082
ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
 
5083
                                  const Loop *L, bool isSigned) {
 
5084
  // Only handle:  "ADDREC < LoopInvariant".
 
5085
  if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
 
5086
 
 
5087
  const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
 
5088
  if (!AddRec || AddRec->getLoop() != L)
 
5089
    return getCouldNotCompute();
 
5090
 
 
5091
  // Check to see if we have a flag which makes analysis easy.
 
5092
  bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
 
5093
                           AddRec->hasNoUnsignedWrap();
 
5094
 
 
5095
  if (AddRec->isAffine()) {
 
5096
    unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
 
5097
    const SCEV *Step = AddRec->getStepRecurrence(*this);
 
5098
 
 
5099
    if (Step->isZero())
 
5100
      return getCouldNotCompute();
 
5101
    if (Step->isOne()) {
 
5102
      // With unit stride, the iteration never steps past the limit value.
 
5103
    } else if (isKnownPositive(Step)) {
 
5104
      // Test whether a positive iteration can step past the limit
 
5105
      // value and past the maximum value for its type in a single step.
 
5106
      // Note that it's not sufficient to check NoWrap here, because even
 
5107
      // though the value after a wrap is undefined, it's not undefined
 
5108
      // behavior, so if wrap does occur, the loop could either terminate or
 
5109
      // loop infinitely, but in either case, the loop is guaranteed to
 
5110
      // iterate at least until the iteration where the wrapping occurs.
 
5111
      const SCEV *One = getIntegerSCEV(1, Step->getType());
 
5112
      if (isSigned) {
 
5113
        APInt Max = APInt::getSignedMaxValue(BitWidth);
 
5114
        if ((Max - getSignedRange(getMinusSCEV(Step, One)).getSignedMax())
 
5115
              .slt(getSignedRange(RHS).getSignedMax()))
 
5116
          return getCouldNotCompute();
 
5117
      } else {
 
5118
        APInt Max = APInt::getMaxValue(BitWidth);
 
5119
        if ((Max - getUnsignedRange(getMinusSCEV(Step, One)).getUnsignedMax())
 
5120
              .ult(getUnsignedRange(RHS).getUnsignedMax()))
 
5121
          return getCouldNotCompute();
 
5122
      }
 
5123
    } else
 
5124
      // TODO: Handle negative strides here and below.
 
5125
      return getCouldNotCompute();
 
5126
 
 
5127
    // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
 
5128
    // m.  So, we count the number of iterations in which {n,+,s} < m is true.
 
5129
    // Note that we cannot simply return max(m-n,0)/s because it's not safe to
 
5130
    // treat m-n as signed nor unsigned due to overflow possibility.
 
5131
 
 
5132
    // First, we get the value of the LHS in the first iteration: n
 
5133
    const SCEV *Start = AddRec->getOperand(0);
 
5134
 
 
5135
    // Determine the minimum constant start value.
 
5136
    const SCEV *MinStart = getConstant(isSigned ?
 
5137
      getSignedRange(Start).getSignedMin() :
 
5138
      getUnsignedRange(Start).getUnsignedMin());
 
5139
 
 
5140
    // If we know that the condition is true in order to enter the loop,
 
5141
    // then we know that it will run exactly (m-n)/s times. Otherwise, we
 
5142
    // only know that it will execute (max(m,n)-n)/s times. In both cases,
 
5143
    // the division must round up.
 
5144
    const SCEV *End = RHS;
 
5145
    if (!isLoopGuardedByCond(L,
 
5146
                             isSigned ? ICmpInst::ICMP_SLT :
 
5147
                                        ICmpInst::ICMP_ULT,
 
5148
                             getMinusSCEV(Start, Step), RHS))
 
5149
      End = isSigned ? getSMaxExpr(RHS, Start)
 
5150
                     : getUMaxExpr(RHS, Start);
 
5151
 
 
5152
    // Determine the maximum constant end value.
 
5153
    const SCEV *MaxEnd = getConstant(isSigned ?
 
5154
      getSignedRange(End).getSignedMax() :
 
5155
      getUnsignedRange(End).getUnsignedMax());
 
5156
 
 
5157
    // If MaxEnd is within a step of the maximum integer value in its type,
 
5158
    // adjust it down to the minimum value which would produce the same effect.
 
5159
    // This allows the subsequent ceiling division of (N+(step-1))/step to
 
5160
    // compute the correct value.
 
5161
    const SCEV *StepMinusOne = getMinusSCEV(Step,
 
5162
                                            getIntegerSCEV(1, Step->getType()));
 
5163
    MaxEnd = isSigned ?
 
5164
      getSMinExpr(MaxEnd,
 
5165
                  getMinusSCEV(getConstant(APInt::getSignedMaxValue(BitWidth)),
 
5166
                               StepMinusOne)) :
 
5167
      getUMinExpr(MaxEnd,
 
5168
                  getMinusSCEV(getConstant(APInt::getMaxValue(BitWidth)),
 
5169
                               StepMinusOne));
 
5170
 
 
5171
    // Finally, we subtract these two values and divide, rounding up, to get
 
5172
    // the number of times the backedge is executed.
 
5173
    const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
 
5174
 
 
5175
    // The maximum backedge count is similar, except using the minimum start
 
5176
    // value and the maximum end value.
 
5177
    const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
 
5178
 
 
5179
    return BackedgeTakenInfo(BECount, MaxBECount);
 
5180
  }
 
5181
 
 
5182
  return getCouldNotCompute();
 
5183
}
 
5184
 
 
5185
/// getNumIterationsInRange - Return the number of iterations of this loop that
 
5186
/// produce values in the specified constant range.  Another way of looking at
 
5187
/// this is that it returns the first iteration number where the value is not in
 
5188
/// the condition, thus computing the exit count. If the iteration count can't
 
5189
/// be computed, an instance of SCEVCouldNotCompute is returned.
 
5190
const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
 
5191
                                                    ScalarEvolution &SE) const {
 
5192
  if (Range.isFullSet())  // Infinite loop.
 
5193
    return SE.getCouldNotCompute();
 
5194
 
 
5195
  // If the start is a non-zero constant, shift the range to simplify things.
 
5196
  if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
 
5197
    if (!SC->getValue()->isZero()) {
 
5198
      SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
 
5199
      Operands[0] = SE.getIntegerSCEV(0, SC->getType());
 
5200
      const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
 
5201
      if (const SCEVAddRecExpr *ShiftedAddRec =
 
5202
            dyn_cast<SCEVAddRecExpr>(Shifted))
 
5203
        return ShiftedAddRec->getNumIterationsInRange(
 
5204
                           Range.subtract(SC->getValue()->getValue()), SE);
 
5205
      // This is strange and shouldn't happen.
 
5206
      return SE.getCouldNotCompute();
 
5207
    }
 
5208
 
 
5209
  // The only time we can solve this is when we have all constant indices.
 
5210
  // Otherwise, we cannot determine the overflow conditions.
 
5211
  for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
 
5212
    if (!isa<SCEVConstant>(getOperand(i)))
 
5213
      return SE.getCouldNotCompute();
 
5214
 
 
5215
 
 
5216
  // Okay at this point we know that all elements of the chrec are constants and
 
5217
  // that the start element is zero.
 
5218
 
 
5219
  // First check to see if the range contains zero.  If not, the first
 
5220
  // iteration exits.
 
5221
  unsigned BitWidth = SE.getTypeSizeInBits(getType());
 
5222
  if (!Range.contains(APInt(BitWidth, 0)))
 
5223
    return SE.getIntegerSCEV(0, getType());
 
5224
 
 
5225
  if (isAffine()) {
 
5226
    // If this is an affine expression then we have this situation:
 
5227
    //   Solve {0,+,A} in Range  ===  Ax in Range
 
5228
 
 
5229
    // We know that zero is in the range.  If A is positive then we know that
 
5230
    // the upper value of the range must be the first possible exit value.
 
5231
    // If A is negative then the lower of the range is the last possible loop
 
5232
    // value.  Also note that we already checked for a full range.
 
5233
    APInt One(BitWidth,1);
 
5234
    APInt A     = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
 
5235
    APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
 
5236
 
 
5237
    // The exit value should be (End+A)/A.
 
5238
    APInt ExitVal = (End + A).udiv(A);
 
5239
    ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
 
5240
 
 
5241
    // Evaluate at the exit value.  If we really did fall out of the valid
 
5242
    // range, then we computed our trip count, otherwise wrap around or other
 
5243
    // things must have happened.
 
5244
    ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
 
5245
    if (Range.contains(Val->getValue()))
 
5246
      return SE.getCouldNotCompute();  // Something strange happened
 
5247
 
 
5248
    // Ensure that the previous value is in the range.  This is a sanity check.
 
5249
    assert(Range.contains(
 
5250
           EvaluateConstantChrecAtConstant(this,
 
5251
           ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
 
5252
           "Linear scev computation is off in a bad way!");
 
5253
    return SE.getConstant(ExitValue);
 
5254
  } else if (isQuadratic()) {
 
5255
    // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
 
5256
    // quadratic equation to solve it.  To do this, we must frame our problem in
 
5257
    // terms of figuring out when zero is crossed, instead of when
 
5258
    // Range.getUpper() is crossed.
 
5259
    SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
 
5260
    NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
 
5261
    const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
 
5262
 
 
5263
    // Next, solve the constructed addrec
 
5264
    std::pair<const SCEV *,const SCEV *> Roots =
 
5265
      SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
 
5266
    const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
 
5267
    const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
 
5268
    if (R1) {
 
5269
      // Pick the smallest positive root value.
 
5270
      if (ConstantInt *CB =
 
5271
          dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
 
5272
                         R1->getValue(), R2->getValue()))) {
 
5273
        if (CB->getZExtValue() == false)
 
5274
          std::swap(R1, R2);   // R1 is the minimum root now.
 
5275
 
 
5276
        // Make sure the root is not off by one.  The returned iteration should
 
5277
        // not be in the range, but the previous one should be.  When solving
 
5278
        // for "X*X < 5", for example, we should not return a root of 2.
 
5279
        ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
 
5280
                                                             R1->getValue(),
 
5281
                                                             SE);
 
5282
        if (Range.contains(R1Val->getValue())) {
 
5283
          // The next iteration must be out of the range...
 
5284
          ConstantInt *NextVal =
 
5285
                ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
 
5286
 
 
5287
          R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
 
5288
          if (!Range.contains(R1Val->getValue()))
 
5289
            return SE.getConstant(NextVal);
 
5290
          return SE.getCouldNotCompute();  // Something strange happened
 
5291
        }
 
5292
 
 
5293
        // If R1 was not in the range, then it is a good return value.  Make
 
5294
        // sure that R1-1 WAS in the range though, just in case.
 
5295
        ConstantInt *NextVal =
 
5296
               ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
 
5297
        R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
 
5298
        if (Range.contains(R1Val->getValue()))
 
5299
          return R1;
 
5300
        return SE.getCouldNotCompute();  // Something strange happened
 
5301
      }
 
5302
    }
 
5303
  }
 
5304
 
 
5305
  return SE.getCouldNotCompute();
 
5306
}
 
5307
 
 
5308
 
 
5309
 
 
5310
//===----------------------------------------------------------------------===//
 
5311
//                   SCEVCallbackVH Class Implementation
 
5312
//===----------------------------------------------------------------------===//
 
5313
 
 
5314
void ScalarEvolution::SCEVCallbackVH::deleted() {
 
5315
  assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
 
5316
  if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
 
5317
    SE->ConstantEvolutionLoopExitValue.erase(PN);
 
5318
  SE->Scalars.erase(getValPtr());
 
5319
  // this now dangles!
 
5320
}
 
5321
 
 
5322
void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
 
5323
  assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
 
5324
 
 
5325
  // Forget all the expressions associated with users of the old value,
 
5326
  // so that future queries will recompute the expressions using the new
 
5327
  // value.
 
5328
  SmallVector<User *, 16> Worklist;
 
5329
  SmallPtrSet<User *, 8> Visited;
 
5330
  Value *Old = getValPtr();
 
5331
  bool DeleteOld = false;
 
5332
  for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
 
5333
       UI != UE; ++UI)
 
5334
    Worklist.push_back(*UI);
 
5335
  while (!Worklist.empty()) {
 
5336
    User *U = Worklist.pop_back_val();
 
5337
    // Deleting the Old value will cause this to dangle. Postpone
 
5338
    // that until everything else is done.
 
5339
    if (U == Old) {
 
5340
      DeleteOld = true;
 
5341
      continue;
 
5342
    }
 
5343
    if (!Visited.insert(U))
 
5344
      continue;
 
5345
    if (PHINode *PN = dyn_cast<PHINode>(U))
 
5346
      SE->ConstantEvolutionLoopExitValue.erase(PN);
 
5347
    SE->Scalars.erase(U);
 
5348
    for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
 
5349
         UI != UE; ++UI)
 
5350
      Worklist.push_back(*UI);
 
5351
  }
 
5352
  // Delete the Old value if it (indirectly) references itself.
 
5353
  if (DeleteOld) {
 
5354
    if (PHINode *PN = dyn_cast<PHINode>(Old))
 
5355
      SE->ConstantEvolutionLoopExitValue.erase(PN);
 
5356
    SE->Scalars.erase(Old);
 
5357
    // this now dangles!
 
5358
  }
 
5359
  // this may dangle!
 
5360
}
 
5361
 
 
5362
ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
 
5363
  : CallbackVH(V), SE(se) {}
 
5364
 
 
5365
//===----------------------------------------------------------------------===//
 
5366
//                   ScalarEvolution Class Implementation
 
5367
//===----------------------------------------------------------------------===//
 
5368
 
 
5369
ScalarEvolution::ScalarEvolution()
 
5370
  : FunctionPass(&ID) {
 
5371
}
 
5372
 
 
5373
bool ScalarEvolution::runOnFunction(Function &F) {
 
5374
  this->F = &F;
 
5375
  LI = &getAnalysis<LoopInfo>();
 
5376
  TD = getAnalysisIfAvailable<TargetData>();
 
5377
  DT = &getAnalysis<DominatorTree>();
 
5378
  return false;
 
5379
}
 
5380
 
 
5381
void ScalarEvolution::releaseMemory() {
 
5382
  Scalars.clear();
 
5383
  BackedgeTakenCounts.clear();
 
5384
  ConstantEvolutionLoopExitValue.clear();
 
5385
  ValuesAtScopes.clear();
 
5386
  UniqueSCEVs.clear();
 
5387
  SCEVAllocator.Reset();
 
5388
}
 
5389
 
 
5390
void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
 
5391
  AU.setPreservesAll();
 
5392
  AU.addRequiredTransitive<LoopInfo>();
 
5393
  AU.addRequiredTransitive<DominatorTree>();
 
5394
}
 
5395
 
 
5396
bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
 
5397
  return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
 
5398
}
 
5399
 
 
5400
static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
 
5401
                          const Loop *L) {
 
5402
  // Print all inner loops first
 
5403
  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
 
5404
    PrintLoopInfo(OS, SE, *I);
 
5405
 
 
5406
  OS << "Loop ";
 
5407
  WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
 
5408
  OS << ": ";
 
5409
 
 
5410
  SmallVector<BasicBlock *, 8> ExitBlocks;
 
5411
  L->getExitBlocks(ExitBlocks);
 
5412
  if (ExitBlocks.size() != 1)
 
5413
    OS << "<multiple exits> ";
 
5414
 
 
5415
  if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
 
5416
    OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
 
5417
  } else {
 
5418
    OS << "Unpredictable backedge-taken count. ";
 
5419
  }
 
5420
 
 
5421
  OS << "\n"
 
5422
        "Loop ";
 
5423
  WriteAsOperand(OS, L->getHeader(), /*PrintType=*/false);
 
5424
  OS << ": ";
 
5425
 
 
5426
  if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
 
5427
    OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
 
5428
  } else {
 
5429
    OS << "Unpredictable max backedge-taken count. ";
 
5430
  }
 
5431
 
 
5432
  OS << "\n";
 
5433
}
 
5434
 
 
5435
void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
 
5436
  // ScalarEvolution's implementation of the print method is to print
 
5437
  // out SCEV values of all instructions that are interesting. Doing
 
5438
  // this potentially causes it to create new SCEV objects though,
 
5439
  // which technically conflicts with the const qualifier. This isn't
 
5440
  // observable from outside the class though, so casting away the
 
5441
  // const isn't dangerous.
 
5442
  ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
 
5443
 
 
5444
  OS << "Classifying expressions for: ";
 
5445
  WriteAsOperand(OS, F, /*PrintType=*/false);
 
5446
  OS << "\n";
 
5447
  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
 
5448
    if (isSCEVable(I->getType())) {
 
5449
      OS << *I << '\n';
 
5450
      OS << "  -->  ";
 
5451
      const SCEV *SV = SE.getSCEV(&*I);
 
5452
      SV->print(OS);
 
5453
 
 
5454
      const Loop *L = LI->getLoopFor((*I).getParent());
 
5455
 
 
5456
      const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
 
5457
      if (AtUse != SV) {
 
5458
        OS << "  -->  ";
 
5459
        AtUse->print(OS);
 
5460
      }
 
5461
 
 
5462
      if (L) {
 
5463
        OS << "\t\t" "Exits: ";
 
5464
        const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
 
5465
        if (!ExitValue->isLoopInvariant(L)) {
 
5466
          OS << "<<Unknown>>";
 
5467
        } else {
 
5468
          OS << *ExitValue;
 
5469
        }
 
5470
      }
 
5471
 
 
5472
      OS << "\n";
 
5473
    }
 
5474
 
 
5475
  OS << "Determining loop execution counts for: ";
 
5476
  WriteAsOperand(OS, F, /*PrintType=*/false);
 
5477
  OS << "\n";
 
5478
  for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
 
5479
    PrintLoopInfo(OS, &SE, *I);
 
5480
}
 
5481