Coverage Report

Created: 2017-11-21 16:49

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Analysis/ScopDetection.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ScopDetection.cpp - Detect Scops -----------------------------------===//
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
// Detect the maximal Scops of a function.
11
//
12
// A static control part (Scop) is a subgraph of the control flow graph (CFG)
13
// that only has statically known control flow and can therefore be described
14
// within the polyhedral model.
15
//
16
// Every Scop fulfills these restrictions:
17
//
18
// * It is a single entry single exit region
19
//
20
// * Only affine linear bounds in the loops
21
//
22
// Every natural loop in a Scop must have a number of loop iterations that can
23
// be described as an affine linear function in surrounding loop iterators or
24
// parameters. (A parameter is a scalar that does not change its value during
25
// execution of the Scop).
26
//
27
// * Only comparisons of affine linear expressions in conditions
28
//
29
// * All loops and conditions perfectly nested
30
//
31
// The control flow needs to be structured such that it could be written using
32
// just 'for' and 'if' statements, without the need for any 'goto', 'break' or
33
// 'continue'.
34
//
35
// * Side effect free functions call
36
//
37
// Function calls and intrinsics that do not have side effects (readnone)
38
// or memory intrinsics (memset, memcpy, memmove) are allowed.
39
//
40
// The Scop detection finds the largest Scops by checking if the largest
41
// region is a Scop. If this is not the case, its canonical subregions are
42
// checked until a region is a Scop. It is now tried to extend this Scop by
43
// creating a larger non canonical region.
44
//
45
//===----------------------------------------------------------------------===//
46
47
#include "polly/ScopDetection.h"
48
#include "polly/LinkAllPasses.h"
49
#include "polly/Options.h"
50
#include "polly/ScopDetectionDiagnostic.h"
51
#include "polly/Support/SCEVValidator.h"
52
#include "polly/Support/ScopHelper.h"
53
#include "polly/Support/ScopLocation.h"
54
#include "llvm/ADT/DenseMap.h"
55
#include "llvm/ADT/SetVector.h"
56
#include "llvm/ADT/SmallPtrSet.h"
57
#include "llvm/ADT/SmallVector.h"
58
#include "llvm/ADT/Statistic.h"
59
#include "llvm/ADT/StringRef.h"
60
#include "llvm/Analysis/AliasAnalysis.h"
61
#include "llvm/Analysis/Loads.h"
62
#include "llvm/Analysis/LoopInfo.h"
63
#include "llvm/Analysis/MemoryLocation.h"
64
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
65
#include "llvm/Analysis/RegionInfo.h"
66
#include "llvm/Analysis/ScalarEvolution.h"
67
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
68
#include "llvm/IR/BasicBlock.h"
69
#include "llvm/IR/Constants.h"
70
#include "llvm/IR/DebugLoc.h"
71
#include "llvm/IR/DerivedTypes.h"
72
#include "llvm/IR/DiagnosticInfo.h"
73
#include "llvm/IR/DiagnosticPrinter.h"
74
#include "llvm/IR/Dominators.h"
75
#include "llvm/IR/Function.h"
76
#include "llvm/IR/InstrTypes.h"
77
#include "llvm/IR/Instruction.h"
78
#include "llvm/IR/Instructions.h"
79
#include "llvm/IR/IntrinsicInst.h"
80
#include "llvm/IR/Intrinsics.h"
81
#include "llvm/IR/LLVMContext.h"
82
#include "llvm/IR/Metadata.h"
83
#include "llvm/IR/Module.h"
84
#include "llvm/IR/PassManager.h"
85
#include "llvm/IR/Type.h"
86
#include "llvm/IR/Value.h"
87
#include "llvm/Pass.h"
88
#include "llvm/Support/Casting.h"
89
#include "llvm/Support/CommandLine.h"
90
#include "llvm/Support/Debug.h"
91
#include "llvm/Support/ErrorHandling.h"
92
#include "llvm/Support/Regex.h"
93
#include "llvm/Support/raw_ostream.h"
94
#include <algorithm>
95
#include <cassert>
96
#include <memory>
97
#include <stack>
98
#include <string>
99
#include <utility>
100
#include <vector>
101
102
using namespace llvm;
103
using namespace polly;
104
105
#define DEBUG_TYPE "polly-detect"
106
107
// This option is set to a very high value, as analyzing such loops increases
108
// compile time on several cases. For experiments that enable this option,
109
// a value of around 40 has been working to avoid run-time regressions with
110
// Polly while still exposing interesting optimization opportunities.
111
static cl::opt<int> ProfitabilityMinPerLoopInstructions(
112
    "polly-detect-profitability-min-per-loop-insts",
113
    cl::desc("The minimal number of per-loop instructions before a single loop "
114
             "region is considered profitable"),
115
    cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory));
116
117
bool polly::PollyProcessUnprofitable;
118
119
static cl::opt<bool, true> XPollyProcessUnprofitable(
120
    "polly-process-unprofitable",
121
    cl::desc(
122
        "Process scops that are unlikely to benefit from Polly optimizations."),
123
    cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore,
124
    cl::cat(PollyCategory));
125
126
static cl::list<std::string> OnlyFunctions(
127
    "polly-only-func",
128
    cl::desc("Only run on functions that match a regex. "
129
             "Multiple regexes can be comma separated. "
130
             "Scop detection will run on all functions that match "
131
             "ANY of the regexes provided."),
132
    cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
133
134
static cl::list<std::string> IgnoredFunctions(
135
    "polly-ignore-func",
136
    cl::desc("Ignore functions that match a regex. "
137
             "Multiple regexes can be comma separated. "
138
             "Scop detection will ignore all functions that match "
139
             "ANY of the regexes provided."),
140
    cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
141
142
bool polly::PollyAllowFullFunction;
143
144
static cl::opt<bool, true>
145
    XAllowFullFunction("polly-detect-full-functions",
146
                       cl::desc("Allow the detection of full functions"),
147
                       cl::location(polly::PollyAllowFullFunction),
148
                       cl::init(false), cl::cat(PollyCategory));
149
150
static cl::opt<std::string> OnlyRegion(
151
    "polly-only-region",
152
    cl::desc("Only run on certain regions (The provided identifier must "
153
             "appear in the name of the region's entry block"),
154
    cl::value_desc("identifier"), cl::ValueRequired, cl::init(""),
155
    cl::cat(PollyCategory));
156
157
static cl::opt<bool>
158
    IgnoreAliasing("polly-ignore-aliasing",
159
                   cl::desc("Ignore possible aliasing of the array bases"),
160
                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
161
                   cl::cat(PollyCategory));
162
163
bool polly::PollyAllowUnsignedOperations;
164
165
static cl::opt<bool, true> XPollyAllowUnsignedOperations(
166
    "polly-allow-unsigned-operations",
167
    cl::desc("Allow unsigned operations such as comparisons or zero-extends."),
168
    cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore,
169
    cl::init(true), cl::cat(PollyCategory));
170
171
bool polly::PollyUseRuntimeAliasChecks;
172
173
static cl::opt<bool, true> XPollyUseRuntimeAliasChecks(
174
    "polly-use-runtime-alias-checks",
175
    cl::desc("Use runtime alias checks to resolve possible aliasing."),
176
    cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore,
177
    cl::init(true), cl::cat(PollyCategory));
178
179
static cl::opt<bool>
180
    ReportLevel("polly-report",
181
                cl::desc("Print information about the activities of Polly"),
182
                cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
183
184
static cl::opt<bool> AllowDifferentTypes(
185
    "polly-allow-differing-element-types",
186
    cl::desc("Allow different element types for array accesses"), cl::Hidden,
187
    cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
188
189
static cl::opt<bool>
190
    AllowNonAffine("polly-allow-nonaffine",
191
                   cl::desc("Allow non affine access functions in arrays"),
192
                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
193
                   cl::cat(PollyCategory));
194
195
static cl::opt<bool>
196
    AllowModrefCall("polly-allow-modref-calls",
197
                    cl::desc("Allow functions with known modref behavior"),
198
                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
199
                    cl::cat(PollyCategory));
200
201
static cl::opt<bool> AllowNonAffineSubRegions(
202
    "polly-allow-nonaffine-branches",
203
    cl::desc("Allow non affine conditions for branches"), cl::Hidden,
204
    cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
205
206
static cl::opt<bool>
207
    AllowNonAffineSubLoops("polly-allow-nonaffine-loops",
208
                           cl::desc("Allow non affine conditions for loops"),
209
                           cl::Hidden, cl::init(false), cl::ZeroOrMore,
210
                           cl::cat(PollyCategory));
211
212
static cl::opt<bool, true>
213
    TrackFailures("polly-detect-track-failures",
214
                  cl::desc("Track failure strings in detecting scop regions"),
215
                  cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore,
216
                  cl::init(true), cl::cat(PollyCategory));
217
218
static cl::opt<bool> KeepGoing("polly-detect-keep-going",
219
                               cl::desc("Do not fail on the first error."),
220
                               cl::Hidden, cl::ZeroOrMore, cl::init(false),
221
                               cl::cat(PollyCategory));
222
223
static cl::opt<bool, true>
224
    PollyDelinearizeX("polly-delinearize",
225
                      cl::desc("Delinearize array access functions"),
226
                      cl::location(PollyDelinearize), cl::Hidden,
227
                      cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
228
229
static cl::opt<bool>
230
    VerifyScops("polly-detect-verify",
231
                cl::desc("Verify the detected SCoPs after each transformation"),
232
                cl::Hidden, cl::init(false), cl::ZeroOrMore,
233
                cl::cat(PollyCategory));
234
235
bool polly::PollyInvariantLoadHoisting;
236
237
static cl::opt<bool, true> XPollyInvariantLoadHoisting(
238
    "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."),
239
    cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore,
240
    cl::init(false), cl::cat(PollyCategory));
241
242
/// The minimal trip count under which loops are considered unprofitable.
243
static const unsigned MIN_LOOP_TRIP_COUNT = 8;
244
245
bool polly::PollyTrackFailures = false;
246
bool polly::PollyDelinearize = false;
247
StringRef polly::PollySkipFnAttr = "polly.skip.fn";
248
249
//===----------------------------------------------------------------------===//
250
// Statistics.
251
252
STATISTIC(NumScopRegions, "Number of scops");
253
STATISTIC(NumLoopsInScop, "Number of loops in scops");
254
STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
255
STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
256
STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
257
STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
258
STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
259
STATISTIC(NumScopsDepthLarger,
260
          "Number of scops with maximal loop depth 6 and larger");
261
STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)");
262
STATISTIC(NumLoopsInProfScop,
263
          "Number of loops in scops (profitable scops only)");
264
STATISTIC(NumLoopsOverall, "Number of total loops");
265
STATISTIC(NumProfScopsDepthOne,
266
          "Number of scops with maximal loop depth 1 (profitable scops only)");
267
STATISTIC(NumProfScopsDepthTwo,
268
          "Number of scops with maximal loop depth 2 (profitable scops only)");
269
STATISTIC(NumProfScopsDepthThree,
270
          "Number of scops with maximal loop depth 3 (profitable scops only)");
271
STATISTIC(NumProfScopsDepthFour,
272
          "Number of scops with maximal loop depth 4 (profitable scops only)");
273
STATISTIC(NumProfScopsDepthFive,
274
          "Number of scops with maximal loop depth 5 (profitable scops only)");
275
STATISTIC(NumProfScopsDepthLarger,
276
          "Number of scops with maximal loop depth 6 and larger "
277
          "(profitable scops only)");
278
STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
279
STATISTIC(MaxNumLoopsInProfScop,
280
          "Maximal number of loops in scops (profitable scops only)");
281
282
static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
283
                                     bool OnlyProfitable);
284
285
namespace {
286
287
class DiagnosticScopFound : public DiagnosticInfo {
288
private:
289
  static int PluginDiagnosticKind;
290
291
  Function &F;
292
  std::string FileName;
293
  unsigned EntryLine, ExitLine;
294
295
public:
296
  DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine,
297
                      unsigned ExitLine)
298
      : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName),
299
0
        EntryLine(EntryLine), ExitLine(ExitLine) {}
300
301
  void print(DiagnosticPrinter &DP) const override;
302
303
0
  static bool classof(const DiagnosticInfo *DI) {
304
0
    return DI->getKind() == PluginDiagnosticKind;
305
0
  }
306
};
307
308
} // namespace
309
310
int DiagnosticScopFound::PluginDiagnosticKind =
311
    getNextAvailablePluginDiagnosticKind();
312
313
0
void DiagnosticScopFound::print(DiagnosticPrinter &DP) const {
314
0
  DP << "Polly detected an optimizable loop region (scop) in function '" << F
315
0
     << "'\n";
316
0
317
0
  if (FileName.empty()) {
318
0
    DP << "Scop location is unknown. Compile with debug info "
319
0
          "(-g) to get more precise information. ";
320
0
    return;
321
0
  }
322
0
323
0
  DP << FileName << ":" << EntryLine << ": Start of scop\n";
324
0
  DP << FileName << ":" << ExitLine << ": End of scop";
325
0
}
326
327
/// Check if a string matches any regex in a list of regexes.
328
/// @param Str the input string to match against.
329
/// @param RegexList a list of strings that are regular expressions.
330
static bool doesStringMatchAnyRegex(StringRef Str,
331
440
                                    const cl::list<std::string> &RegexList) {
332
440
  for (auto RegexStr : RegexList) {
333
5
    Regex R(RegexStr);
334
5
335
5
    std::string Err;
336
5
    if (!R.isValid(Err))
337
0
      report_fatal_error("invalid regex given as input to polly: " + Err, true);
338
5
339
5
    if (R.match(Str))
340
2
      return true;
341
438
  }
342
438
  return false;
343
438
}
344
//===----------------------------------------------------------------------===//
345
// ScopDetection.
346
347
ScopDetection::ScopDetection(Function &F, const DominatorTree &DT,
348
                             ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI,
349
                             AliasAnalysis &AA, OptimizationRemarkEmitter &ORE)
350
438
    : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) {
351
438
  if (!PollyProcessUnprofitable && 
LI.empty()10
)
352
0
    return;
353
438
354
438
  Region *TopRegion = RI.getTopLevelRegion();
355
438
356
438
  if (!OnlyFunctions.empty() &&
357
438
      
!doesStringMatchAnyRegex(F.getName(), OnlyFunctions)3
)
358
1
    return;
359
437
360
437
  if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions))
361
0
    return;
362
437
363
437
  if (!isValidFunction(F))
364
8
    return;
365
429
366
429
  findScops(*TopRegion);
367
429
368
429
  NumScopRegions += ValidRegions.size();
369
429
370
429
  // Prune non-profitable regions.
371
1.15k
  for (auto &DIt : DetectionContextMap) {
372
1.15k
    auto &DC = DIt.getSecond();
373
1.15k
    if (DC.Log.hasErrors())
374
135
      continue;
375
1.01k
    if (!ValidRegions.count(&DC.CurRegion))
376
615
      continue;
377
400
    LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0);
378
400
    updateLoopCountStatistic(Stats, false /* OnlyProfitable */);
379
400
    if (isProfitableRegion(DC)) {
380
392
      updateLoopCountStatistic(Stats, true /* OnlyProfitable */);
381
392
      continue;
382
392
    }
383
8
384
8
    ValidRegions.remove(&DC.CurRegion);
385
8
  }
386
429
387
429
  NumProfScopRegions += ValidRegions.size();
388
429
  NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops;
389
429
390
429
  // Only makes sense when we tracked errors.
391
429
  if (PollyTrackFailures)
392
429
    emitMissedRemarks(F);
393
429
394
429
  if (ReportLevel)
395
0
    printLocations(F);
396
438
397
438
  assert(ValidRegions.size() <= DetectionContextMap.size() &&
398
438
         "Cached more results than valid regions");
399
438
}
400
401
template <class RR, typename... Args>
402
inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert,
403
193
                                   Args &&... Arguments) const {
404
193
  if (!Context.Verifying) {
405
193
    RejectLog &Log = Context.Log;
406
193
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
193
408
193
    if (PollyTrackFailures)
409
193
      Log.report(RejectReason);
410
193
411
193
    DEBUG(dbgs() << RejectReason->getMessage());
412
193
    DEBUG(dbgs() << "\n");
413
193
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
193
417
193
  return false;
418
193
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNonAffBranch, llvm::BasicBlock*, llvm::SCEV const*&, llvm::SCEV const*&, llvm::SwitchInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::SCEV const*&&&, llvm::SCEV const*&&&, llvm::SwitchInst*&&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportInvalidCond, llvm::BranchInst*&, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BranchInst*&&&, llvm::BasicBlock*&&) const
bool polly::ScopDetection::invalid<polly::ReportUndefOperand, llvm::BasicBlock*, llvm::ICmpInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::ICmpInst*&&&) const
Line
Count
Source
403
3
                                   Args &&... Arguments) const {
404
3
  if (!Context.Verifying) {
405
3
    RejectLog &Log = Context.Log;
406
3
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
3
408
3
    if (PollyTrackFailures)
409
3
      Log.report(RejectReason);
410
3
411
3
    DEBUG(dbgs() << RejectReason->getMessage());
412
3
    DEBUG(dbgs() << "\n");
413
3
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
3
417
3
  return false;
418
3
}
bool polly::ScopDetection::invalid<polly::ReportNonAffBranch, llvm::BasicBlock*, llvm::SCEV const*&, llvm::SCEV const*&, llvm::ICmpInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::SCEV const*&&&, llvm::SCEV const*&&&, llvm::ICmpInst*&&&) const
Line
Count
Source
403
3
                                   Args &&... Arguments) const {
404
3
  if (!Context.Verifying) {
405
3
    RejectLog &Log = Context.Log;
406
3
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
3
408
3
    if (PollyTrackFailures)
409
3
      Log.report(RejectReason);
410
3
411
3
    DEBUG(dbgs() << RejectReason->getMessage());
412
3
    DEBUG(dbgs() << "\n");
413
3
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
3
417
3
  return false;
418
3
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportInvalidTerminator, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&) const
bool polly::ScopDetection::invalid<polly::ReportUndefCond, llvm::TerminatorInst*&, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::TerminatorInst*&&&, llvm::BasicBlock*&&) const
Line
Count
Source
403
51
                                   Args &&... Arguments) const {
404
51
  if (!Context.Verifying) {
405
51
    RejectLog &Log = Context.Log;
406
51
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
51
408
51
    if (PollyTrackFailures)
409
51
      Log.report(RejectReason);
410
51
411
51
    DEBUG(dbgs() << RejectReason->getMessage());
412
51
    DEBUG(dbgs() << "\n");
413
51
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
51
417
51
  return false;
418
51
}
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const*&, llvm::Instruction const*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const*&&&, llvm::Instruction const*&&&, llvm::Value*&&&) const
Line
Count
Source
403
1
                                   Args &&... Arguments) const {
404
1
  if (!Context.Verifying) {
405
1
    RejectLog &Log = Context.Log;
406
1
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
1
408
1
    if (PollyTrackFailures)
409
1
      Log.report(RejectReason);
410
1
411
1
    DEBUG(dbgs() << RejectReason->getMessage());
412
1
    DEBUG(dbgs() << "\n");
413
1
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
1
417
1
  return false;
418
1
}
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const* const&, llvm::Instruction const*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const* const&&&, llvm::Instruction const*&&&, llvm::Value*&&&) const
Line
Count
Source
403
7
                                   Args &&... Arguments) const {
404
7
  if (!Context.Verifying) {
405
7
    RejectLog &Log = Context.Log;
406
7
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
7
408
7
    if (PollyTrackFailures)
409
7
      Log.report(RejectReason);
410
7
411
7
    DEBUG(dbgs() << RejectReason->getMessage());
412
7
    DEBUG(dbgs() << "\n");
413
7
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
7
417
7
  return false;
418
7
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNoBasePtr, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportUndefBasePtr, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportIntToPtr, llvm::IntToPtrInst*&>(polly::ScopDetection::DetectionContext&, bool, llvm::IntToPtrInst*&&&) const
bool polly::ScopDetection::invalid<polly::ReportVariantBasePtr, llvm::Value*&, llvm::Instruction*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Value*&&&, llvm::Instruction*&&&) const
Line
Count
Source
403
2
                                   Args &&... Arguments) const {
404
2
  if (!Context.Verifying) {
405
2
    RejectLog &Log = Context.Log;
406
2
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
2
408
2
    if (PollyTrackFailures)
409
2
      Log.report(RejectReason);
410
2
411
2
    DEBUG(dbgs() << RejectReason->getMessage());
412
2
    DEBUG(dbgs() << "\n");
413
2
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
2
417
2
  return false;
418
2
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportDifferentArrayElementSize, llvm::Instruction*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&, llvm::Value*&&&) const
bool polly::ScopDetection::invalid<polly::ReportNonAffineAccess, llvm::SCEV const*&, llvm::Instruction*&, llvm::Value*&>(polly::ScopDetection::DetectionContext&, bool, llvm::SCEV const*&&&, llvm::Instruction*&&&, llvm::Value*&&&) const
Line
Count
Source
403
5
                                   Args &&... Arguments) const {
404
5
  if (!Context.Verifying) {
405
5
    RejectLog &Log = Context.Log;
406
5
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
5
408
5
    if (PollyTrackFailures)
409
5
      Log.report(RejectReason);
410
5
411
5
    DEBUG(dbgs() << RejectReason->getMessage());
412
5
    DEBUG(dbgs() << "\n");
413
5
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
5
417
5
  return false;
418
5
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportAlias, llvm::Instruction*&, llvm::AliasSet&>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&&, llvm::AliasSet&&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportFuncCall, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportAlloca, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportNonSimpleMemoryAccess, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
bool polly::ScopDetection::invalid<polly::ReportUnknownInst, llvm::Instruction*>(polly::ScopDetection::DetectionContext&, bool, llvm::Instruction*&&) const
Line
Count
Source
403
19
                                   Args &&... Arguments) const {
404
19
  if (!Context.Verifying) {
405
19
    RejectLog &Log = Context.Log;
406
19
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
19
408
19
    if (PollyTrackFailures)
409
19
      Log.report(RejectReason);
410
19
411
19
    DEBUG(dbgs() << RejectReason->getMessage());
412
19
    DEBUG(dbgs() << "\n");
413
19
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
19
417
19
  return false;
418
19
}
Unexecuted instantiation: bool polly::ScopDetection::invalid<polly::ReportLoopHasNoExit, llvm::Loop*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&) const
bool polly::ScopDetection::invalid<polly::ReportLoopBound, llvm::Loop*&, llvm::SCEV const*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&, llvm::SCEV const*&&&) const
Line
Count
Source
403
51
                                   Args &&... Arguments) const {
404
51
  if (!Context.Verifying) {
405
51
    RejectLog &Log = Context.Log;
406
51
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
51
408
51
    if (PollyTrackFailures)
409
51
      Log.report(RejectReason);
410
51
411
51
    DEBUG(dbgs() << RejectReason->getMessage());
412
51
    DEBUG(dbgs() << "\n");
413
51
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
51
417
51
  return false;
418
51
}
bool polly::ScopDetection::invalid<polly::ReportUnprofitable, llvm::Region*>(polly::ScopDetection::DetectionContext&, bool, llvm::Region*&&) const
Line
Count
Source
403
8
                                   Args &&... Arguments) const {
404
8
  if (!Context.Verifying) {
405
8
    RejectLog &Log = Context.Log;
406
8
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
8
408
8
    if (PollyTrackFailures)
409
8
      Log.report(RejectReason);
410
8
411
8
    DEBUG(dbgs() << RejectReason->getMessage());
412
8
    DEBUG(dbgs() << "\n");
413
8
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
8
417
8
  return false;
418
8
}
bool polly::ScopDetection::invalid<polly::ReportLoopOnlySomeLatches, llvm::Loop*&>(polly::ScopDetection::DetectionContext&, bool, llvm::Loop*&&&) const
Line
Count
Source
403
3
                                   Args &&... Arguments) const {
404
3
  if (!Context.Verifying) {
405
3
    RejectLog &Log = Context.Log;
406
3
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
3
408
3
    if (PollyTrackFailures)
409
3
      Log.report(RejectReason);
410
3
411
3
    DEBUG(dbgs() << RejectReason->getMessage());
412
3
    DEBUG(dbgs() << "\n");
413
3
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
3
417
3
  return false;
418
3
}
bool polly::ScopDetection::invalid<polly::ReportUnreachableInExit, llvm::BasicBlock*, llvm::DebugLoc&>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&, llvm::DebugLoc&&&) const
Line
Count
Source
403
12
                                   Args &&... Arguments) const {
404
12
  if (!Context.Verifying) {
405
12
    RejectLog &Log = Context.Log;
406
12
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
12
408
12
    if (PollyTrackFailures)
409
12
      Log.report(RejectReason);
410
12
411
12
    DEBUG(dbgs() << RejectReason->getMessage());
412
12
    DEBUG(dbgs() << "\n");
413
12
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
12
417
12
  return false;
418
12
}
bool polly::ScopDetection::invalid<polly::ReportEntry, llvm::BasicBlock*>(polly::ScopDetection::DetectionContext&, bool, llvm::BasicBlock*&&) const
Line
Count
Source
403
27
                                   Args &&... Arguments) const {
404
27
  if (!Context.Verifying) {
405
27
    RejectLog &Log = Context.Log;
406
27
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
27
408
27
    if (PollyTrackFailures)
409
27
      Log.report(RejectReason);
410
27
411
27
    DEBUG(dbgs() << RejectReason->getMessage());
412
27
    DEBUG(dbgs() << "\n");
413
27
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
27
417
27
  return false;
418
27
}
bool polly::ScopDetection::invalid<polly::ReportIrreducibleRegion, llvm::Region*, llvm::DebugLoc&>(polly::ScopDetection::DetectionContext&, bool, llvm::Region*&&, llvm::DebugLoc&&&) const
Line
Count
Source
403
1
                                   Args &&... Arguments) const {
404
1
  if (!Context.Verifying) {
405
1
    RejectLog &Log = Context.Log;
406
1
    std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...);
407
1
408
1
    if (PollyTrackFailures)
409
1
      Log.report(RejectReason);
410
1
411
1
    DEBUG(dbgs() << RejectReason->getMessage());
412
1
    DEBUG(dbgs() << "\n");
413
1
  } else {
414
0
    assert(!Assert && "Verification of detected scop failed");
415
0
  }
416
1
417
1
  return false;
418
1
}
419
420
1.33k
bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const {
421
1.33k
  if (!ValidRegions.count(&R))
422
955
    return false;
423
375
424
375
  if (Verify) {
425
375
    DetectionContextMap.erase(getBBPairForRegion(&R));
426
375
    const auto &It = DetectionContextMap.insert(std::make_pair(
427
375
        getBBPairForRegion(&R),
428
375
        DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/)));
429
375
    DetectionContext &Context = It.first->second;
430
375
    return isValidRegion(Context);
431
375
  }
432
0
433
0
  return true;
434
0
}
435
436
4
std::string ScopDetection::regionIsInvalidBecause(const Region *R) const {
437
4
  // Get the first error we found. Even in keep-going mode, this is the first
438
4
  // reason that caused the candidate to be rejected.
439
4
  auto *Log = lookupRejectionLog(R);
440
4
441
4
  // This can happen when we marked a region invalid, but didn't track
442
4
  // an error for it.
443
4
  if (!Log || 
!Log->hasErrors()3
)
444
4
    return "";
445
0
446
0
  RejectReasonPtr RR = *Log->begin();
447
0
  return RR->getMessage();
448
0
}
449
450
bool ScopDetection::addOverApproximatedRegion(Region *AR,
451
242
                                              DetectionContext &Context) const {
452
242
  // If we already know about Ar we can exit.
453
242
  if (!Context.NonAffineSubRegionSet.insert(AR))
454
14
    return true;
455
228
456
228
  // All loops in the region have to be overapproximated too if there
457
228
  // are accesses that depend on the iteration count.
458
228
459
521
  
for (BasicBlock *BB : AR->blocks()) 228
{
460
521
    Loop *L = LI.getLoopFor(BB);
461
521
    if (AR->contains(L))
462
68
      Context.BoxedLoopsSet.insert(L);
463
521
  }
464
228
465
228
  return (AllowNonAffineSubLoops || 
Context.BoxedLoopsSet.empty()199
);
466
242
}
467
468
bool ScopDetection::onlyValidRequiredInvariantLoads(
469
13.1k
    InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const {
470
13.1k
  Region &CurRegion = Context.CurRegion;
471
13.1k
  const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout();
472
13.1k
473
13.1k
  if (!PollyInvariantLoadHoisting && 
!RequiredILS.empty()11.9k
)
474
202
    return false;
475
12.9k
476
12.9k
  for (LoadInst *Load : RequiredILS) {
477
223
    // If we already know a load has been accepted as required invariant, we
478
223
    // already run the validation below once and consequently don't need to
479
223
    // run it again. Hence, we return early. For certain test cases (e.g.,
480
223
    // COSMO this avoids us spending 50% of scop-detection time in this
481
223
    // very function (and its children).
482
223
    if (Context.RequiredILS.count(Load))
483
119
      continue;
484
104
485
104
    if (!isHoistableLoad(Load, CurRegion, LI, SE, DT))
486
7
      return false;
487
97
488
97
    for (auto NonAffineRegion : Context.NonAffineSubRegionSet) {
489
0
      if (isSafeToLoadUnconditionally(Load->getPointerOperand(),
490
0
                                      Load->getAlignment(), DL))
491
0
        continue;
492
0
493
0
      if (NonAffineRegion->contains(Load) &&
494
0
          Load->getParent() != NonAffineRegion->getEntry())
495
0
        return false;
496
12.9k
    }
497
223
  }
498
12.9k
499
12.9k
  Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end());
500
12.9k
501
12.9k
  return true;
502
12.9k
}
503
504
bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1,
505
4.45k
                                         Loop *Scope) const {
506
4.45k
  SetVector<Value *> Values;
507
4.45k
  findValues(S0, SE, Values);
508
4.45k
  if (S1)
509
2.11k
    findValues(S1, SE, Values);
510
4.45k
511
4.45k
  SmallPtrSet<Value *, 8> PtrVals;
512
4.45k
  for (auto *V : Values) {
513
1.96k
    if (auto *P2I = dyn_cast<PtrToIntInst>(V))
514
2
      V = P2I->getOperand(0);
515
1.96k
516
1.96k
    if (!V->getType()->isPointerTy())
517
1.94k
      continue;
518
17
519
17
    auto *PtrSCEV = SE.getSCEVAtScope(V, Scope);
520
17
    if (isa<SCEVConstant>(PtrSCEV))
521
2
      continue;
522
15
523
15
    auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV));
524
15
    if (!BasePtr)
525
0
      return true;
526
15
527
15
    auto *BasePtrVal = BasePtr->getValue();
528
15
    if (PtrVals.insert(BasePtrVal).second) {
529
15
      for (auto *PtrVal : PtrVals)
530
15
        if (PtrVal != BasePtrVal && 
!AA.isNoAlias(PtrVal, BasePtrVal)0
)
531
0
          return true;
532
4.45k
    }
533
1.96k
  }
534
4.45k
535
4.45k
  return false;
536
4.45k
}
537
538
bool ScopDetection::isAffine(const SCEV *S, Loop *Scope,
539
13.5k
                             DetectionContext &Context) const {
540
13.5k
  InvariantLoadsSetTy AccessILS;
541
13.5k
  if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS))
542
351
    return false;
543
13.1k
544
13.1k
  if (!onlyValidRequiredInvariantLoads(AccessILS, Context))
545
209
    return false;
546
12.9k
547
12.9k
  return true;
548
12.9k
}
549
550
bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI,
551
                                  Value *Condition, bool IsLoopBranch,
552
13
                                  DetectionContext &Context) const {
553
13
  Loop *L = LI.getLoopFor(&BB);
554
13
  const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L);
555
13
556
13
  if (IsLoopBranch && 
L->isLoopLatch(&BB)1
)
557
1
    return false;
558
12
559
12
  // Check for invalid usage of different pointers in one expression.
560
12
  if (involvesMultiplePtrs(ConditionSCEV, nullptr, L))
561
0
    return false;
562
12
563
12
  if (isAffine(ConditionSCEV, L, Context))
564
12
    return true;
565
0
566
0
  if (AllowNonAffineSubRegions &&
567
0
      addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
568
0
    return true;
569
0
570
0
  return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB,
571
0
                                     ConditionSCEV, ConditionSCEV, SI);
572
0
}
573
574
bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI,
575
                                  Value *Condition, bool IsLoopBranch,
576
10.0k
                                  DetectionContext &Context) const {
577
10.0k
  // Constant integer conditions are always affine.
578
10.0k
  if (isa<ConstantInt>(Condition))
579
5.57k
    return true;
580
4.48k
581
4.48k
  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
582
11
    auto Opcode = BinOp->getOpcode();
583
11
    if (Opcode == Instruction::And || 
Opcode == Instruction::Or6
) {
584
11
      Value *Op0 = BinOp->getOperand(0);
585
11
      Value *Op1 = BinOp->getOperand(1);
586
11
      return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) &&
587
11
             isValidBranch(BB, BI, Op1, IsLoopBranch, Context);
588
11
    }
589
4.47k
  }
590
4.47k
591
4.47k
  if (auto PHI = dyn_cast<PHINode>(Condition)) {
592
4
    auto *Unique = dyn_cast_or_null<ConstantInt>(
593
4
        getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT));
594
4
    if (Unique && 
(0
Unique->isZero()0
||
Unique->isOne()0
))
595
0
      return true;
596
4.47k
  }
597
4.47k
598
4.47k
  if (auto Load = dyn_cast<LoadInst>(Condition))
599
0
    if (!IsLoopBranch && Context.CurRegion.contains(Load)) {
600
0
      Context.RequiredILS.insert(Load);
601
0
      return true;
602
0
    }
603
4.47k
604
4.47k
  // Non constant conditions of branches need to be ICmpInst.
605
4.47k
  if (!isa<ICmpInst>(Condition)) {
606
35
    if (!IsLoopBranch && AllowNonAffineSubRegions &&
607
35
        addOverApproximatedRegion(RI.getRegionFor(&BB), Context))
608
35
      return true;
609
0
    return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB);
610
0
  }
611
4.44k
612
4.44k
  ICmpInst *ICmp = cast<ICmpInst>(Condition);
613
4.44k
614
4.44k
  // Are both operands of the ICmp affine?
615
4.44k
  if (isa<UndefValue>(ICmp->getOperand(0)) ||
616
4.44k
      isa<UndefValue>(ICmp->getOperand(1)))
617
3
    return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp);
618
4.43k
619
4.43k
  Loop *L = LI.getLoopFor(&BB);
620
4.43k
  const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L);
621
4.43k
  const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L);
622
4.43k
623
4.43k
  LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT);
624
4.43k
  RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT);
625
4.43k
626
4.43k
  // If unsigned operations are not allowed try to approximate the region.
627
4.43k
  if (ICmp->isUnsigned() && 
!PollyAllowUnsignedOperations19
)
628
0
    return !IsLoopBranch && AllowNonAffineSubRegions &&
629
0
           addOverApproximatedRegion(RI.getRegionFor(&BB), Context);
630
4.43k
631
4.43k
  // Check for invalid usage of different pointers in one expression.
632
4.43k
  if (ICmp->isEquality() && 
involvesMultiplePtrs(LHS, nullptr, L)2.32k
&&
633
4.43k
      
involvesMultiplePtrs(RHS, nullptr, L)0
)
634
0
    return false;
635
4.43k
636
4.43k
  // Check for invalid usage of different pointers in a relational comparison.
637
4.43k
  if (ICmp->isRelational() && 
involvesMultiplePtrs(LHS, RHS, L)2.11k
)
638
0
    return false;
639
4.43k
640
4.43k
  if (isAffine(LHS, L, Context) && 
isAffine(RHS, L, Context)4.36k
)
641
4.21k
    return true;
642
225
643
225
  if (!IsLoopBranch && 
AllowNonAffineSubRegions188
&&
644
225
      
addOverApproximatedRegion(RI.getRegionFor(&BB), Context)188
)
645
185
    return true;
646
40
647
40
  if (IsLoopBranch)
648
37
    return false;
649
3
650
3
  return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS,
651
3
                                     ICmp);
652
3
}
653
654
bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch,
655
                               bool AllowUnreachable,
656
10.1k
                               DetectionContext &Context) const {
657
10.1k
  Region &CurRegion = Context.CurRegion;
658
10.1k
659
10.1k
  TerminatorInst *TI = BB.getTerminator();
660
10.1k
661
10.1k
  if (AllowUnreachable && 
isa<UnreachableInst>(TI)32
)
662
0
    return true;
663
10.1k
664
10.1k
  // Return instructions are only valid if the region is the top level region.
665
10.1k
  if (isa<ReturnInst>(TI) && 
CurRegion.isTopLevelRegion()0
)
666
0
    return true;
667
10.1k
668
10.1k
  Value *Condition = getConditionFromTerminator(TI);
669
10.1k
670
10.1k
  if (!Condition)
671
0
    return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB);
672
10.1k
673
10.1k
  // UndefValue is not allowed as condition.
674
10.1k
  if (isa<UndefValue>(Condition))
675
51
    return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB);
676
10.0k
677
10.0k
  if (BranchInst *BI = dyn_cast<BranchInst>(TI))
678
10.0k
    return isValidBranch(BB, BI, Condition, IsLoopBranch, Context);
679
13
680
13
  SwitchInst *SI = dyn_cast<SwitchInst>(TI);
681
13
  assert(SI && "Terminator was neither branch nor switch");
682
13
683
13
  return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context);
684
13
}
685
686
bool ScopDetection::isValidCallInst(CallInst &CI,
687
76
                                    DetectionContext &Context) const {
688
76
  if (CI.doesNotReturn())
689
0
    return false;
690
76
691
76
  if (CI.doesNotAccessMemory())
692
40
    return true;
693
36
694
36
  if (auto *II = dyn_cast<IntrinsicInst>(&CI))
695
28
    if (isValidIntrinsicInst(*II, Context))
696
24
      return true;
697
12
698
12
  Function *CalledFunction = CI.getCalledFunction();
699
12
700
12
  // Indirect calls are not supported.
701
12
  if (CalledFunction == nullptr)
702
0
    return false;
703
12
704
12
  if (AllowModrefCall) {
705
12
    switch (AA.getModRefBehavior(CalledFunction)) {
706
12
    case FMRB_UnknownModRefBehavior:
707
0
      return false;
708
12
    case FMRB_DoesNotAccessMemory:
709
6
    case FMRB_OnlyReadsMemory:
710
6
      // Implicitly disable delinearization since we have an unknown
711
6
      // accesses with an unknown access function.
712
6
      Context.HasUnknownAccess = true;
713
6
      Context.AST.add(&CI);
714
6
      return true;
715
6
    case FMRB_OnlyReadsArgumentPointees:
716
6
    case FMRB_OnlyAccessesArgumentPointees:
717
22
      for (const auto &Arg : CI.arg_operands()) {
718
22
        if (!Arg->getType()->isPointerTy())
719
14
          continue;
720
8
721
8
        // Bail if a pointer argument has a base address not known to
722
8
        // ScalarEvolution. Note that a zero pointer is acceptable.
723
8
        auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent()));
724
8
        if (ArgSCEV->isZero())
725
4
          continue;
726
4
727
4
        auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
728
4
        if (!BP)
729
0
          return false;
730
4
731
4
        // Implicitly disable delinearization since we have an unknown
732
4
        // accesses with an unknown access function.
733
4
        Context.HasUnknownAccess = true;
734
4
      }
735
6
736
6
      Context.AST.add(&CI);
737
6
      return true;
738
6
    case FMRB_DoesNotReadMemory:
739
0
    case FMRB_OnlyAccessesInaccessibleMem:
740
0
    case FMRB_OnlyAccessesInaccessibleOrArgMem:
741
0
      return false;
742
0
    }
743
0
  }
744
0
745
0
  return false;
746
0
}
747
748
bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II,
749
28
                                         DetectionContext &Context) const {
750
28
  if (isIgnoredIntrinsic(&II))
751
10
    return true;
752
18
753
18
  // The closest loop surrounding the call instruction.
754
18
  Loop *L = LI.getLoopFor(II.getParent());
755
18
756
18
  // The access function and base pointer for memory intrinsics.
757
18
  const SCEV *AF;
758
18
  const SCEVUnknown *BP;
759
18
760
18
  switch (II.getIntrinsicID()) {
761
18
  // Memory intrinsics that can be represented are supported.
762
18
  case Intrinsic::memmove:
763
12
  case Intrinsic::memcpy:
764
12
    AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L);
765
12
    if (!AF->isZero()) {
766
12
      BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
767
12
      // Bail if the source pointer is not valid.
768
12
      if (!isValidAccess(&II, AF, BP, Context))
769
0
        return false;
770
12
    }
771
12
  // Fall through
772
28
  case Intrinsic::memset:
773
28
    AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L);
774
28
    if (
!AF->isZero()16
) {
775
14
      BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF));
776
14
      // Bail if the destination pointer is not valid.
777
14
      if (!isValidAccess(&II, AF, BP, Context))
778
0
        return false;
779
16
    }
780
16
781
16
    // Bail if the length is not affine.
782
16
    if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L,
783
16
                  Context))
784
2
      return false;
785
14
786
14
    return true;
787
14
  default:
788
2
    break;
789
2
  }
790
2
791
2
  return false;
792
2
}
793
794
bool ScopDetection::isInvariant(Value &Val, const Region &Reg,
795
3.17k
                                DetectionContext &Ctx) const {
796
3.17k
  // A reference to function argument or constant value is invariant.
797
3.17k
  if (isa<Argument>(Val) || 
isa<Constant>(Val)1.01k
)
798
2.37k
    return true;
799
796
800
796
  Instruction *I = dyn_cast<Instruction>(&Val);
801
796
  if (!I)
802
0
    return false;
803
796
804
796
  if (!Reg.contains(I))
805
574
    return true;
806
222
807
222
  // Loads within the SCoP may read arbitrary values, need to hoist them. If it
808
222
  // is not hoistable, it will be rejected later, but here we assume it is and
809
222
  // that makes the value invariant.
810
222
  if (auto LI = dyn_cast<LoadInst>(I)) {
811
220
    Ctx.RequiredILS.insert(LI);
812
220
    return true;
813
220
  }
814
2
815
2
  return false;
816
2
}
817
818
namespace {
819
820
/// Remove smax of smax(0, size) expressions from a SCEV expression and
821
/// register the '...' components.
822
///
823
/// Array access expressions as they are generated by GFortran contain smax(0,
824
/// size) expressions that confuse the 'normal' delinearization algorithm.
825
/// However, if we extract such expressions before the normal delinearization
826
/// takes place they can actually help to identify array size expressions in
827
/// Fortran accesses. For the subsequently following delinearization the smax(0,
828
/// size) component can be replaced by just 'size'. This is correct as we will
829
/// always add and verify the assumption that for all subscript expressions
830
/// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify
831
/// that 0 <= size, which means smax(0, size) == size.
832
class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> {
833
public:
834
  SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms)
835
637
      : SCEVRewriteVisitor(SE), Terms(Terms) {}
836
837
  static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
838
637
                             std::vector<const SCEV *> *Terms = nullptr) {
839
637
    SCEVRemoveMax Rewriter(SE, Terms);
840
637
    return Rewriter.visit(Scev);
841
637
  }
842
843
4
  const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
844
4
    if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) {
845
4
      auto Res = visit(Expr->getOperand(1));
846
4
      if (Terms)
847
2
        (*Terms).push_back(Res);
848
4
      return Res;
849
4
    }
850
0
851
0
    return Expr;
852
0
  }
853
854
private:
855
  std::vector<const SCEV *> *Terms;
856
};
857
858
} // namespace
859
860
SmallVector<const SCEV *, 4>
861
ScopDetection::getDelinearizationTerms(DetectionContext &Context,
862
172
                                       const SCEVUnknown *BasePointer) const {
863
172
  SmallVector<const SCEV *, 4> Terms;
864
320
  for (const auto &Pair : Context.Accesses[BasePointer]) {
865
320
    std::vector<const SCEV *> MaxTerms;
866
320
    SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms);
867
320
    if (!MaxTerms.empty()) {
868
2
      Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end());
869
2
      continue;
870
2
    }
871
318
    // In case the outermost expression is a plain add, we check if any of its
872
318
    // terms has the form 4 * %inst * %param * %param ..., aka a term that
873
318
    // contains a product between a parameter and an instruction that is
874
318
    // inside the scop. Such instructions, if allowed at all, are instructions
875
318
    // SCEV can not represent, but Polly is still looking through. As a
876
318
    // result, these instructions can depend on induction variables and are
877
318
    // most likely no array sizes. However, terms that are multiplied with
878
318
    // them are likely candidates for array sizes.
879
318
    if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) {
880
5
      for (auto Op : AF->operands()) {
881
5
        if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op))
882
0
          SE.collectParametricTerms(AF2, Terms);
883
5
        if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) {
884
2
          SmallVector<const SCEV *, 0> Operands;
885
2
886
4
          for (auto *MulOp : AF2->operands()) {
887
4
            if (auto *Const = dyn_cast<SCEVConstant>(MulOp))
888
0
              Operands.push_back(Const);
889
4
            if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) {
890
2
              if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) {
891
0
                if (!Context.CurRegion.contains(Inst))
892
0
                  Operands.push_back(MulOp);
893
0
894
2
              } else {
895
2
                Operands.push_back(MulOp);
896
2
              }
897
2
            }
898
4
          }
899
2
          if (Operands.size())
900
1
            Terms.push_back(SE.getMulExpr(Operands));
901
2
        }
902
5
      }
903
2
    }
904
318
    if (Terms.empty())
905
183
      SE.collectParametricTerms(Pair.second, Terms);
906
320
  }
907
172
  return Terms;
908
172
}
909
910
bool ScopDetection::hasValidArraySizes(DetectionContext &Context,
911
                                       SmallVectorImpl<const SCEV *> &Sizes,
912
                                       const SCEVUnknown *BasePointer,
913
172
                                       Loop *Scope) const {
914
172
  // If no sizes were found, all sizes are trivially valid. We allow this case
915
172
  // to make it possible to pass known-affine accesses to the delinearization to
916
172
  // try to recover some interesting multi-dimensional accesses, but to still
917
172
  // allow the already known to be affine access in case the delinearization
918
172
  // fails. In such situations, the delinearization will just return a Sizes
919
172
  // array of size zero.
920
172
  if (Sizes.size() == 0)
921
20
    return true;
922
152
923
152
  Value *BaseValue = BasePointer->getValue();
924
152
  Region &CurRegion = Context.CurRegion;
925
515
  for (const SCEV *DelinearizedSize : Sizes) {
926
515
    if (!isAffine(DelinearizedSize, Scope, Context)) {
927
1
      Sizes.clear();
928
1
      break;
929
1
    }
930
514
    if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) {
931
350
      auto *V = dyn_cast<Value>(Unknown->getValue());
932
350
      if (auto *Load = dyn_cast<LoadInst>(V)) {
933
4
        if (Context.CurRegion.contains(Load) &&
934
4
            isHoistableLoad(Load, CurRegion, LI, SE, DT))
935
4
          Context.RequiredILS.insert(Load);
936
4
        continue;
937
4
      }
938
510
    }
939
510
    if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false,
940
510
                                  Context.RequiredILS))
941
0
      return invalid<ReportNonAffineAccess>(
942
0
          Context, /*Assert=*/true, DelinearizedSize,
943
0
          Context.Accesses[BasePointer].front().first, BaseValue);
944
152
  }
945
152
946
152
  // No array shape derived.
947
152
  if (Sizes.empty()) {
948
1
    if (AllowNonAffine)
949
0
      return true;
950
1
951
1
    for (const auto &Pair : Context.Accesses[BasePointer]) {
952
1
      const Instruction *Insn = Pair.first;
953
1
      const SCEV *AF = Pair.second;
954
1
955
1
      if (!isAffine(AF, Scope, Context)) {
956
1
        invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn,
957
1
                                       BaseValue);
958
1
        if (!KeepGoing)
959
1
          return false;
960
0
      }
961
1
    }
962
0
    return false;
963
0
  }
964
151
  return true;
965
151
}
966
967
// We first store the resulting memory accesses in TempMemoryAccesses. Only
968
// if the access functions for all memory accesses have been successfully
969
// delinearized we continue. Otherwise, we either report a failure or, if
970
// non-affine accesses are allowed, we drop the information. In case the
971
// information is dropped the memory accesses need to be overapproximated
972
// when translated to a polyhedral representation.
973
bool ScopDetection::computeAccessFunctions(
974
    DetectionContext &Context, const SCEVUnknown *BasePointer,
975
171
    std::shared_ptr<ArrayShape> Shape) const {
976
171
  Value *BaseValue = BasePointer->getValue();
977
171
  bool BasePtrHasNonAffine = false;
978
171
  MapInsnToMemAcc TempMemoryAccesses;
979
317
  for (const auto &Pair : Context.Accesses[BasePointer]) {
980
317
    const Instruction *Insn = Pair.first;
981
317
    auto *AF = Pair.second;
982
317
    AF = SCEVRemoveMax::rewrite(AF, SE);
983
317
    bool IsNonAffine = false;
984
317
    TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape)));
985
317
    MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second;
986
317
    auto *Scope = LI.getLoopFor(Insn->getParent());
987
317
988
317
    if (!AF) {
989
0
      if (isAffine(Pair.second, Scope, Context))
990
0
        Acc->DelinearizedSubscripts.push_back(Pair.second);
991
0
      else
992
0
        IsNonAffine = true;
993
317
    } else {
994
317
      if (Shape->DelinearizedSizes.size() == 0) {
995
26
        Acc->DelinearizedSubscripts.push_back(AF);
996
291
      } else {
997
291
        SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts,
998
291
                                  Shape->DelinearizedSizes);
999
291
        if (Acc->DelinearizedSubscripts.size() == 0)
1000
0
          IsNonAffine = true;
1001
291
      }
1002
317
      for (const SCEV *S : Acc->DelinearizedSubscripts)
1003
1.02k
        if (!isAffine(S, Scope, Context))
1004
26
          IsNonAffine = true;
1005
317
    }
1006
317
1007
317
    // (Possibly) report non affine access
1008
317
    if (IsNonAffine) {
1009
26
      BasePtrHasNonAffine = true;
1010
26
      if (!AllowNonAffine)
1011
7
        invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second,
1012
7
                                       Insn, BaseValue);
1013
26
      if (!KeepGoing && !AllowNonAffine)
1014
7
        return false;
1015
164
    }
1016
317
  }
1017
164
1018
164
  if (!BasePtrHasNonAffine)
1019
149
    Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(),
1020
149
                                TempMemoryAccesses.end());
1021
171
1022
171
  return true;
1023
171
}
1024
1025
bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context,
1026
                                          const SCEVUnknown *BasePointer,
1027
172
                                          Loop *Scope) const {
1028
172
  auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer));
1029
172
1030
172
  auto Terms = getDelinearizationTerms(Context, BasePointer);
1031
172
1032
172
  SE.findArrayDimensions(Terms, Shape->DelinearizedSizes,
1033
172
                         Context.ElementSize[BasePointer]);
1034
172
1035
172
  if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer,
1036
172
                          Scope))
1037
1
    return false;
1038
171
1039
171
  return computeAccessFunctions(Context, BasePointer, Shape);
1040
171
}
1041
1042
1.05k
bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const {
1043
1.05k
  // TODO: If we have an unknown access and other non-affine accesses we do
1044
1.05k
  //       not try to delinearize them for now.
1045
1.05k
  if (Context.HasUnknownAccess && 
!Context.NonAffineAccesses.empty()10
)
1046
4
    return AllowNonAffine;
1047
1.04k
1048
1.04k
  for (auto &Pair : Context.NonAffineAccesses) {
1049
172
    auto *BasePointer = Pair.first;
1050
172
    auto *Scope = Pair.second;
1051
172
    if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) {
1052
8
      if (KeepGoing)
1053
0
        continue;
1054
8
      else
1055
8
        return false;
1056
1.03k
    }
1057
172
  }
1058
1.03k
  return true;
1059
1.03k
}
1060
1061
bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF,
1062
                                  const SCEVUnknown *BP,
1063
3.17k
                                  DetectionContext &Context) const {
1064
3.17k
1065
3.17k
  if (!BP)
1066
0
    return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst);
1067
3.17k
1068
3.17k
  auto *BV = BP->getValue();
1069
3.17k
  if (isa<UndefValue>(BV))
1070
0
    return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst);
1071
3.17k
1072
3.17k
  // FIXME: Think about allowing IntToPtrInst
1073
3.17k
  if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV))
1074
0
    return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst);
1075
3.17k
1076
3.17k
  // Check that the base address of the access is invariant in the current
1077
3.17k
  // region.
1078
3.17k
  if (!isInvariant(*BV, Context.CurRegion, Context))
1079
2
    return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst);
1080
3.17k
1081
3.17k
  AF = SE.getMinusSCEV(AF, BP);
1082
3.17k
1083
3.17k
  const SCEV *Size;
1084
3.17k
  if (!isa<MemIntrinsic>(Inst)) {
1085
3.14k
    Size = SE.getElementSize(Inst);
1086
3.14k
  } else {
1087
26
    auto *SizeTy =
1088
26
        SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext()));
1089
26
    Size = SE.getConstant(SizeTy, 8);
1090
26
  }
1091
3.17k
1092
3.17k
  if (Context.ElementSize[BP]) {
1093
1.44k
    if (!AllowDifferentTypes && 
Context.ElementSize[BP] != Size0
)
1094
0
      return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true,
1095
0
                                                      Inst, BV);
1096
1.44k
1097
1.44k
    Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]);
1098
1.73k
  } else {
1099
1.73k
    Context.ElementSize[BP] = Size;
1100
1.73k
  }
1101
3.17k
1102
3.17k
  bool IsVariantInNonAffineLoop = false;
1103
3.17k
  SetVector<const Loop *> Loops;
1104
3.17k
  findLoops(AF, Loops);
1105
3.17k
  for (const Loop *L : Loops)
1106
3.17k
    
if (2.62k
Context.BoxedLoopsSet.count(L)2.62k
)
1107
15
      IsVariantInNonAffineLoop = true;
1108
3.17k
1109
3.17k
  auto *Scope = LI.getLoopFor(Inst->getParent());
1110
3.17k
  bool IsAffine = !IsVariantInNonAffineLoop && 
isAffine(AF, Scope, Context)3.15k
;
1111
3.17k
  // Do not try to delinearize memory intrinsics and force them to be affine.
1112
3.17k
  if (isa<MemIntrinsic>(Inst) && 
!IsAffine26
) {
1113
0
    return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1114
0
                                          BV);
1115
3.17k
  } else if (PollyDelinearize && 
!IsVariantInNonAffineLoop3.16k
) {
1116
3.15k
    Context.Accesses[BP].push_back({Inst, AF});
1117
3.15k
1118
3.15k
    if (!IsAffine || 
hasIVParams(AF)2.84k
)
1119
303
      Context.NonAffineAccesses.insert(
1120
303
          std::make_pair(BP, LI.getLoopFor(Inst->getParent())));
1121
3.15k
  } else 
if (21
!AllowNonAffine21
&&
!IsAffine9
) {
1122
5
    return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst,
1123
5
                                          BV);
1124
5
  }
1125
3.16k
1126
3.16k
  if (IgnoreAliasing)
1127
204
    return true;
1128
2.96k
1129
2.96k
  // Check if the base pointer of the memory access does alias with
1130
2.96k
  // any other pointer. This cannot be handled at the moment.
1131
2.96k
  AAMDNodes AATags;
1132
2.96k
  Inst->getAAMetadata(AATags);
1133
2.96k
  AliasSet &AS = Context.AST.getAliasSetForPointer(
1134
2.96k
      BP->getValue(), MemoryLocation::UnknownSize, AATags);
1135
2.96k
1136
2.96k
  if (!AS.isMustAlias()) {
1137
559
    if (PollyUseRuntimeAliasChecks) {
1138
559
      bool CanBuildRunTimeCheck = true;
1139
559
      // The run-time alias check places code that involves the base pointer at
1140
559
      // the beginning of the SCoP. This breaks if the base pointer is defined
1141
559
      // inside the scop. Hence, we can only create a run-time check if we are
1142
559
      // sure the base pointer is not an instruction defined inside the scop.
1143
559
      // However, we can ignore loads that will be hoisted.
1144
2.15k
      for (const auto &Ptr : AS) {
1145
2.15k
        Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue());
1146
2.15k
        if (Inst && 
Context.CurRegion.contains(Inst)1.27k
) {
1147
1.23k
          auto *Load = dyn_cast<LoadInst>(Inst);
1148
1.23k
          if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT)) {
1149
1.23k
            Context.RequiredILS.insert(Load);
1150
1.23k
            continue;
1151
1.23k
          }
1152
0
1153
0
          CanBuildRunTimeCheck = false;
1154
0
          break;
1155
0
        }
1156
2.15k
      }
1157
559
1158
559
      if (CanBuildRunTimeCheck)
1159
559
        return true;
1160
0
    }
1161
0
    return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS);
1162
0
  }
1163
2.40k
1164
2.40k
  return true;
1165
2.40k
}
1166
1167
bool ScopDetection::isValidMemoryAccess(MemAccInst Inst,
1168
3.14k
                                        DetectionContext &Context) const {
1169
3.14k
  Value *Ptr = Inst.getPointerOperand();
1170
3.14k
  Loop *L = LI.getLoopFor(Inst->getParent());
1171
3.14k
  const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L);
1172
3.14k
  const SCEVUnknown *BasePointer;
1173
3.14k
1174
3.14k
  BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
1175
3.14k
1176
3.14k
  return isValidAccess(Inst, AccessFunction, BasePointer, Context);
1177
3.14k
}
1178
1179
bool ScopDetection::isValidInstruction(Instruction &Inst,
1180
14.9k
                                       DetectionContext &Context) const {
1181
28.9k
  for (auto &Op : Inst.operands()) {
1182
28.9k
    auto *OpInst = dyn_cast<Instruction>(&Op);
1183
28.9k
1184
28.9k
    if (!OpInst)
1185
12.1k
      continue;
1186
16.7k
1187
16.7k
    if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) {
1188
0
      auto *PHI = dyn_cast<PHINode>(OpInst);
1189
0
      if (PHI) {
1190
0
        for (User *U : PHI->users()) {
1191
0
          if (!isa<TerminatorInst>(U))
1192
0
            return false;
1193
0
        }
1194
0
      } else {
1195
0
        return false;
1196
0
      }
1197
14.9k
    }
1198
28.9k
  }
1199
14.9k
1200
14.9k
  if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst))
1201
0
    return false;
1202
14.9k
1203
14.9k
  // We only check the call instruction but not invoke instruction.
1204
14.9k
  if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1205
76
    if (isValidCallInst(*CI, Context))
1206
76
      return true;
1207
0
1208
0
    return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst);
1209
0
  }
1210
14.8k
1211
14.8k
  if (!Inst.mayReadOrWriteMemory()) {
1212
11.7k
    if (!isa<AllocaInst>(Inst))
1213
11.7k
      return true;
1214
0
1215
0
    return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst);
1216
0
  }
1217
3.16k
1218
3.16k
  // Check the access function.
1219
3.16k
  if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
1220
3.14k
    Context.hasStores |= isa<StoreInst>(MemInst);
1221
3.14k
    Context.hasLoads |= isa<LoadInst>(MemInst);
1222
3.14k
    if (!MemInst.isSimple())
1223
0
      return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true,
1224
0
                                                  &Inst);
1225
3.14k
1226
3.14k
    return isValidMemoryAccess(MemInst, Context);
1227
3.14k
  }
1228
19
1229
19
  // We do not know this instruction, therefore we assume it is invalid.
1230
19
  return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst);
1231
19
}
1232
1233
/// Check whether @p L has exiting blocks.
1234
///
1235
/// @param L The loop of interest
1236
///
1237
/// @return True if the loop has exiting blocks, false otherwise.
1238
1.87k
static bool hasExitingBlocks(Loop *L) {
1239
1.87k
  SmallVector<BasicBlock *, 4> ExitingBlocks;
1240
1.87k
  L->getExitingBlocks(ExitingBlocks);
1241
1.87k
  return !ExitingBlocks.empty();
1242
1.87k
}
1243
1244
bool ScopDetection::canUseISLTripCount(Loop *L,
1245
1.87k
                                       DetectionContext &Context) const {
1246
1.87k
  // Ensure the loop has valid exiting blocks as well as latches, otherwise we
1247
1.87k
  // need to overapproximate it as a boxed loop.
1248
1.87k
  SmallVector<BasicBlock *, 4> LoopControlBlocks;
1249
1.87k
  L->getExitingBlocks(LoopControlBlocks);
1250
1.87k
  L->getLoopLatches(LoopControlBlocks);
1251
3.69k
  for (BasicBlock *ControlBB : LoopControlBlocks) {
1252
3.69k
    if (!isValidCFG(*ControlBB, true, false, Context))
1253
70
      return false;
1254
1.80k
  }
1255
1.80k
1256
1.80k
  // We can use ISL to compute the trip count of L.
1257
1.80k
  return true;
1258
1.80k
}
1259
1260
1.87k
bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const {
1261
1.87k
  // Loops that contain part but not all of the blocks of a region cannot be
1262
1.87k
  // handled by the schedule generation. Such loop constructs can happen
1263
1.87k
  // because a region can contain BBs that have no path to the exit block
1264
1.87k
  // (Infinite loops, UnreachableInst), but such blocks are never part of a
1265
1.87k
  // loop.
1266
1.87k
  //
1267
1.87k
  // _______________
1268
1.87k
  // | Loop Header | <-----------.
1269
1.87k
  // ---------------             |
1270
1.87k
  //        |                    |
1271
1.87k
  // _______________       ______________
1272
1.87k
  // | RegionEntry |-----> | RegionExit |----->
1273
1.87k
  // ---------------       --------------
1274
1.87k
  //        |
1275
1.87k
  // _______________
1276
1.87k
  // | EndlessLoop | <--.
1277
1.87k
  // ---------------    |
1278
1.87k
  //       |            |
1279
1.87k
  //       \------------/
1280
1.87k
  //
1281
1.87k
  // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is
1282
1.87k
  // neither entirely contained in the region RegionEntry->RegionExit
1283
1.87k
  // (containing RegionEntry,EndlessLoop) nor is the region entirely contained
1284
1.87k
  // in the loop.
1285
1.87k
  // The block EndlessLoop is contained in the region because Region::contains
1286
1.87k
  // tests whether it is not dominated by RegionExit. This is probably to not
1287
1.87k
  // having to query the PostdominatorTree. Instead of an endless loop, a dead
1288
1.87k
  // end can also be formed by an UnreachableInst. This case is already caught
1289
1.87k
  // by isErrorBlock(). We hence only have to reject endless loops here.
1290
1.87k
  if (!hasExitingBlocks(L))
1291
0
    return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L);
1292
1.87k
1293
1.87k
  if (canUseISLTripCount(L, Context))
1294
1.80k
    return true;
1295
70
1296
70
  if (AllowNonAffineSubLoops && 
AllowNonAffineSubRegions19
) {
1297
19
    Region *R = RI.getRegionFor(L->getHeader());
1298
24
    while (R != &Context.CurRegion && 
!R->contains(L)20
)
1299
19
      
R = R->getParent()5
;
1300
19
1301
19
    if (addOverApproximatedRegion(R, Context))
1302
19
      return true;
1303
51
  }
1304
51
1305
51
  const SCEV *LoopCount = SE.getBackedgeTakenCount(L);
1306
51
  return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount);
1307
51
}
1308
1309
/// Return the number of loops in @p L (incl. @p L) that have a trip
1310
///        count that is not known to be less than @MinProfitableTrips.
1311
ScopDetection::LoopStats
1312
ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE,
1313
1.29k
                                       unsigned MinProfitableTrips) {
1314
1.29k
  auto *TripCount = SE.getBackedgeTakenCount(L);
1315
1.29k
1316
1.29k
  int NumLoops = 1;
1317
1.29k
  int MaxLoopDepth = 1;
1318
1.29k
  if (MinProfitableTrips > 0)
1319
16
    if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount))
1320
8
      if (TripCountC->getType()->getScalarSizeInBits() <= 64)
1321
8
        if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips)
1322
4
          NumLoops -= 1;
1323
1.29k
1324
1.29k
  for (auto &SubLoop : *L) {
1325
394
    LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1326
394
    NumLoops += Stats.NumLoops;
1327
394
    MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1);
1328
394
  }
1329
1.29k
1330
1.29k
  return {NumLoops, MaxLoopDepth};
1331
1.29k
}
1332
1333
ScopDetection::LoopStats
1334
ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE,
1335
837
                                    LoopInfo &LI, unsigned MinProfitableTrips) {
1336
837
  int LoopNum = 0;
1337
837
  int MaxLoopDepth = 0;
1338
837
1339
837
  auto L = LI.getLoopFor(R->getEntry());
1340
837
1341
837
  // If L is fully contained in R, move to first loop surrounding R. Otherwise,
1342
837
  // L is either nullptr or already surrounding R.
1343
837
  if (L && 
R->contains(L)369
) {
1344
355
    L = R->outermostLoopInRegion(L);
1345
355
    L = L->getParentLoop();
1346
355
  }
1347
837
1348
837
  auto SubLoops =
1349
837
      L ? 
L->getSubLoopsVector()26
:
std::vector<Loop *>(LI.begin(), LI.end())811
;
1350
837
1351
837
  for (auto &SubLoop : SubLoops)
1352
926
    if (R->contains(SubLoop)) {
1353
904
      LoopStats Stats =
1354
904
          countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips);
1355
904
      LoopNum += Stats.NumLoops;
1356
904
      MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth);
1357
904
    }
1358
837
1359
837
  return {LoopNum, MaxLoopDepth};
1360
837
}
1361
1362
401
Region *ScopDetection::expandRegion(Region &R) {
1363
401
  // Initial no valid region was found (greater than R)
1364
401
  std::unique_ptr<Region> LastValidRegion;
1365
401
  auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion());
1366
401
1367
401
  DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n");
1368
401
1369
601
  while (ExpandedRegion) {
1370
217
    const auto &It = DetectionContextMap.insert(std::make_pair(
1371
217
        getBBPairForRegion(ExpandedRegion.get()),
1372
217
        DetectionContext(*ExpandedRegion, AA, false /*verifying*/)));
1373
217
    DetectionContext &Context = It.first->second;
1374
217
    DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n");
1375
217
    // Only expand when we did not collect errors.
1376
217
1377
217
    if (!Context.Log.hasErrors()) {
1378
217
      // If the exit is valid check all blocks
1379
217
      //  - if true, a valid region was found => store it + keep expanding
1380
217
      //  - if false, .tbd. => stop  (should this really end the loop?)
1381
217
      if (!allBlocksValid(Context) || 
Context.Log.hasErrors()200
) {
1382
17
        removeCachedResults(*ExpandedRegion);
1383
17
        DetectionContextMap.erase(It.first);
1384
17
        break;
1385
17
      }
1386
200
1387
200
      // Store this region, because it is the greatest valid (encountered so
1388
200
      // far).
1389
200
      if (LastValidRegion) {
1390
81
        removeCachedResults(*LastValidRegion);
1391
81
        DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get()));
1392
81
      }
1393
217
      LastValidRegion = std::move(ExpandedRegion);
1394
217
1395
217
      // Create and test the next greater region (if any)
1396
217
      ExpandedRegion =
1397
217
          std::unique_ptr<Region>(LastValidRegion->getExpandedRegion());
1398
217
1399
217
    } else {
1400
0
      // Create and test the next greater region (if any)
1401
0
      removeCachedResults(*ExpandedRegion);
1402
0
      DetectionContextMap.erase(It.first);
1403
0
      ExpandedRegion =
1404
0
          std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion());
1405
0
    }
1406
217
  }
1407
401
1408
401
  DEBUG({
1409
401
    if (LastValidRegion)
1410
401
      dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n";
1411
401
    else
1412
401
      dbgs() << "\tExpanding " << R.getNameStr() << " failed\n";
1413
401
  });
1414
401
1415
401
  return LastValidRegion.release();
1416
401
}
1417
1418
20
static bool regionWithoutLoops(Region &R, LoopInfo &LI) {
1419
20
  for (const BasicBlock *BB : R.blocks())
1420
22
    if (R.contains(LI.getLoopFor(BB)))
1421
20
      return false;
1422
0
1423
0
  return true;
1424
0
}
1425
1426
302
void ScopDetection::removeCachedResultsRecursively(const Region &R) {
1427
302
  for (auto &SubRegion : R) {
1428
248
    if (ValidRegions.count(SubRegion.get())) {
1429
65
      removeCachedResults(*SubRegion.get());
1430
65
    } else
1431
183
      removeCachedResultsRecursively(*SubRegion);
1432
248
  }
1433
302
}
1434
1435
848
void ScopDetection::removeCachedResults(const Region &R) {
1436
848
  ValidRegions.remove(&R);
1437
848
}
1438
1439
1.03k
void ScopDetection::findScops(Region &R) {
1440
1.03k
  const auto &It = DetectionContextMap.insert(std::make_pair(
1441
1.03k
      getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/)));
1442
1.03k
  DetectionContext &Context = It.first->second;
1443
1.03k
1444
1.03k
  bool RegionIsValid = false;
1445
1.03k
  if (!PollyProcessUnprofitable && 
regionWithoutLoops(R, LI)20
)
1446
0
    invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R);
1447
1.03k
  else
1448
1.03k
    RegionIsValid = isValidRegion(Context);
1449
1.03k
1450
1.03k
  bool HasErrors = !RegionIsValid || 
Context.Log.size() > 0465
;
1451
1.03k
1452
1.03k
  if (HasErrors) {
1453
566
    removeCachedResults(R);
1454
566
  } else {
1455
465
    ValidRegions.insert(&R);
1456
465
    return;
1457
465
  }
1458
566
1459
566
  for (auto &SubRegion : R)
1460
602
    findScops(*SubRegion);
1461
566
1462
566
  // Try to expand regions.
1463
566
  //
1464
566
  // As the region tree normally only contains canonical regions, non canonical
1465
566
  // regions that form a Scop are not found. Therefore, those non canonical
1466
566
  // regions are checked by expanding the canonical ones.
1467
566
1468
566
  std::vector<Region *> ToExpand;
1469
566
1470
566
  for (auto &SubRegion : R)
1471
602
    ToExpand.push_back(SubRegion.get());
1472
566
1473
602
  for (Region *CurrentRegion : ToExpand) {
1474
602
    // Skip invalid regions. Regions may become invalid, if they are element of
1475
602
    // an already expanded region.
1476
602
    if (!ValidRegions.count(CurrentRegion))
1477
201
      continue;
1478
401
1479
401
    // Skip regions that had errors.
1480
401
    bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors();
1481
401
    if (HadErrors)
1482
0
      continue;
1483
401
1484
401
    Region *ExpandedR = expandRegion(*CurrentRegion);
1485
401
1486
401
    if (!ExpandedR)
1487
282
      continue;
1488
119
1489
119
    R.addSubRegion(ExpandedR, true);
1490
119
    ValidRegions.insert(ExpandedR);
1491
119
    removeCachedResults(*CurrentRegion);
1492
119
    removeCachedResultsRecursively(*ExpandedR);
1493
119
  }
1494
1.03k
}
1495
1496
1.15k
bool ScopDetection::allBlocksValid(DetectionContext &Context) const {
1497
1.15k
  Region &CurRegion = Context.CurRegion;
1498
1.15k
1499
6.64k
  for (const BasicBlock *BB : CurRegion.blocks()) {
1500
6.64k
    Loop *L = LI.getLoopFor(BB);
1501
6.64k
    if (L && 
L->getHeader() == BB5.70k
) {
1502
1.88k
      if (CurRegion.contains(L)) {
1503
1.87k
        if (!isValidLoop(L, Context) && 
!KeepGoing51
)
1504
51
          return false;
1505
17
      } else {
1506
17
        SmallVector<BasicBlock *, 1> Latches;
1507
17
        L->getLoopLatches(Latches);
1508
17
        for (BasicBlock *Latch : Latches)
1509
22
          if (CurRegion.contains(Latch))
1510
3
            return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true,
1511
3
                                                      L);
1512
1.10k
      }
1513
1.88k
    }
1514
6.64k
  }
1515
1.10k
1516
6.40k
  
for (BasicBlock *BB : CurRegion.blocks()) 1.10k
{
1517
6.40k
    bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT);
1518
6.40k
1519
6.40k
    // Also check exception blocks (and possibly register them as non-affine
1520
6.40k
    // regions). Even though exception blocks are not modeled, we use them
1521
6.40k
    // to forward-propagate domain constraints during ScopInfo construction.
1522
6.40k
    if (!isValidCFG(*BB, false, IsErrorBlock, Context) && 
!KeepGoing25
)
1523
25
      return false;
1524
6.38k
1525
6.38k
    if (IsErrorBlock)
1526
32
      continue;
1527
6.34k
1528
21.2k
    
for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); 6.34k
I != E;
++I14.9k
)
1529
14.9k
      if (!isValidInstruction(*I, Context) && 
!KeepGoing26
)
1530
26
        return false;
1531
6.40k
  }
1532
1.10k
1533
1.10k
  
if (1.05k
!hasAffineMemoryAccesses(Context)1.05k
)
1534
10
    return false;
1535
1.04k
1536
1.04k
  return true;
1537
1.04k
}
1538
1539
bool ScopDetection::hasSufficientCompute(DetectionContext &Context,
1540
4
                                         int NumLoops) const {
1541
4
  int InstCount = 0;
1542
4
1543
4
  if (NumLoops == 0)
1544
0
    return false;
1545
4
1546
4
  for (auto *BB : Context.CurRegion.blocks())
1547
19
    if (Context.CurRegion.contains(LI.getLoopFor(BB)))
1548
19
      InstCount += BB->size();
1549
4
1550
4
  InstCount = InstCount / NumLoops;
1551
4
1552
4
  return InstCount >= ProfitabilityMinPerLoopInstructions;
1553
4
}
1554
1555
bool ScopDetection::hasPossiblyDistributableLoop(
1556
4
    DetectionContext &Context) const {
1557
4
  for (auto *BB : Context.CurRegion.blocks()) {
1558
4
    auto *L = LI.getLoopFor(BB);
1559
4
    if (!Context.CurRegion.contains(L))
1560
0
      continue;
1561
4
    if (Context.BoxedLoopsSet.count(L))
1562
0
      continue;
1563
4
    unsigned StmtsWithStoresInLoops = 0;
1564
19
    for (auto *LBB : L->blocks()) {
1565
19
      bool MemStore = false;
1566
19
      for (auto &I : *LBB)
1567
102
        MemStore |= isa<StoreInst>(&I);
1568
19
      StmtsWithStoresInLoops += MemStore;
1569
19
    }
1570
4
    return (StmtsWithStoresInLoops > 1);
1571
4
  }
1572
0
  return false;
1573
0
}
1574
1575
400
bool ScopDetection::isProfitableRegion(DetectionContext &Context) const {
1576
400
  Region &CurRegion = Context.CurRegion;
1577
400
1578
400
  if (PollyProcessUnprofitable)
1579
390
    return true;
1580
10
1581
10
  // We can probably not do a lot on scops that only write or only read
1582
10
  // data.
1583
10
  if (!Context.hasStores || 
!Context.hasLoads9
)
1584
2
    return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1585
8
1586
8
  int NumLoops =
1587
8
      countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops;
1588
8
  int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size();
1589
8
1590
8
  // Scops with at least two loops may allow either loop fusion or tiling and
1591
8
  // are consequently interesting to look at.
1592
8
  if (NumAffineLoops >= 2)
1593
2
    return true;
1594
6
1595
6
  // A loop with multiple non-trivial blocks might be amendable to distribution.
1596
6
  if (NumAffineLoops == 1 && 
hasPossiblyDistributableLoop(Context)4
)
1597
0
    return true;
1598
6
1599
6
  // Scops that contain a loop with a non-trivial amount of computation per
1600
6
  // loop-iteration are interesting as we may be able to parallelize such
1601
6
  // loops. Individual loops that have only a small amount of computation
1602
6
  // per-iteration are performance-wise very fragile as any change to the
1603
6
  // loop induction variables may affect performance. To not cause spurious
1604
6
  // performance regressions, we do not consider such loops.
1605
6
  if (NumAffineLoops == 1 && 
hasSufficientCompute(Context, NumLoops)4
)
1606
0
    return true;
1607
6
1608
6
  return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion);
1609
6
}
1610
1611
1.40k
bool ScopDetection::isValidRegion(DetectionContext &Context) const {
1612
1.40k
  Region &CurRegion = Context.CurRegion;
1613
1.40k
1614
1.40k
  DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t");
1615
1.40k
1616
1.40k
  if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) {
1617
429
    DEBUG(dbgs() << "Top level region is invalid\n");
1618
429
    return false;
1619
429
  }
1620
977
1621
977
  DebugLoc DbgLoc;
1622
977
  if (CurRegion.getExit() &&
1623
977
      isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) {
1624
12
    DEBUG(dbgs() << "Unreachable in exit\n");
1625
12
    return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true,
1626
12
                                            CurRegion.getExit(), DbgLoc);
1627
12
  }
1628
965
1629
965
  if (!CurRegion.getEntry()->getName().count(OnlyRegion)) {
1630
0
    DEBUG({
1631
0
      dbgs() << "Region entry does not match -polly-region-only";
1632
0
      dbgs() << "\n";
1633
0
    });
1634
0
    return false;
1635
0
  }
1636
965
1637
965
  // SCoP cannot contain the entry block of the function, because we need
1638
965
  // to insert alloca instruction there when translate scalar to array.
1639
965
  if (!PollyAllowFullFunction &&
1640
965
      CurRegion.getEntry() ==
1641
965
          &(CurRegion.getEntry()->getParent()->getEntryBlock()))
1642
27
    return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry());
1643
938
1644
938
  if (!allBlocksValid(Context))
1645
98
    return false;
1646
840
1647
840
  if (!isReducibleRegion(CurRegion, DbgLoc))
1648
1
    return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true,
1649
1
                                            &CurRegion, DbgLoc);
1650
839
1651
839
  DEBUG(dbgs() << "OK\n");
1652
839
  return true;
1653
839
}
1654
1655
0
void ScopDetection::markFunctionAsInvalid(Function *F) {
1656
0
  F->addFnAttr(PollySkipFnAttr);
1657
0
}
1658
1659
437
bool ScopDetection::isValidFunction(Function &F) {
1660
437
  return !F.hasFnAttribute(PollySkipFnAttr);
1661
437
}
1662
1663
0
void ScopDetection::printLocations(Function &F) {
1664
0
  for (const Region *R : *this) {
1665
0
    unsigned LineEntry, LineExit;
1666
0
    std::string FileName;
1667
0
1668
0
    getDebugLocation(R, LineEntry, LineExit, FileName);
1669
0
    DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit);
1670
0
    F.getContext().diagnose(Diagnostic);
1671
0
  }
1672
0
}
1673
1674
429
void ScopDetection::emitMissedRemarks(const Function &F) {
1675
1.15k
  for (auto &DIt : DetectionContextMap) {
1676
1.15k
    auto &DC = DIt.getSecond();
1677
1.15k
    if (DC.Log.hasErrors())
1678
143
      emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE);
1679
1.15k
  }
1680
429
}
1681
1682
840
bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const {
1683
840
  /// Enum for coloring BBs in Region.
1684
840
  ///
1685
840
  /// WHITE - Unvisited BB in DFS walk.
1686
840
  /// GREY - BBs which are currently on the DFS stack for processing.
1687
840
  /// BLACK - Visited and completely processed BB.
1688
840
  enum Color { WHITE, GREY, BLACK };
1689
840
1690
840
  BasicBlock *REntry = R.getEntry();
1691
840
  BasicBlock *RExit = R.getExit();
1692
840
  // Map to match the color of a BasicBlock during the DFS walk.
1693
840
  DenseMap<const BasicBlock *, Color> BBColorMap;
1694
840
  // Stack keeping track of current BB and index of next child to be processed.
1695
840
  std::stack<std::pair<BasicBlock *, unsigned>> DFSStack;
1696
840
1697
840
  unsigned AdjacentBlockIndex = 0;
1698
840
  BasicBlock *CurrBB, *SuccBB;
1699
840
  CurrBB = REntry;
1700
840
1701
840
  // Initialize the map for all BB with WHITE color.
1702
840
  for (auto *BB : R.blocks())
1703
3.83k
    BBColorMap[BB] = WHITE;
1704
840
1705
840
  // Process the entry block of the Region.
1706
840
  BBColorMap[CurrBB] = GREY;
1707
840
  DFSStack.push(std::make_pair(CurrBB, 0));
1708
840
1709
7.67k
  while (!DFSStack.empty()) {
1710
6.83k
    // Get next BB on stack to be processed.
1711
6.83k
    CurrBB = DFSStack.top().first;
1712
6.83k
    AdjacentBlockIndex = DFSStack.top().second;
1713
6.83k
    DFSStack.pop();
1714
6.83k
1715
6.83k
    // Loop to iterate over the successors of current BB.
1716
6.83k
    const TerminatorInst *TInst = CurrBB->getTerminator();
1717
6.83k
    unsigned NSucc = TInst->getNumSuccessors();
1718
9.20k
    for (unsigned I = AdjacentBlockIndex; I < NSucc;
1719
6.83k
         
++I, ++AdjacentBlockIndex2.36k
) {
1720
5.36k
      SuccBB = TInst->getSuccessor(I);
1721
5.36k
1722
5.36k
      // Checks for region exit block and self-loops in BB.
1723
5.36k
      if (SuccBB == RExit || 
SuccBB == CurrBB4.39k
)
1724
1.27k
        continue;
1725
4.09k
1726
4.09k
      // WHITE indicates an unvisited BB in DFS walk.
1727
4.09k
      if (BBColorMap[SuccBB] == WHITE) {
1728
2.99k
        // Push the current BB and the index of the next child to be visited.
1729
2.99k
        DFSStack.push(std::make_pair(CurrBB, I + 1));
1730
2.99k
        // Push the next BB to be processed.
1731
2.99k
        DFSStack.push(std::make_pair(SuccBB, 0));
1732
2.99k
        // First time the BB is being processed.
1733
2.99k
        BBColorMap[SuccBB] = GREY;
1734
2.99k
        break;
1735
2.99k
      } else 
if (1.09k
BBColorMap[SuccBB] == GREY1.09k
) {
1736
877
        // GREY indicates a loop in the control flow.
1737
877
        // If the destination dominates the source, it is a natural loop
1738
877
        // else, an irreducible control flow in the region is detected.
1739
877
        if (!DT.dominates(SuccBB, CurrBB)) {
1740
1
          // Get debug info of instruction which causes irregular control flow.
1741
1
          DbgLoc = TInst->getDebugLoc();
1742
1
          return false;
1743
1
        }
1744
1.09k
      }
1745
5.36k
    }
1746
6.83k
1747
6.83k
    // If all children of current BB have been processed,
1748
6.83k
    // then mark that BB as fully processed.
1749
6.83k
    
if (6.83k
AdjacentBlockIndex == NSucc6.83k
)
1750
3.83k
      BBColorMap[CurrBB] = BLACK;
1751
6.83k
  }
1752
840
1753
840
  
return true839
;
1754
840
}
1755
1756
static void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
1757
792
                                     bool OnlyProfitable) {
1758
792
  if (!OnlyProfitable) {
1759
400
    NumLoopsInScop += Stats.NumLoops;
1760
400
    MaxNumLoopsInScop =
1761
400
        std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
1762
400
    if (Stats.MaxDepth == 1)
1763
261
      NumScopsDepthOne++;
1764
139
    else if (Stats.MaxDepth == 2)
1765
80
      NumScopsDepthTwo++;
1766
59
    else if (Stats.MaxDepth == 3)
1767
31
      NumScopsDepthThree++;
1768
28
    else if (Stats.MaxDepth == 4)
1769
2
      NumScopsDepthFour++;
1770
26
    else if (Stats.MaxDepth == 5)
1771
0
      NumScopsDepthFive++;
1772
26
    else
1773
26
      NumScopsDepthLarger++;
1774
400
  } else {
1775
392
    NumLoopsInProfScop += Stats.NumLoops;
1776
392
    MaxNumLoopsInProfScop =
1777
392
        std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops);
1778
392
    if (Stats.MaxDepth == 1)
1779
257
      NumProfScopsDepthOne++;
1780
135
    else if (Stats.MaxDepth == 2)
1781
77
      NumProfScopsDepthTwo++;
1782
58
    else if (Stats.MaxDepth == 3)
1783
31
      NumProfScopsDepthThree++;
1784
27
    else if (Stats.MaxDepth == 4)
1785
1
      NumProfScopsDepthFour++;
1786
26
    else if (Stats.MaxDepth == 5)
1787
0
      NumProfScopsDepthFive++;
1788
26
    else
1789
26
      NumProfScopsDepthLarger++;
1790
392
  }
1791
792
}
1792
1793
ScopDetection::DetectionContext *
1794
778
ScopDetection::getDetectionContext(const Region *R) const {
1795
778
  auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R));
1796
778
  if (DCMIt == DetectionContextMap.end())
1797
1
    return nullptr;
1798
777
  return &DCMIt->second;
1799
777
}
1800
1801
405
const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const {
1802
405
  const DetectionContext *DC = getDetectionContext(R);
1803
405
  return DC ? 
&DC->Log404
:
nullptr1
;
1804
405
}
1805
1806
0
void ScopDetection::verifyRegion(const Region &R) const {
1807
0
  assert(isMaxRegionInScop(R) && "Expect R is a valid region.");
1808
0
1809
0
  DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/);
1810
0
  isValidRegion(Context);
1811
0
}
1812
1813
0
void ScopDetection::verifyAnalysis() const {
1814
0
  if (!VerifyScops)
1815
0
    return;
1816
0
1817
0
  for (const Region *R : ValidRegions)
1818
0
    verifyRegion(*R);
1819
0
}
1820
1821
438
bool ScopDetectionWrapperPass::runOnFunction(Function &F) {
1822
438
  auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1823
438
  auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo();
1824
438
  auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1825
438
  auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1826
438
  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1827
438
  auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1828
438
  Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE));
1829
438
  return false;
1830
438
}
1831
1832
400
void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1833
400
  AU.addRequired<LoopInfoWrapperPass>();
1834
400
  AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
1835
400
  AU.addRequired<DominatorTreeWrapperPass>();
1836
400
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1837
400
  // We also need AA and RegionInfo when we are verifying analysis.
1838
400
  AU.addRequiredTransitive<AAResultsWrapperPass>();
1839
400
  AU.addRequiredTransitive<RegionInfoPass>();
1840
400
  AU.setPreservesAll();
1841
400
}
1842
1843
36
void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const {
1844
36
  for (const Region *R : Result->ValidRegions)
1845
36
    
OS << "Valid Region for Scop: " << R->getNameStr() << '\n'18
;
1846
36
1847
36
  OS << "\n";
1848
36
}
1849
1850
400
ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) {
1851
400
  // Disable runtime alias checks if we ignore aliasing all together.
1852
400
  if (IgnoreAliasing)
1853
3
    PollyUseRuntimeAliasChecks = false;
1854
400
}
1855
1856
257
ScopAnalysis::ScopAnalysis() {
1857
257
  // Disable runtime alias checks if we ignore aliasing all together.
1858
257
  if (IgnoreAliasing)
1859
0
    PollyUseRuntimeAliasChecks = false;
1860
257
}
1861
1862
431
void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); }
1863
1864
char ScopDetectionWrapperPass::ID;
1865
1866
AnalysisKey ScopAnalysis::Key;
1867
1868
0
ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
1869
0
  auto &LI = FAM.getResult<LoopAnalysis>(F);
1870
0
  auto &RI = FAM.getResult<RegionInfoAnalysis>(F);
1871
0
  auto &AA = FAM.getResult<AAManager>(F);
1872
0
  auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
1873
0
  auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1874
0
  auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1875
0
  return {F, DT, SE, LI, RI, AA, ORE};
1876
0
}
1877
1878
PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F,
1879
0
                                               FunctionAnalysisManager &FAM) {
1880
0
  OS << "Detected Scops in Function " << F.getName() << "\n";
1881
0
  auto &SD = FAM.getResult<ScopAnalysis>(F);
1882
0
  for (const Region *R : SD.ValidRegions)
1883
0
    OS << "Valid Region for Scop: " << R->getNameStr() << '\n';
1884
0
1885
0
  OS << "\n";
1886
0
  return PreservedAnalyses::all();
1887
0
}
1888
1889
0
Pass *polly::createScopDetectionWrapperPassPass() {
1890
0
  return new ScopDetectionWrapperPass();
1891
0
}
1892
1893
17.2k
INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect",
1894
17.2k
                      "Polly - Detect static control parts (SCoPs)", false,
1895
17.2k
                      false);
1896
17.2k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
1897
17.2k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
1898
17.2k
INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1899
17.2k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1900
17.2k
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
1901
17.2k
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
1902
17.2k
INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect",
1903
                    "Polly - Detect static control parts (SCoPs)", false, false)