gokashi commited on
Commit
52119a9
·
verified ·
1 Parent(s): 71bbeb5

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. deps/exla/cache/xla_extension/include/llvm/Analysis/AliasAnalysisEvaluator.h +61 -0
  2. deps/exla/cache/xla_extension/include/llvm/Analysis/AssumptionCache.h +274 -0
  3. deps/exla/cache/xla_extension/include/llvm/Analysis/BlockFrequencyInfo.h +168 -0
  4. deps/exla/cache/xla_extension/include/llvm/Analysis/CFG.h +203 -0
  5. deps/exla/cache/xla_extension/include/llvm/Analysis/CGSCCPassManager.h +596 -0
  6. deps/exla/cache/xla_extension/include/llvm/Analysis/CallPrinter.h +43 -0
  7. deps/exla/cache/xla_extension/include/llvm/Analysis/CaptureTracking.h +200 -0
  8. deps/exla/cache/xla_extension/include/llvm/Analysis/ConstantFolding.h +231 -0
  9. deps/exla/cache/xla_extension/include/llvm/Analysis/CycleAnalysis.h +78 -0
  10. deps/exla/cache/xla_extension/include/llvm/Analysis/DDG.h +575 -0
  11. deps/exla/cache/xla_extension/include/llvm/Analysis/DDGPrinter.h +93 -0
  12. deps/exla/cache/xla_extension/include/llvm/Analysis/DOTGraphTraitsPass.h +342 -0
  13. deps/exla/cache/xla_extension/include/llvm/Analysis/DXILMetadataAnalysis.h +95 -0
  14. deps/exla/cache/xla_extension/include/llvm/Analysis/DependenceGraphBuilder.h +203 -0
  15. deps/exla/cache/xla_extension/include/llvm/Analysis/DomConditionCache.h +54 -0
  16. deps/exla/cache/xla_extension/include/llvm/Analysis/DominanceFrontierImpl.h +151 -0
  17. deps/exla/cache/xla_extension/include/llvm/Analysis/FloatingPointPredicateUtils.h +87 -0
  18. deps/exla/cache/xla_extension/include/llvm/Analysis/FunctionPropertiesAnalysis.h +201 -0
  19. deps/exla/cache/xla_extension/include/llvm/Analysis/GlobalsModRef.h +170 -0
  20. deps/exla/cache/xla_extension/include/llvm/Analysis/GuardUtils.h +69 -0
  21. deps/exla/cache/xla_extension/include/llvm/Analysis/HeatUtils.h +40 -0
  22. deps/exla/cache/xla_extension/include/llvm/Analysis/IndirectCallVisitor.h +97 -0
  23. deps/exla/cache/xla_extension/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h +47 -0
  24. deps/exla/cache/xla_extension/include/llvm/Analysis/InstCount.h +28 -0
  25. deps/exla/cache/xla_extension/include/llvm/Analysis/InstructionPrecedenceTracking.h +146 -0
  26. deps/exla/cache/xla_extension/include/llvm/Analysis/InstructionSimplify.h +305 -0
  27. deps/exla/cache/xla_extension/include/llvm/Analysis/InteractiveModelRunner.h +69 -0
  28. deps/exla/cache/xla_extension/include/llvm/Analysis/KernelInfo.h +35 -0
  29. deps/exla/cache/xla_extension/include/llvm/Analysis/LastRunTrackingAnalysis.h +109 -0
  30. deps/exla/cache/xla_extension/include/llvm/Analysis/LazyBlockFrequencyInfo.h +126 -0
  31. deps/exla/cache/xla_extension/include/llvm/Analysis/LazyValueInfo.h +185 -0
  32. deps/exla/cache/xla_extension/include/llvm/Analysis/LoopAccessAnalysis.h +979 -0
  33. deps/exla/cache/xla_extension/include/llvm/Analysis/LoopAnalysisManager.h +166 -0
  34. deps/exla/cache/xla_extension/include/llvm/Analysis/LoopCacheAnalysis.h +299 -0
  35. deps/exla/cache/xla_extension/include/llvm/Analysis/MemDerefPrinter.h +25 -0
  36. deps/exla/cache/xla_extension/include/llvm/Analysis/MemoryDependenceAnalysis.h +555 -0
  37. deps/exla/cache/xla_extension/include/llvm/Analysis/ModuleDebugInfoPrinter.h +30 -0
  38. deps/exla/cache/xla_extension/include/llvm/Analysis/NoInferenceModelRunner.h +36 -0
  39. deps/exla/cache/xla_extension/include/llvm/Analysis/ObjCARCAliasAnalysis.h +79 -0
  40. deps/exla/cache/xla_extension/include/llvm/Analysis/ObjCARCAnalysisUtils.h +273 -0
  41. deps/exla/cache/xla_extension/include/llvm/Analysis/PHITransAddr.h +125 -0
  42. deps/exla/cache/xla_extension/include/llvm/Analysis/PostDominators.h +118 -0
  43. deps/exla/cache/xla_extension/include/llvm/Analysis/PtrUseVisitor.h +317 -0
  44. deps/exla/cache/xla_extension/include/llvm/Analysis/RegionIterator.h +366 -0
  45. deps/exla/cache/xla_extension/include/llvm/Analysis/RegionPrinter.h +81 -0
  46. deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionDivision.h +73 -0
  47. deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionExpressions.h +963 -0
  48. deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionNormalization.h +74 -0
  49. deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionPatternMatch.h +244 -0
  50. deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarFuncs.def +117 -0
deps/exla/cache/xla_extension/include/llvm/Analysis/AliasAnalysisEvaluator.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- AliasAnalysisEvaluator.h - Alias Analysis Accuracy Evaluator -------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ ///
10
+ /// This file implements a simple N^2 alias analysis accuracy evaluator. The
11
+ /// analysis result is a set of statistics of how many times the AA
12
+ /// infrastructure provides each kind of alias result and mod/ref result when
13
+ /// queried with all pairs of pointers in the function.
14
+ ///
15
+ /// It can be used to evaluate a change in an alias analysis implementation,
16
+ /// algorithm, or the AA pipeline infrastructure itself. It acts like a stable
17
+ /// and easily tested consumer of all AA information exposed.
18
+ ///
19
+ /// This is inspired and adapted from code by: Naveen Neelakantam, Francesco
20
+ /// Spadini, and Wojciech Stryjewski.
21
+ ///
22
+ //===----------------------------------------------------------------------===//
23
+
24
+ #ifndef LLVM_ANALYSIS_ALIASANALYSISEVALUATOR_H
25
+ #define LLVM_ANALYSIS_ALIASANALYSISEVALUATOR_H
26
+
27
+ #include "llvm/IR/PassManager.h"
28
+ #include "llvm/Support/Compiler.h"
29
+
30
+ namespace llvm {
31
+ class AAResults;
32
+ class Function;
33
+
34
+ class AAEvaluator : public PassInfoMixin<AAEvaluator> {
35
+ int64_t FunctionCount = 0;
36
+ int64_t NoAliasCount = 0, MayAliasCount = 0, PartialAliasCount = 0;
37
+ int64_t MustAliasCount = 0;
38
+ int64_t NoModRefCount = 0, ModCount = 0, RefCount = 0, ModRefCount = 0;
39
+
40
+ public:
41
+ AAEvaluator() = default;
42
+ AAEvaluator(AAEvaluator &&Arg)
43
+ : FunctionCount(Arg.FunctionCount), NoAliasCount(Arg.NoAliasCount),
44
+ MayAliasCount(Arg.MayAliasCount),
45
+ PartialAliasCount(Arg.PartialAliasCount),
46
+ MustAliasCount(Arg.MustAliasCount), NoModRefCount(Arg.NoModRefCount),
47
+ ModCount(Arg.ModCount), RefCount(Arg.RefCount),
48
+ ModRefCount(Arg.ModRefCount) {
49
+ Arg.FunctionCount = 0;
50
+ }
51
+ LLVM_ABI ~AAEvaluator();
52
+
53
+ /// Run the pass over the function.
54
+ LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
55
+
56
+ private:
57
+ void runInternal(Function &F, AAResults &AA);
58
+ };
59
+ }
60
+
61
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/AssumptionCache.h ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/AssumptionCache.h - Track @llvm.assume -----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file contains a pass that keeps track of @llvm.assume intrinsics in
10
+ // the functions of a module (allowing assumptions within any function to be
11
+ // found cheaply by other parts of the optimizer).
12
+ //
13
+ //===----------------------------------------------------------------------===//
14
+
15
+ #ifndef LLVM_ANALYSIS_ASSUMPTIONCACHE_H
16
+ #define LLVM_ANALYSIS_ASSUMPTIONCACHE_H
17
+
18
+ #include "llvm/ADT/ArrayRef.h"
19
+ #include "llvm/ADT/DenseMap.h"
20
+ #include "llvm/ADT/DenseMapInfo.h"
21
+ #include "llvm/ADT/SmallVector.h"
22
+ #include "llvm/IR/PassManager.h"
23
+ #include "llvm/IR/ValueHandle.h"
24
+ #include "llvm/Pass.h"
25
+ #include "llvm/Support/Compiler.h"
26
+ #include <memory>
27
+
28
+ namespace llvm {
29
+
30
+ class AssumeInst;
31
+ class Function;
32
+ class raw_ostream;
33
+ class TargetTransformInfo;
34
+ class Value;
35
+
36
+ /// A cache of \@llvm.assume calls within a function.
37
+ ///
38
+ /// This cache provides fast lookup of assumptions within a function by caching
39
+ /// them and amortizing the cost of scanning for them across all queries. Passes
40
+ /// that create new assumptions are required to call registerAssumption() to
41
+ /// register any new \@llvm.assume calls that they create. Deletions of
42
+ /// \@llvm.assume calls do not require special handling.
43
+ class AssumptionCache {
44
+ public:
45
+ /// Value of ResultElem::Index indicating that the argument to the call of the
46
+ /// llvm.assume.
47
+ enum : unsigned { ExprResultIdx = std::numeric_limits<unsigned>::max() };
48
+
49
+ struct ResultElem {
50
+ WeakVH Assume;
51
+
52
+ /// contains either ExprResultIdx or the index of the operand bundle
53
+ /// containing the knowledge.
54
+ unsigned Index;
55
+ operator Value *() const { return Assume; }
56
+ };
57
+
58
+ private:
59
+ /// The function for which this cache is handling assumptions.
60
+ ///
61
+ /// We track this to lazily populate our assumptions.
62
+ Function &F;
63
+
64
+ TargetTransformInfo *TTI;
65
+
66
+ /// Vector of weak value handles to calls of the \@llvm.assume
67
+ /// intrinsic.
68
+ SmallVector<ResultElem, 4> AssumeHandles;
69
+
70
+ class LLVM_ABI AffectedValueCallbackVH final : public CallbackVH {
71
+ AssumptionCache *AC;
72
+
73
+ void deleted() override;
74
+ void allUsesReplacedWith(Value *) override;
75
+
76
+ public:
77
+ using DMI = DenseMapInfo<Value *>;
78
+
79
+ AffectedValueCallbackVH(Value *V, AssumptionCache *AC = nullptr)
80
+ : CallbackVH(V), AC(AC) {}
81
+ };
82
+
83
+ friend AffectedValueCallbackVH;
84
+
85
+ /// A map of values about which an assumption might be providing
86
+ /// information to the relevant set of assumptions.
87
+ using AffectedValuesMap =
88
+ DenseMap<AffectedValueCallbackVH, SmallVector<ResultElem, 1>,
89
+ AffectedValueCallbackVH::DMI>;
90
+ AffectedValuesMap AffectedValues;
91
+
92
+ /// Get the vector of assumptions which affect a value from the cache.
93
+ SmallVector<ResultElem, 1> &getOrInsertAffectedValues(Value *V);
94
+
95
+ /// Move affected values in the cache for OV to be affected values for NV.
96
+ void transferAffectedValuesInCache(Value *OV, Value *NV);
97
+
98
+ /// Flag tracking whether we have scanned the function yet.
99
+ ///
100
+ /// We want to be as lazy about this as possible, and so we scan the function
101
+ /// at the last moment.
102
+ bool Scanned = false;
103
+
104
+ /// Scan the function for assumptions and add them to the cache.
105
+ LLVM_ABI void scanFunction();
106
+
107
+ public:
108
+ /// Construct an AssumptionCache from a function by scanning all of
109
+ /// its instructions.
110
+ AssumptionCache(Function &F, TargetTransformInfo *TTI = nullptr)
111
+ : F(F), TTI(TTI) {}
112
+
113
+ /// This cache is designed to be self-updating and so it should never be
114
+ /// invalidated.
115
+ bool invalidate(Function &, const PreservedAnalyses &,
116
+ FunctionAnalysisManager::Invalidator &) {
117
+ return false;
118
+ }
119
+
120
+ /// Add an \@llvm.assume intrinsic to this function's cache.
121
+ ///
122
+ /// The call passed in must be an instruction within this function and must
123
+ /// not already be in the cache.
124
+ LLVM_ABI void registerAssumption(AssumeInst *CI);
125
+
126
+ /// Remove an \@llvm.assume intrinsic from this function's cache if it has
127
+ /// been added to the cache earlier.
128
+ LLVM_ABI void unregisterAssumption(AssumeInst *CI);
129
+
130
+ /// Update the cache of values being affected by this assumption (i.e.
131
+ /// the values about which this assumption provides information).
132
+ LLVM_ABI void updateAffectedValues(AssumeInst *CI);
133
+
134
+ /// Clear the cache of \@llvm.assume intrinsics for a function.
135
+ ///
136
+ /// It will be re-scanned the next time it is requested.
137
+ void clear() {
138
+ AssumeHandles.clear();
139
+ AffectedValues.clear();
140
+ Scanned = false;
141
+ }
142
+
143
+ /// Access the list of assumption handles currently tracked for this
144
+ /// function.
145
+ ///
146
+ /// Note that these produce weak handles that may be null. The caller must
147
+ /// handle that case.
148
+ /// FIXME: We should replace this with pointee_iterator<filter_iterator<...>>
149
+ /// when we can write that to filter out the null values. Then caller code
150
+ /// will become simpler.
151
+ MutableArrayRef<ResultElem> assumptions() {
152
+ if (!Scanned)
153
+ scanFunction();
154
+ return AssumeHandles;
155
+ }
156
+
157
+ /// Access the list of assumptions which affect this value.
158
+ MutableArrayRef<ResultElem> assumptionsFor(const Value *V) {
159
+ if (!Scanned)
160
+ scanFunction();
161
+
162
+ auto AVI = AffectedValues.find_as(const_cast<Value *>(V));
163
+ if (AVI == AffectedValues.end())
164
+ return MutableArrayRef<ResultElem>();
165
+
166
+ return AVI->second;
167
+ }
168
+ };
169
+
170
+ /// A function analysis which provides an \c AssumptionCache.
171
+ ///
172
+ /// This analysis is intended for use with the new pass manager and will vend
173
+ /// assumption caches for a given function.
174
+ class AssumptionAnalysis : public AnalysisInfoMixin<AssumptionAnalysis> {
175
+ friend AnalysisInfoMixin<AssumptionAnalysis>;
176
+
177
+ LLVM_ABI static AnalysisKey Key;
178
+
179
+ public:
180
+ using Result = AssumptionCache;
181
+
182
+ LLVM_ABI AssumptionCache run(Function &F, FunctionAnalysisManager &);
183
+ };
184
+
185
+ /// Printer pass for the \c AssumptionAnalysis results.
186
+ class AssumptionPrinterPass : public PassInfoMixin<AssumptionPrinterPass> {
187
+ raw_ostream &OS;
188
+
189
+ public:
190
+ explicit AssumptionPrinterPass(raw_ostream &OS) : OS(OS) {}
191
+
192
+ LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
193
+
194
+ static bool isRequired() { return true; }
195
+ };
196
+
197
+ /// An immutable pass that tracks lazily created \c AssumptionCache
198
+ /// objects.
199
+ ///
200
+ /// This is essentially a workaround for the legacy pass manager's weaknesses
201
+ /// which associates each assumption cache with Function and clears it if the
202
+ /// function is deleted. The nature of the AssumptionCache is that it is not
203
+ /// invalidated by any changes to the function body and so this is sufficient
204
+ /// to be conservatively correct.
205
+ class LLVM_ABI AssumptionCacheTracker : public ImmutablePass {
206
+ /// A callback value handle applied to function objects, which we use to
207
+ /// delete our cache of intrinsics for a function when it is deleted.
208
+ class LLVM_ABI FunctionCallbackVH final : public CallbackVH {
209
+ AssumptionCacheTracker *ACT;
210
+
211
+ void deleted() override;
212
+
213
+ public:
214
+ using DMI = DenseMapInfo<Value *>;
215
+
216
+ FunctionCallbackVH(Value *V, AssumptionCacheTracker *ACT = nullptr)
217
+ : CallbackVH(V), ACT(ACT) {}
218
+ };
219
+
220
+ friend FunctionCallbackVH;
221
+
222
+ using FunctionCallsMap =
223
+ DenseMap<FunctionCallbackVH, std::unique_ptr<AssumptionCache>,
224
+ FunctionCallbackVH::DMI>;
225
+
226
+ FunctionCallsMap AssumptionCaches;
227
+
228
+ public:
229
+ /// Get the cached assumptions for a function.
230
+ ///
231
+ /// If no assumptions are cached, this will scan the function. Otherwise, the
232
+ /// existing cache will be returned.
233
+ AssumptionCache &getAssumptionCache(Function &F);
234
+
235
+ /// Return the cached assumptions for a function if it has already been
236
+ /// scanned. Otherwise return nullptr.
237
+ AssumptionCache *lookupAssumptionCache(Function &F);
238
+
239
+ AssumptionCacheTracker();
240
+ ~AssumptionCacheTracker() override;
241
+
242
+ void releaseMemory() override {
243
+ verifyAnalysis();
244
+ AssumptionCaches.shrink_and_clear();
245
+ }
246
+
247
+ void verifyAnalysis() const override;
248
+
249
+ bool doFinalization(Module &) override {
250
+ verifyAnalysis();
251
+ return false;
252
+ }
253
+
254
+ static char ID; // Pass identification, replacement for typeid
255
+ };
256
+
257
+ template<> struct simplify_type<AssumptionCache::ResultElem> {
258
+ using SimpleType = Value *;
259
+
260
+ static SimpleType getSimplifiedValue(AssumptionCache::ResultElem &Val) {
261
+ return Val;
262
+ }
263
+ };
264
+ template<> struct simplify_type<const AssumptionCache::ResultElem> {
265
+ using SimpleType = /*const*/ Value *;
266
+
267
+ static SimpleType getSimplifiedValue(const AssumptionCache::ResultElem &Val) {
268
+ return Val;
269
+ }
270
+ };
271
+
272
+ } // end namespace llvm
273
+
274
+ #endif // LLVM_ANALYSIS_ASSUMPTIONCACHE_H
deps/exla/cache/xla_extension/include/llvm/Analysis/BlockFrequencyInfo.h ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- BlockFrequencyInfo.h - Block Frequency Analysis ----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // Loops should be simplified before this analysis.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFO_H
14
+ #define LLVM_ANALYSIS_BLOCKFREQUENCYINFO_H
15
+
16
+ #include "llvm/IR/PassManager.h"
17
+ #include "llvm/Pass.h"
18
+ #include "llvm/Support/BlockFrequency.h"
19
+ #include "llvm/Support/Compiler.h"
20
+ #include "llvm/Support/Printable.h"
21
+ #include <cstdint>
22
+ #include <memory>
23
+ #include <optional>
24
+
25
+ namespace llvm {
26
+
27
+ class BasicBlock;
28
+ class BranchProbabilityInfo;
29
+ class LoopInfo;
30
+ class Module;
31
+ class raw_ostream;
32
+ template <class BlockT> class BlockFrequencyInfoImpl;
33
+
34
+ enum PGOViewCountsType { PGOVCT_None, PGOVCT_Graph, PGOVCT_Text };
35
+
36
+ /// BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to
37
+ /// estimate IR basic block frequencies.
38
+ class BlockFrequencyInfo {
39
+ using ImplType = BlockFrequencyInfoImpl<BasicBlock>;
40
+
41
+ std::unique_ptr<ImplType> BFI;
42
+
43
+ public:
44
+ LLVM_ABI BlockFrequencyInfo();
45
+ LLVM_ABI BlockFrequencyInfo(const Function &F,
46
+ const BranchProbabilityInfo &BPI,
47
+ const LoopInfo &LI);
48
+ BlockFrequencyInfo(const BlockFrequencyInfo &) = delete;
49
+ BlockFrequencyInfo &operator=(const BlockFrequencyInfo &) = delete;
50
+ LLVM_ABI BlockFrequencyInfo(BlockFrequencyInfo &&Arg);
51
+ LLVM_ABI BlockFrequencyInfo &operator=(BlockFrequencyInfo &&RHS);
52
+ LLVM_ABI ~BlockFrequencyInfo();
53
+
54
+ /// Handle invalidation explicitly.
55
+ LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
56
+ FunctionAnalysisManager::Invalidator &);
57
+
58
+ LLVM_ABI const Function *getFunction() const;
59
+ LLVM_ABI const BranchProbabilityInfo *getBPI() const;
60
+ LLVM_ABI void view(StringRef = "BlockFrequencyDAGs") const;
61
+
62
+ /// getblockFreq - Return block frequency. Return 0 if we don't have the
63
+ /// information. Please note that initial frequency is equal to ENTRY_FREQ. It
64
+ /// means that we should not rely on the value itself, but only on the
65
+ /// comparison to the other block frequencies. We do this to avoid using of
66
+ /// floating points.
67
+ LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const;
68
+
69
+ /// Returns the estimated profile count of \p BB.
70
+ /// This computes the relative block frequency of \p BB and multiplies it by
71
+ /// the enclosing function's count (if available) and returns the value.
72
+ LLVM_ABI std::optional<uint64_t>
73
+ getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic = false) const;
74
+
75
+ /// Returns the estimated profile count of \p Freq.
76
+ /// This uses the frequency \p Freq and multiplies it by
77
+ /// the enclosing function's count (if available) and returns the value.
78
+ LLVM_ABI std::optional<uint64_t>
79
+ getProfileCountFromFreq(BlockFrequency Freq) const;
80
+
81
+ /// Returns true if \p BB is an irreducible loop header
82
+ /// block. Otherwise false.
83
+ LLVM_ABI bool isIrrLoopHeader(const BasicBlock *BB);
84
+
85
+ // Set the frequency of the given basic block.
86
+ LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq);
87
+
88
+ /// Set the frequency of \p ReferenceBB to \p Freq and scale the frequencies
89
+ /// of the blocks in \p BlocksToScale such that their frequencies relative
90
+ /// to \p ReferenceBB remain unchanged.
91
+ LLVM_ABI void
92
+ setBlockFreqAndScale(const BasicBlock *ReferenceBB, BlockFrequency Freq,
93
+ SmallPtrSetImpl<BasicBlock *> &BlocksToScale);
94
+
95
+ /// calculate - compute block frequency info for the given function.
96
+ LLVM_ABI void calculate(const Function &F, const BranchProbabilityInfo &BPI,
97
+ const LoopInfo &LI);
98
+
99
+ LLVM_ABI BlockFrequency getEntryFreq() const;
100
+ LLVM_ABI void releaseMemory();
101
+ LLVM_ABI void print(raw_ostream &OS) const;
102
+
103
+ // Compare to the other BFI and verify they match.
104
+ LLVM_ABI void verifyMatch(BlockFrequencyInfo &Other) const;
105
+ };
106
+
107
+ /// Print the block frequency @p Freq relative to the current functions entry
108
+ /// frequency. Returns a Printable object that can be piped via `<<` to a
109
+ /// `raw_ostream`.
110
+ LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI,
111
+ BlockFrequency Freq);
112
+
113
+ /// Convenience function equivalent to calling
114
+ /// `printBlockFreq(BFI, BFI.getBlocakFreq(&BB))`.
115
+ LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI,
116
+ const BasicBlock &BB);
117
+
118
+ /// Analysis pass which computes \c BlockFrequencyInfo.
119
+ class BlockFrequencyAnalysis
120
+ : public AnalysisInfoMixin<BlockFrequencyAnalysis> {
121
+ friend AnalysisInfoMixin<BlockFrequencyAnalysis>;
122
+
123
+ LLVM_ABI static AnalysisKey Key;
124
+
125
+ public:
126
+ /// Provide the result type for this analysis pass.
127
+ using Result = BlockFrequencyInfo;
128
+
129
+ /// Run the analysis pass over a function and produce BFI.
130
+ LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM);
131
+ };
132
+
133
+ /// Printer pass for the \c BlockFrequencyInfo results.
134
+ class BlockFrequencyPrinterPass
135
+ : public PassInfoMixin<BlockFrequencyPrinterPass> {
136
+ raw_ostream &OS;
137
+
138
+ public:
139
+ explicit BlockFrequencyPrinterPass(raw_ostream &OS) : OS(OS) {}
140
+
141
+ LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
142
+
143
+ static bool isRequired() { return true; }
144
+ };
145
+
146
+ /// Legacy analysis pass which computes \c BlockFrequencyInfo.
147
+ class LLVM_ABI BlockFrequencyInfoWrapperPass : public FunctionPass {
148
+ BlockFrequencyInfo BFI;
149
+
150
+ public:
151
+ static char ID;
152
+
153
+ BlockFrequencyInfoWrapperPass();
154
+ ~BlockFrequencyInfoWrapperPass() override;
155
+
156
+ BlockFrequencyInfo &getBFI() { return BFI; }
157
+ const BlockFrequencyInfo &getBFI() const { return BFI; }
158
+
159
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
160
+
161
+ bool runOnFunction(Function &F) override;
162
+ void releaseMemory() override;
163
+ void print(raw_ostream &OS, const Module *M) const override;
164
+ };
165
+
166
+ } // end namespace llvm
167
+
168
+ #endif // LLVM_ANALYSIS_BLOCKFREQUENCYINFO_H
deps/exla/cache/xla_extension/include/llvm/Analysis/CFG.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- Analysis/CFG.h - BasicBlock Analyses --------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This family of functions performs analyses on basic blocks, and instructions
10
+ // contained within basic blocks.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_CFG_H
15
+ #define LLVM_ANALYSIS_CFG_H
16
+
17
+ #include "llvm/ADT/GraphTraits.h"
18
+ #include "llvm/ADT/SmallPtrSet.h"
19
+ #include "llvm/Support/Compiler.h"
20
+ #include <utility>
21
+
22
+ namespace llvm {
23
+
24
+ class BasicBlock;
25
+ class DominatorTree;
26
+ class Function;
27
+ class Instruction;
28
+ class LoopInfo;
29
+ template <typename T> class SmallVectorImpl;
30
+
31
+ /// Analyze the specified function to find all of the loop backedges in the
32
+ /// function and return them. This is a relatively cheap (compared to
33
+ /// computing dominators and loop info) analysis.
34
+ ///
35
+ /// The output is added to Result, as pairs of <from,to> edge info.
36
+ LLVM_ABI void FindFunctionBackedges(
37
+ const Function &F,
38
+ SmallVectorImpl<std::pair<const BasicBlock *, const BasicBlock *>> &Result);
39
+
40
+ /// Search for the specified successor of basic block BB and return its position
41
+ /// in the terminator instruction's list of successors. It is an error to call
42
+ /// this with a block that is not a successor.
43
+ LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB,
44
+ const BasicBlock *Succ);
45
+
46
+ /// Return true if the specified edge is a critical edge. Critical edges are
47
+ /// edges from a block with multiple successors to a block with multiple
48
+ /// predecessors.
49
+ ///
50
+ LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum,
51
+ bool AllowIdenticalEdges = false);
52
+ LLVM_ABI bool isCriticalEdge(const Instruction *TI, const BasicBlock *Succ,
53
+ bool AllowIdenticalEdges = false);
54
+
55
+ /// Determine whether instruction 'To' is reachable from 'From', without passing
56
+ /// through any blocks in ExclusionSet, returning true if uncertain.
57
+ ///
58
+ /// Determine whether there is a path from From to To within a single function.
59
+ /// Returns false only if we can prove that once 'From' has been executed then
60
+ /// 'To' can not be executed. Conservatively returns true.
61
+ ///
62
+ /// This function is linear with respect to the number of blocks in the CFG,
63
+ /// walking down successors from From to reach To, with a fixed threshold.
64
+ /// Using DT or LI allows us to answer more quickly. LI reduces the cost of
65
+ /// an entire loop of any number of blocks to be the same as the cost of a
66
+ /// single block. DT reduces the cost by allowing the search to terminate when
67
+ /// we find a block that dominates the block containing 'To'. DT is most useful
68
+ /// on branchy code but not loops, and LI is most useful on code with loops but
69
+ /// does not help on branchy code outside loops.
70
+ LLVM_ABI bool isPotentiallyReachable(
71
+ const Instruction *From, const Instruction *To,
72
+ const SmallPtrSetImpl<BasicBlock *> *ExclusionSet = nullptr,
73
+ const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
74
+
75
+ /// Determine whether block 'To' is reachable from 'From', returning
76
+ /// true if uncertain.
77
+ ///
78
+ /// Determine whether there is a path from From to To within a single function.
79
+ /// Returns false only if we can prove that once 'From' has been reached then
80
+ /// 'To' can not be executed. Conservatively returns true.
81
+ LLVM_ABI bool isPotentiallyReachable(
82
+ const BasicBlock *From, const BasicBlock *To,
83
+ const SmallPtrSetImpl<BasicBlock *> *ExclusionSet = nullptr,
84
+ const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
85
+
86
+ /// Determine whether there is at least one path from a block in
87
+ /// 'Worklist' to 'StopBB' without passing through any blocks in
88
+ /// 'ExclusionSet', returning true if uncertain.
89
+ ///
90
+ /// Determine whether there is a path from at least one block in Worklist to
91
+ /// StopBB within a single function without passing through any of the blocks
92
+ /// in 'ExclusionSet'. Returns false only if we can prove that once any block
93
+ /// in 'Worklist' has been reached then 'StopBB' can not be executed.
94
+ /// Conservatively returns true.
95
+ LLVM_ABI bool isPotentiallyReachableFromMany(
96
+ SmallVectorImpl<BasicBlock *> &Worklist, const BasicBlock *StopBB,
97
+ const SmallPtrSetImpl<BasicBlock *> *ExclusionSet,
98
+ const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
99
+
100
+ /// Determine whether there is a potentially a path from at least one block in
101
+ /// 'Worklist' to at least one block in 'StopSet' within a single function
102
+ /// without passing through any of the blocks in 'ExclusionSet'. Returns false
103
+ /// only if we can prove that once any block in 'Worklist' has been reached then
104
+ /// no blocks in 'StopSet' can be executed without passing through any blocks in
105
+ /// 'ExclusionSet'. Conservatively returns true.
106
+ LLVM_ABI bool isManyPotentiallyReachableFromMany(
107
+ SmallVectorImpl<BasicBlock *> &Worklist,
108
+ const SmallPtrSetImpl<const BasicBlock *> &StopSet,
109
+ const SmallPtrSetImpl<BasicBlock *> *ExclusionSet,
110
+ const DominatorTree *DT = nullptr, const LoopInfo *LI = nullptr);
111
+
112
+ /// Return true if the control flow in \p RPOTraversal is irreducible.
113
+ ///
114
+ /// This is a generic implementation to detect CFG irreducibility based on loop
115
+ /// info analysis. It can be used for any kind of CFG (Loop, MachineLoop,
116
+ /// Function, MachineFunction, etc.) by providing an RPO traversal (\p
117
+ /// RPOTraversal) and the loop info analysis (\p LI) of the CFG. This utility
118
+ /// function is only recommended when loop info analysis is available. If loop
119
+ /// info analysis isn't available, please, don't compute it explicitly for this
120
+ /// purpose. There are more efficient ways to detect CFG irreducibility that
121
+ /// don't require recomputing loop info analysis (e.g., T1/T2 or Tarjan's
122
+ /// algorithm).
123
+ ///
124
+ /// Requirements:
125
+ /// 1) GraphTraits must be implemented for NodeT type. It is used to access
126
+ /// NodeT successors.
127
+ // 2) \p RPOTraversal must be a valid reverse post-order traversal of the
128
+ /// target CFG with begin()/end() iterator interfaces.
129
+ /// 3) \p LI must be a valid LoopInfoBase that contains up-to-date loop
130
+ /// analysis information of the CFG.
131
+ ///
132
+ /// This algorithm uses the information about reducible loop back-edges already
133
+ /// computed in \p LI. When a back-edge is found during the RPO traversal, the
134
+ /// algorithm checks whether the back-edge is one of the reducible back-edges in
135
+ /// loop info. If it isn't, the CFG is irreducible. For example, for the CFG
136
+ /// below (canonical irreducible graph) loop info won't contain any loop, so the
137
+ /// algorithm will return that the CFG is irreducible when checking the B <-
138
+ /// -> C back-edge.
139
+ ///
140
+ /// (A->B, A->C, B->C, C->B, C->D)
141
+ /// A
142
+ /// / \
143
+ /// B<- ->C
144
+ /// |
145
+ /// D
146
+ ///
147
+ template <class NodeT, class RPOTraversalT, class LoopInfoT,
148
+ class GT = GraphTraits<NodeT>>
149
+ bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI) {
150
+ /// Check whether the edge (\p Src, \p Dst) is a reducible loop backedge
151
+ /// according to LI. I.e., check if there exists a loop that contains Src and
152
+ /// where Dst is the loop header.
153
+ auto isProperBackedge = [&](NodeT Src, NodeT Dst) {
154
+ for (const auto *Lp = LI.getLoopFor(Src); Lp; Lp = Lp->getParentLoop()) {
155
+ if (Lp->getHeader() == Dst)
156
+ return true;
157
+ }
158
+ return false;
159
+ };
160
+
161
+ SmallPtrSet<NodeT, 32> Visited;
162
+ for (NodeT Node : RPOTraversal) {
163
+ Visited.insert(Node);
164
+ for (NodeT Succ : make_range(GT::child_begin(Node), GT::child_end(Node))) {
165
+ // Succ hasn't been visited yet
166
+ if (!Visited.count(Succ))
167
+ continue;
168
+ // We already visited Succ, thus Node->Succ must be a backedge. Check that
169
+ // the head matches what we have in the loop information. Otherwise, we
170
+ // have an irreducible graph.
171
+ if (!isProperBackedge(Node, Succ))
172
+ return true;
173
+ }
174
+ }
175
+
176
+ return false;
177
+ }
178
+
179
+ // Returns true if these basic blocks belong to a presplit coroutine and the
180
+ // edge corresponds to the 'default' case in the switch statement in the
181
+ // pattern:
182
+ //
183
+ // %0 = call i8 @llvm.coro.suspend(token none, i1 false)
184
+ // switch i8 %0, label %suspend [i8 0, label %resume
185
+ // i8 1, label %cleanup]
186
+ //
187
+ // i.e. the edge to the `%suspend` BB. This edge is special in that it will
188
+ // be elided by coroutine lowering (coro-split), and the `%suspend` BB needs
189
+ // to be kept as-is. It's not a real CFG edge - post-lowering, it will end
190
+ // up being a `ret`, and it must be thus lowerable to support symmetric
191
+ // transfer. For example:
192
+ // - this edge is not a loop exit edge if encountered in a loop (and should
193
+ // be ignored)
194
+ // - must not be split for PGO instrumentation, for example.
195
+ LLVM_ABI bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src,
196
+ const BasicBlock &Dest);
197
+
198
+ /// Return true if there is at least a path through which F can return, false if
199
+ /// there is no such path.
200
+ LLVM_ABI bool canReturn(const Function &F);
201
+ } // namespace llvm
202
+
203
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/CGSCCPassManager.h ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- CGSCCPassManager.h - Call graph pass management ----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ ///
10
+ /// This header provides classes for managing passes over SCCs of the call
11
+ /// graph. These passes form an important component of LLVM's interprocedural
12
+ /// optimizations. Because they operate on the SCCs of the call graph, and they
13
+ /// traverse the graph in post-order, they can effectively do pair-wise
14
+ /// interprocedural optimizations for all call edges in the program while
15
+ /// incrementally refining it and improving the context of these pair-wise
16
+ /// optimizations. At each call site edge, the callee has already been
17
+ /// optimized as much as is possible. This in turn allows very accurate
18
+ /// analysis of it for IPO.
19
+ ///
20
+ /// A secondary more general goal is to be able to isolate optimization on
21
+ /// unrelated parts of the IR module. This is useful to ensure our
22
+ /// optimizations are principled and don't miss oportunities where refinement
23
+ /// of one part of the module influences transformations in another part of the
24
+ /// module. But this is also useful if we want to parallelize the optimizations
25
+ /// across common large module graph shapes which tend to be very wide and have
26
+ /// large regions of unrelated cliques.
27
+ ///
28
+ /// To satisfy these goals, we use the LazyCallGraph which provides two graphs
29
+ /// nested inside each other (and built lazily from the bottom-up): the call
30
+ /// graph proper, and a reference graph. The reference graph is super set of
31
+ /// the call graph and is a conservative approximation of what could through
32
+ /// scalar or CGSCC transforms *become* the call graph. Using this allows us to
33
+ /// ensure we optimize functions prior to them being introduced into the call
34
+ /// graph by devirtualization or other technique, and thus ensures that
35
+ /// subsequent pair-wise interprocedural optimizations observe the optimized
36
+ /// form of these functions. The (potentially transitive) reference
37
+ /// reachability used by the reference graph is a conservative approximation
38
+ /// that still allows us to have independent regions of the graph.
39
+ ///
40
+ /// FIXME: There is one major drawback of the reference graph: in its naive
41
+ /// form it is quadratic because it contains a distinct edge for each
42
+ /// (potentially indirect) reference, even if are all through some common
43
+ /// global table of function pointers. This can be fixed in a number of ways
44
+ /// that essentially preserve enough of the normalization. While it isn't
45
+ /// expected to completely preclude the usability of this, it will need to be
46
+ /// addressed.
47
+ ///
48
+ ///
49
+ /// All of these issues are made substantially more complex in the face of
50
+ /// mutations to the call graph while optimization passes are being run. When
51
+ /// mutations to the call graph occur we want to achieve two different things:
52
+ ///
53
+ /// - We need to update the call graph in-flight and invalidate analyses
54
+ /// cached on entities in the graph. Because of the cache-based analysis
55
+ /// design of the pass manager, it is essential to have stable identities for
56
+ /// the elements of the IR that passes traverse, and to invalidate any
57
+ /// analyses cached on these elements as the mutations take place.
58
+ ///
59
+ /// - We want to preserve the incremental and post-order traversal of the
60
+ /// graph even as it is refined and mutated. This means we want optimization
61
+ /// to observe the most refined form of the call graph and to do so in
62
+ /// post-order.
63
+ ///
64
+ /// To address this, the CGSCC manager uses both worklists that can be expanded
65
+ /// by passes which transform the IR, and provides invalidation tests to skip
66
+ /// entries that become dead. This extra data is provided to every SCC pass so
67
+ /// that it can carefully update the manager's traversal as the call graph
68
+ /// mutates.
69
+ ///
70
+ /// We also provide support for running function passes within the CGSCC walk,
71
+ /// and there we provide automatic update of the call graph including of the
72
+ /// pass manager to reflect call graph changes that fall out naturally as part
73
+ /// of scalar transformations.
74
+ ///
75
+ /// The patterns used to ensure the goals of post-order visitation of the fully
76
+ /// refined graph:
77
+ ///
78
+ /// 1) Sink toward the "bottom" as the graph is refined. This means that any
79
+ /// iteration continues in some valid post-order sequence after the mutation
80
+ /// has altered the structure.
81
+ ///
82
+ /// 2) Enqueue in post-order, including the current entity. If the current
83
+ /// entity's shape changes, it and everything after it in post-order needs
84
+ /// to be visited to observe that shape.
85
+ ///
86
+ //===----------------------------------------------------------------------===//
87
+
88
+ #ifndef LLVM_ANALYSIS_CGSCCPASSMANAGER_H
89
+ #define LLVM_ANALYSIS_CGSCCPASSMANAGER_H
90
+
91
+ #include "llvm/ADT/MapVector.h"
92
+ #include "llvm/Analysis/LazyCallGraph.h"
93
+ #include "llvm/IR/PassManager.h"
94
+ #include "llvm/IR/ValueHandle.h"
95
+ #include "llvm/Support/Compiler.h"
96
+ #include "llvm/Support/raw_ostream.h"
97
+ #include <cassert>
98
+ #include <utility>
99
+
100
+ namespace llvm {
101
+
102
+ class Function;
103
+ template <typename T, unsigned int N> class SmallPriorityWorklist;
104
+ struct CGSCCUpdateResult;
105
+
106
+ class Module;
107
+
108
+ // Allow debug logging in this inline function.
109
+ #define DEBUG_TYPE "cgscc"
110
+
111
+ /// Extern template declaration for the analysis set for this IR unit.
112
+ extern template class LLVM_TEMPLATE_ABI AllAnalysesOn<LazyCallGraph::SCC>;
113
+
114
+ extern template class LLVM_TEMPLATE_ABI
115
+ AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
116
+
117
+ /// The CGSCC analysis manager.
118
+ ///
119
+ /// See the documentation for the AnalysisManager template for detail
120
+ /// documentation. This type serves as a convenient way to refer to this
121
+ /// construct in the adaptors and proxies used to integrate this into the larger
122
+ /// pass manager infrastructure.
123
+ using CGSCCAnalysisManager =
124
+ AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
125
+
126
+ // Explicit specialization and instantiation declarations for the pass manager.
127
+ // See the comments on the definition of the specialization for details on how
128
+ // it differs from the primary template.
129
+ template <>
130
+ LLVM_ABI PreservedAnalyses
131
+ PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
132
+ CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
133
+ CGSCCAnalysisManager &AM,
134
+ LazyCallGraph &G, CGSCCUpdateResult &UR);
135
+ extern template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
136
+ LazyCallGraph &, CGSCCUpdateResult &>;
137
+
138
+ /// The CGSCC pass manager.
139
+ ///
140
+ /// See the documentation for the PassManager template for details. It runs
141
+ /// a sequence of SCC passes over each SCC that the manager is run over. This
142
+ /// type serves as a convenient way to refer to this construct.
143
+ using CGSCCPassManager =
144
+ PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
145
+ CGSCCUpdateResult &>;
146
+
147
+ /// An explicit specialization of the require analysis template pass.
148
+ template <typename AnalysisT>
149
+ struct RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC, CGSCCAnalysisManager,
150
+ LazyCallGraph &, CGSCCUpdateResult &>
151
+ : PassInfoMixin<RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC,
152
+ CGSCCAnalysisManager, LazyCallGraph &,
153
+ CGSCCUpdateResult &>> {
154
+ PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
155
+ LazyCallGraph &CG, CGSCCUpdateResult &) {
156
+ (void)AM.template getResult<AnalysisT>(C, CG);
157
+ return PreservedAnalyses::all();
158
+ }
159
+ void printPipeline(raw_ostream &OS,
160
+ function_ref<StringRef(StringRef)> MapClassName2PassName) {
161
+ auto ClassName = AnalysisT::name();
162
+ auto PassName = MapClassName2PassName(ClassName);
163
+ OS << "require<" << PassName << '>';
164
+ }
165
+ };
166
+
167
+ /// A proxy from a \c CGSCCAnalysisManager to a \c Module.
168
+ using CGSCCAnalysisManagerModuleProxy =
169
+ InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
170
+
171
+ /// We need a specialized result for the \c CGSCCAnalysisManagerModuleProxy so
172
+ /// it can have access to the call graph in order to walk all the SCCs when
173
+ /// invalidating things.
174
+ template <> class CGSCCAnalysisManagerModuleProxy::Result {
175
+ public:
176
+ explicit Result(CGSCCAnalysisManager &InnerAM, LazyCallGraph &G)
177
+ : InnerAM(&InnerAM), G(&G) {}
178
+
179
+ /// Accessor for the analysis manager.
180
+ CGSCCAnalysisManager &getManager() { return *InnerAM; }
181
+
182
+ /// Handler for invalidation of the Module.
183
+ ///
184
+ /// If the proxy analysis itself is preserved, then we assume that the set of
185
+ /// SCCs in the Module hasn't changed. Thus any pointers to SCCs in the
186
+ /// CGSCCAnalysisManager are still valid, and we don't need to call \c clear
187
+ /// on the CGSCCAnalysisManager.
188
+ ///
189
+ /// Regardless of whether this analysis is marked as preserved, all of the
190
+ /// analyses in the \c CGSCCAnalysisManager are potentially invalidated based
191
+ /// on the set of preserved analyses.
192
+ LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA,
193
+ ModuleAnalysisManager::Invalidator &Inv);
194
+
195
+ private:
196
+ CGSCCAnalysisManager *InnerAM;
197
+ LazyCallGraph *G;
198
+ };
199
+
200
+ /// Provide a specialized run method for the \c CGSCCAnalysisManagerModuleProxy
201
+ /// so it can pass the lazy call graph to the result.
202
+ template <>
203
+ LLVM_ABI CGSCCAnalysisManagerModuleProxy::Result
204
+ CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM);
205
+
206
+ // Ensure the \c CGSCCAnalysisManagerModuleProxy is provided as an extern
207
+ // template.
208
+ extern template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
209
+
210
+ extern template class LLVM_TEMPLATE_ABI OuterAnalysisManagerProxy<
211
+ ModuleAnalysisManager, LazyCallGraph::SCC, LazyCallGraph &>;
212
+
213
+ /// A proxy from a \c ModuleAnalysisManager to an \c SCC.
214
+ using ModuleAnalysisManagerCGSCCProxy =
215
+ OuterAnalysisManagerProxy<ModuleAnalysisManager, LazyCallGraph::SCC,
216
+ LazyCallGraph &>;
217
+
218
+ /// Support structure for SCC passes to communicate updates the call graph back
219
+ /// to the CGSCC pass manager infrastructure.
220
+ ///
221
+ /// The CGSCC pass manager runs SCC passes which are allowed to update the call
222
+ /// graph and SCC structures. This means the structure the pass manager works
223
+ /// on is mutating underneath it. In order to support that, there needs to be
224
+ /// careful communication about the precise nature and ramifications of these
225
+ /// updates to the pass management infrastructure.
226
+ ///
227
+ /// All SCC passes will have to accept a reference to the management layer's
228
+ /// update result struct and use it to reflect the results of any CG updates
229
+ /// performed.
230
+ ///
231
+ /// Passes which do not change the call graph structure in any way can just
232
+ /// ignore this argument to their run method.
233
+ struct CGSCCUpdateResult {
234
+ /// Worklist of the SCCs queued for processing.
235
+ ///
236
+ /// When a pass refines the graph and creates new SCCs or causes them to have
237
+ /// a different shape or set of component functions it should add the SCCs to
238
+ /// this worklist so that we visit them in the refined form.
239
+ ///
240
+ /// Note that if the SCCs are part of a RefSCC that is added to the \c
241
+ /// RCWorklist, they don't need to be added here as visiting the RefSCC will
242
+ /// be sufficient to re-visit the SCCs within it.
243
+ ///
244
+ /// This worklist is in reverse post-order, as we pop off the back in order
245
+ /// to observe SCCs in post-order. When adding SCCs, clients should add them
246
+ /// in reverse post-order.
247
+ SmallPriorityWorklist<LazyCallGraph::SCC *, 1> &CWorklist;
248
+
249
+ /// The set of invalidated SCCs which should be skipped if they are found
250
+ /// in \c CWorklist.
251
+ ///
252
+ /// This is used to quickly prune out SCCs when they get deleted and happen
253
+ /// to already be on the worklist. We use this primarily to avoid scanning
254
+ /// the list and removing entries from it.
255
+ SmallPtrSetImpl<LazyCallGraph::SCC *> &InvalidatedSCCs;
256
+
257
+ /// If non-null, the updated current \c SCC being processed.
258
+ ///
259
+ /// This is set when a graph refinement takes place and the "current" point
260
+ /// in the graph moves "down" or earlier in the post-order walk. This will
261
+ /// often cause the "current" SCC to be a newly created SCC object and the
262
+ /// old one to be added to the above worklist. When that happens, this
263
+ /// pointer is non-null and can be used to continue processing the "top" of
264
+ /// the post-order walk.
265
+ LazyCallGraph::SCC *UpdatedC;
266
+
267
+ /// Preserved analyses across SCCs.
268
+ ///
269
+ /// We specifically want to allow CGSCC passes to mutate ancestor IR
270
+ /// (changing both the CG structure and the function IR itself). However,
271
+ /// this means we need to take special care to correctly mark what analyses
272
+ /// are preserved *across* SCCs. We have to track this out-of-band here
273
+ /// because within the main `PassManager` infrastructure we need to mark
274
+ /// everything within an SCC as preserved in order to avoid repeatedly
275
+ /// invalidating the same analyses as we unnest pass managers and adaptors.
276
+ /// So we track the cross-SCC version of the preserved analyses here from any
277
+ /// code that does direct invalidation of SCC analyses, and then use it
278
+ /// whenever we move forward in the post-order walk of SCCs before running
279
+ /// passes over the new SCC.
280
+ PreservedAnalyses CrossSCCPA;
281
+
282
+ /// A hacky area where the inliner can retain history about inlining
283
+ /// decisions that mutated the call graph's SCC structure in order to avoid
284
+ /// infinite inlining. See the comments in the inliner's CG update logic.
285
+ ///
286
+ /// FIXME: Keeping this here seems like a big layering issue, we should look
287
+ /// for a better technique.
288
+ SmallDenseSet<std::pair<LazyCallGraph::Node *, LazyCallGraph::SCC *>, 4>
289
+ &InlinedInternalEdges;
290
+
291
+ /// Functions that a pass has considered to be dead to be removed at the end
292
+ /// of the call graph walk in batch.
293
+ SmallVector<Function *, 4> &DeadFunctions;
294
+
295
+ /// Weak VHs to keep track of indirect calls for the purposes of detecting
296
+ /// devirtualization.
297
+ ///
298
+ /// This is a map to avoid having duplicate entries. If a Value is
299
+ /// deallocated, its corresponding WeakTrackingVH will be nulled out. When
300
+ /// checking if a Value is in the map or not, also check if the corresponding
301
+ /// WeakTrackingVH is null to avoid issues with a new Value sharing the same
302
+ /// address as a deallocated one.
303
+ SmallMapVector<Value *, WeakTrackingVH, 16> IndirectVHs;
304
+ };
305
+
306
+ /// The core module pass which does a post-order walk of the SCCs and
307
+ /// runs a CGSCC pass over each one.
308
+ ///
309
+ /// Designed to allow composition of a CGSCCPass(Manager) and
310
+ /// a ModulePassManager. Note that this pass must be run with a module analysis
311
+ /// manager as it uses the LazyCallGraph analysis. It will also run the
312
+ /// \c CGSCCAnalysisManagerModuleProxy analysis prior to running the CGSCC
313
+ /// pass over the module to enable a \c FunctionAnalysisManager to be used
314
+ /// within this run safely.
315
+ class ModuleToPostOrderCGSCCPassAdaptor
316
+ : public PassInfoMixin<ModuleToPostOrderCGSCCPassAdaptor> {
317
+ public:
318
+ using PassConceptT =
319
+ detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
320
+ LazyCallGraph &, CGSCCUpdateResult &>;
321
+
322
+ explicit ModuleToPostOrderCGSCCPassAdaptor(std::unique_ptr<PassConceptT> Pass)
323
+ : Pass(std::move(Pass)) {}
324
+
325
+ ModuleToPostOrderCGSCCPassAdaptor(ModuleToPostOrderCGSCCPassAdaptor &&Arg)
326
+ : Pass(std::move(Arg.Pass)) {}
327
+
328
+ friend void swap(ModuleToPostOrderCGSCCPassAdaptor &LHS,
329
+ ModuleToPostOrderCGSCCPassAdaptor &RHS) {
330
+ std::swap(LHS.Pass, RHS.Pass);
331
+ }
332
+
333
+ ModuleToPostOrderCGSCCPassAdaptor &
334
+ operator=(ModuleToPostOrderCGSCCPassAdaptor RHS) {
335
+ swap(*this, RHS);
336
+ return *this;
337
+ }
338
+
339
+ /// Runs the CGSCC pass across every SCC in the module.
340
+ LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
341
+
342
+ void printPipeline(raw_ostream &OS,
343
+ function_ref<StringRef(StringRef)> MapClassName2PassName) {
344
+ OS << "cgscc(";
345
+ Pass->printPipeline(OS, MapClassName2PassName);
346
+ OS << ')';
347
+ }
348
+
349
+ static bool isRequired() { return true; }
350
+
351
+ private:
352
+ std::unique_ptr<PassConceptT> Pass;
353
+ };
354
+
355
+ /// A function to deduce a function pass type and wrap it in the
356
+ /// templated adaptor.
357
+ template <typename CGSCCPassT>
358
+ ModuleToPostOrderCGSCCPassAdaptor
359
+ createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass) {
360
+ using PassModelT =
361
+ detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
362
+ LazyCallGraph &, CGSCCUpdateResult &>;
363
+ // Do not use make_unique, it causes too many template instantiations,
364
+ // causing terrible compile times.
365
+ return ModuleToPostOrderCGSCCPassAdaptor(
366
+ std::unique_ptr<ModuleToPostOrderCGSCCPassAdaptor::PassConceptT>(
367
+ new PassModelT(std::forward<CGSCCPassT>(Pass))));
368
+ }
369
+
370
+ /// A proxy from a \c FunctionAnalysisManager to an \c SCC.
371
+ ///
372
+ /// When a module pass runs and triggers invalidation, both the CGSCC and
373
+ /// Function analysis manager proxies on the module get an invalidation event.
374
+ /// We don't want to fully duplicate responsibility for most of the
375
+ /// invalidation logic. Instead, this layer is only responsible for SCC-local
376
+ /// invalidation events. We work with the module's FunctionAnalysisManager to
377
+ /// invalidate function analyses.
378
+ class FunctionAnalysisManagerCGSCCProxy
379
+ : public AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy> {
380
+ public:
381
+ class Result {
382
+ public:
383
+ explicit Result() : FAM(nullptr) {}
384
+ explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
385
+
386
+ void updateFAM(FunctionAnalysisManager &FAM) { this->FAM = &FAM; }
387
+ /// Accessor for the analysis manager.
388
+ FunctionAnalysisManager &getManager() {
389
+ assert(FAM);
390
+ return *FAM;
391
+ }
392
+
393
+ LLVM_ABI bool invalidate(LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
394
+ CGSCCAnalysisManager::Invalidator &Inv);
395
+
396
+ private:
397
+ FunctionAnalysisManager *FAM;
398
+ };
399
+
400
+ /// Computes the \c FunctionAnalysisManager and stores it in the result proxy.
401
+ LLVM_ABI Result run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
402
+ LazyCallGraph &);
403
+
404
+ private:
405
+ friend AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy>;
406
+
407
+ LLVM_ABI static AnalysisKey Key;
408
+ };
409
+
410
+ extern template class LLVM_TEMPLATE_ABI
411
+ OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
412
+
413
+ /// A proxy from a \c CGSCCAnalysisManager to a \c Function.
414
+ using CGSCCAnalysisManagerFunctionProxy =
415
+ OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
416
+
417
+ /// Helper to update the call graph after running a function pass.
418
+ ///
419
+ /// Function passes can only mutate the call graph in specific ways. This
420
+ /// routine provides a helper that updates the call graph in those ways
421
+ /// including returning whether any changes were made and populating a CG
422
+ /// update result struct for the overall CGSCC walk.
423
+ LLVM_ABI LazyCallGraph::SCC &updateCGAndAnalysisManagerForFunctionPass(
424
+ LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
425
+ CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
426
+ FunctionAnalysisManager &FAM);
427
+
428
+ /// Helper to update the call graph after running a CGSCC pass.
429
+ ///
430
+ /// CGSCC passes can only mutate the call graph in specific ways. This
431
+ /// routine provides a helper that updates the call graph in those ways
432
+ /// including returning whether any changes were made and populating a CG
433
+ /// update result struct for the overall CGSCC walk.
434
+ LLVM_ABI LazyCallGraph::SCC &updateCGAndAnalysisManagerForCGSCCPass(
435
+ LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
436
+ CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
437
+ FunctionAnalysisManager &FAM);
438
+
439
+ /// Adaptor that maps from a SCC to its functions.
440
+ ///
441
+ /// Designed to allow composition of a FunctionPass(Manager) and
442
+ /// a CGSCCPassManager. Note that if this pass is constructed with a pointer
443
+ /// to a \c CGSCCAnalysisManager it will run the
444
+ /// \c FunctionAnalysisManagerCGSCCProxy analysis prior to running the function
445
+ /// pass over the SCC to enable a \c FunctionAnalysisManager to be used
446
+ /// within this run safely.
447
+ class CGSCCToFunctionPassAdaptor
448
+ : public PassInfoMixin<CGSCCToFunctionPassAdaptor> {
449
+ public:
450
+ using PassConceptT = detail::PassConcept<Function, FunctionAnalysisManager>;
451
+
452
+ explicit CGSCCToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
453
+ bool EagerlyInvalidate, bool NoRerun)
454
+ : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate),
455
+ NoRerun(NoRerun) {}
456
+
457
+ CGSCCToFunctionPassAdaptor(CGSCCToFunctionPassAdaptor &&Arg)
458
+ : Pass(std::move(Arg.Pass)), EagerlyInvalidate(Arg.EagerlyInvalidate),
459
+ NoRerun(Arg.NoRerun) {}
460
+
461
+ friend void swap(CGSCCToFunctionPassAdaptor &LHS,
462
+ CGSCCToFunctionPassAdaptor &RHS) {
463
+ std::swap(LHS.Pass, RHS.Pass);
464
+ }
465
+
466
+ CGSCCToFunctionPassAdaptor &operator=(CGSCCToFunctionPassAdaptor RHS) {
467
+ swap(*this, RHS);
468
+ return *this;
469
+ }
470
+
471
+ /// Runs the function pass across every function in the module.
472
+ LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C,
473
+ CGSCCAnalysisManager &AM, LazyCallGraph &CG,
474
+ CGSCCUpdateResult &UR);
475
+
476
+ void printPipeline(raw_ostream &OS,
477
+ function_ref<StringRef(StringRef)> MapClassName2PassName) {
478
+ OS << "function";
479
+ if (EagerlyInvalidate || NoRerun) {
480
+ OS << "<";
481
+ if (EagerlyInvalidate)
482
+ OS << "eager-inv";
483
+ if (EagerlyInvalidate && NoRerun)
484
+ OS << ";";
485
+ if (NoRerun)
486
+ OS << "no-rerun";
487
+ OS << ">";
488
+ }
489
+ OS << '(';
490
+ Pass->printPipeline(OS, MapClassName2PassName);
491
+ OS << ')';
492
+ }
493
+
494
+ static bool isRequired() { return true; }
495
+
496
+ private:
497
+ std::unique_ptr<PassConceptT> Pass;
498
+ bool EagerlyInvalidate;
499
+ bool NoRerun;
500
+ };
501
+
502
+ /// A function to deduce a function pass type and wrap it in the
503
+ /// templated adaptor.
504
+ template <typename FunctionPassT>
505
+ CGSCCToFunctionPassAdaptor
506
+ createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass,
507
+ bool EagerlyInvalidate = false,
508
+ bool NoRerun = false) {
509
+ using PassModelT =
510
+ detail::PassModel<Function, FunctionPassT, FunctionAnalysisManager>;
511
+ // Do not use make_unique, it causes too many template instantiations,
512
+ // causing terrible compile times.
513
+ return CGSCCToFunctionPassAdaptor(
514
+ std::unique_ptr<CGSCCToFunctionPassAdaptor::PassConceptT>(
515
+ new PassModelT(std::forward<FunctionPassT>(Pass))),
516
+ EagerlyInvalidate, NoRerun);
517
+ }
518
+
519
+ // A marker to determine if function passes should be run on a function within a
520
+ // CGSCCToFunctionPassAdaptor. This is used to prevent running an expensive
521
+ // function pass (manager) on a function multiple times if SCC mutations cause a
522
+ // function to be visited multiple times and the function is not modified by
523
+ // other SCC passes.
524
+ class ShouldNotRunFunctionPassesAnalysis
525
+ : public AnalysisInfoMixin<ShouldNotRunFunctionPassesAnalysis> {
526
+ public:
527
+ LLVM_ABI static AnalysisKey Key;
528
+ struct Result {};
529
+
530
+ Result run(Function &F, FunctionAnalysisManager &FAM) { return Result(); }
531
+ };
532
+
533
+ /// A helper that repeats an SCC pass each time an indirect call is refined to
534
+ /// a direct call by that pass.
535
+ ///
536
+ /// While the CGSCC pass manager works to re-visit SCCs and RefSCCs as they
537
+ /// change shape, we may also want to repeat an SCC pass if it simply refines
538
+ /// an indirect call to a direct call, even if doing so does not alter the
539
+ /// shape of the graph. Note that this only pertains to direct calls to
540
+ /// functions where IPO across the SCC may be able to compute more precise
541
+ /// results. For intrinsics, we assume scalar optimizations already can fully
542
+ /// reason about them.
543
+ ///
544
+ /// This repetition has the potential to be very large however, as each one
545
+ /// might refine a single call site. As a consequence, in practice we use an
546
+ /// upper bound on the number of repetitions to limit things.
547
+ class DevirtSCCRepeatedPass : public PassInfoMixin<DevirtSCCRepeatedPass> {
548
+ public:
549
+ using PassConceptT =
550
+ detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
551
+ LazyCallGraph &, CGSCCUpdateResult &>;
552
+
553
+ explicit DevirtSCCRepeatedPass(std::unique_ptr<PassConceptT> Pass,
554
+ int MaxIterations)
555
+ : Pass(std::move(Pass)), MaxIterations(MaxIterations) {}
556
+
557
+ /// Runs the wrapped pass up to \c MaxIterations on the SCC, iterating
558
+ /// whenever an indirect call is refined.
559
+ LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &InitialC,
560
+ CGSCCAnalysisManager &AM, LazyCallGraph &CG,
561
+ CGSCCUpdateResult &UR);
562
+
563
+ void printPipeline(raw_ostream &OS,
564
+ function_ref<StringRef(StringRef)> MapClassName2PassName) {
565
+ OS << "devirt<" << MaxIterations << ">(";
566
+ Pass->printPipeline(OS, MapClassName2PassName);
567
+ OS << ')';
568
+ }
569
+
570
+ private:
571
+ std::unique_ptr<PassConceptT> Pass;
572
+ int MaxIterations;
573
+ };
574
+
575
+ /// A function to deduce a function pass type and wrap it in the
576
+ /// templated adaptor.
577
+ template <typename CGSCCPassT>
578
+ DevirtSCCRepeatedPass createDevirtSCCRepeatedPass(CGSCCPassT &&Pass,
579
+ int MaxIterations) {
580
+ using PassModelT =
581
+ detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
582
+ LazyCallGraph &, CGSCCUpdateResult &>;
583
+ // Do not use make_unique, it causes too many template instantiations,
584
+ // causing terrible compile times.
585
+ return DevirtSCCRepeatedPass(
586
+ std::unique_ptr<DevirtSCCRepeatedPass::PassConceptT>(
587
+ new PassModelT(std::forward<CGSCCPassT>(Pass))),
588
+ MaxIterations);
589
+ }
590
+
591
+ // Clear out the debug logging macro.
592
+ #undef DEBUG_TYPE
593
+
594
+ } // end namespace llvm
595
+
596
+ #endif // LLVM_ANALYSIS_CGSCCPASSMANAGER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/CallPrinter.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- CallPrinter.h - Call graph printer external interface ----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines external functions that can be called to explicitly
10
+ // instantiate the call graph printer.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_CALLPRINTER_H
15
+ #define LLVM_ANALYSIS_CALLPRINTER_H
16
+
17
+ #include "llvm/IR/PassManager.h"
18
+ #include "llvm/Support/Compiler.h"
19
+
20
+ namespace llvm {
21
+
22
+ class ModulePass;
23
+
24
+ /// Pass for printing the call graph to a dot file
25
+ class CallGraphDOTPrinterPass : public PassInfoMixin<CallGraphDOTPrinterPass> {
26
+ public:
27
+ LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
28
+ static bool isRequired() { return true; }
29
+ };
30
+
31
+ /// Pass for viewing the call graph
32
+ class CallGraphViewerPass : public PassInfoMixin<CallGraphViewerPass> {
33
+ public:
34
+ LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
35
+ static bool isRequired() { return true; }
36
+ };
37
+
38
+ LLVM_ABI ModulePass *createCallGraphViewerPass();
39
+ LLVM_ABI ModulePass *createCallGraphDOTPrinterPass();
40
+
41
+ } // end namespace llvm
42
+
43
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/CaptureTracking.h ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===----- llvm/Analysis/CaptureTracking.h - Pointer capture ----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file contains routines that help determine which pointers are captured.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_CAPTURETRACKING_H
14
+ #define LLVM_ANALYSIS_CAPTURETRACKING_H
15
+
16
+ #include "llvm/ADT/DenseMap.h"
17
+ #include "llvm/Support/Compiler.h"
18
+ #include "llvm/Support/ModRef.h"
19
+
20
+ namespace llvm {
21
+
22
+ class Value;
23
+ class Use;
24
+ class CaptureInfo;
25
+ class DataLayout;
26
+ class Instruction;
27
+ class DominatorTree;
28
+ class LoopInfo;
29
+ class Function;
30
+ template <typename Fn> class function_ref;
31
+
32
+ /// getDefaultMaxUsesToExploreForCaptureTracking - Return default value of
33
+ /// the maximal number of uses to explore before giving up. It is used by
34
+ /// PointerMayBeCaptured family analysis.
35
+ LLVM_ABI unsigned getDefaultMaxUsesToExploreForCaptureTracking();
36
+
37
+ /// PointerMayBeCaptured - Return true if this pointer value may be captured
38
+ /// by the enclosing function (which is required to exist). This routine can
39
+ /// be expensive, so consider caching the results. The boolean ReturnCaptures
40
+ /// specifies whether returning the value (or part of it) from the function
41
+ /// counts as capturing it or not.
42
+ /// MaxUsesToExplore specifies how many uses the analysis should explore for
43
+ /// one value before giving up due too "too many uses". If MaxUsesToExplore
44
+ /// is zero, a default value is assumed.
45
+ /// This function only considers captures of the passed value via its def-use
46
+ /// chain, without considering captures of values it may be based on, or
47
+ /// implicit captures such as for external globals.
48
+ LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures,
49
+ unsigned MaxUsesToExplore = 0);
50
+
51
+ /// Return which components of the pointer may be captured. Only consider
52
+ /// components that are part of \p Mask. Once \p StopFn on the accumulated
53
+ /// components returns true, the traversal is aborted early. By default, this
54
+ /// happens when *any* of the components in \p Mask are captured.
55
+ /// This function only considers captures of the passed value via its def-use
56
+ /// chain, without considering captures of values it may be based on, or
57
+ /// implicit captures such as for external globals.
58
+ LLVM_ABI CaptureComponents PointerMayBeCaptured(
59
+ const Value *V, bool ReturnCaptures, CaptureComponents Mask,
60
+ function_ref<bool(CaptureComponents)> StopFn = capturesAnything,
61
+ unsigned MaxUsesToExplore = 0);
62
+
63
+ /// PointerMayBeCapturedBefore - Return true if this pointer value may be
64
+ /// captured by the enclosing function (which is required to exist). If a
65
+ /// DominatorTree is provided, only captures which happen before the given
66
+ /// instruction are considered. This routine can be expensive, so consider
67
+ /// caching the results. The boolean ReturnCaptures specifies whether
68
+ /// returning the value (or part of it) from the function counts as capturing
69
+ /// it or not. Captures by the provided instruction are considered if the
70
+ /// final parameter is true.
71
+ /// MaxUsesToExplore specifies how many uses the analysis should explore for
72
+ /// one value before giving up due too "too many uses". If MaxUsesToExplore
73
+ /// is zero, a default value is assumed.
74
+ /// This function only considers captures of the passed value via its def-use
75
+ /// chain, without considering captures of values it may be based on, or
76
+ /// implicit captures such as for external globals.
77
+ LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
78
+ const Instruction *I,
79
+ const DominatorTree *DT,
80
+ bool IncludeI = false,
81
+ unsigned MaxUsesToExplore = 0,
82
+ const LoopInfo *LI = nullptr);
83
+
84
+ /// Return which components of the pointer may be captured on the path to
85
+ /// \p I. Only consider components that are part of \p Mask. Once \p StopFn
86
+ /// on the accumulated components returns true, the traversal is aborted
87
+ /// early. By default, this happens when *any* of the components in \p Mask
88
+ /// are captured.
89
+ /// This function only considers captures of the passed value via its def-use
90
+ /// chain, without considering captures of values it may be based on, or
91
+ /// implicit captures such as for external globals.
92
+ LLVM_ABI CaptureComponents PointerMayBeCapturedBefore(
93
+ const Value *V, bool ReturnCaptures, const Instruction *I,
94
+ const DominatorTree *DT, bool IncludeI, CaptureComponents Mask,
95
+ function_ref<bool(CaptureComponents)> StopFn = capturesAnything,
96
+ const LoopInfo *LI = nullptr, unsigned MaxUsesToExplore = 0);
97
+
98
+ // Returns the 'earliest' instruction that captures \p V in \F. An instruction
99
+ // A is considered earlier than instruction B, if A dominates B. If 2 escapes
100
+ // do not dominate each other, the terminator of the common dominator is
101
+ // chosen. If not all uses can be analyzed, the earliest escape is set to
102
+ // the first instruction in the function entry block. If \p V does not escape,
103
+ // nullptr is returned. Note that the caller of the function has to ensure
104
+ // that the instruction the result value is compared against is not in a
105
+ // cycle.
106
+ //
107
+ // Only consider components that are part of \p Mask.
108
+ LLVM_ABI Instruction *FindEarliestCapture(const Value *V, Function &F,
109
+ bool ReturnCaptures,
110
+ const DominatorTree &DT,
111
+ CaptureComponents Mask,
112
+ unsigned MaxUsesToExplore = 0);
113
+
114
+ /// Capture information for a specific Use.
115
+ struct UseCaptureInfo {
116
+ /// Components captured by this use.
117
+ CaptureComponents UseCC;
118
+ /// Components captured by the return value of the user of this Use.
119
+ CaptureComponents ResultCC;
120
+
121
+ UseCaptureInfo(CaptureComponents UseCC,
122
+ CaptureComponents ResultCC = CaptureComponents::None)
123
+ : UseCC(UseCC), ResultCC(ResultCC) {}
124
+
125
+ static UseCaptureInfo passthrough() {
126
+ return UseCaptureInfo(CaptureComponents::None, CaptureComponents::All);
127
+ }
128
+
129
+ bool isPassthrough() const {
130
+ return capturesNothing(UseCC) && capturesAnything(ResultCC);
131
+ }
132
+
133
+ operator CaptureComponents() const { return UseCC | ResultCC; }
134
+ };
135
+
136
+ /// This callback is used in conjunction with PointerMayBeCaptured. In
137
+ /// addition to the interface here, you'll need to provide your own getters
138
+ /// to see whether anything was captured.
139
+ struct LLVM_ABI CaptureTracker {
140
+ /// Action returned from captures().
141
+ enum Action {
142
+ /// Stop the traversal.
143
+ Stop,
144
+ /// Continue traversal, and also follow the return value of the user if
145
+ /// it has additional capture components (that is, if it has capture
146
+ /// components in Ret that are not part of Other).
147
+ Continue,
148
+ /// Continue traversal, but do not follow the return value of the user,
149
+ /// even if it has additional capture components. Should only be used if
150
+ /// captures() has already taken the potential return captures into
151
+ /// account.
152
+ ContinueIgnoringReturn,
153
+ };
154
+
155
+ virtual ~CaptureTracker();
156
+
157
+ /// tooManyUses - The depth of traversal has breached a limit. There may be
158
+ /// capturing instructions that will not be passed into captured().
159
+ virtual void tooManyUses() = 0;
160
+
161
+ /// shouldExplore - This is the use of a value derived from the pointer.
162
+ /// To prune the search (ie., assume that none of its users could possibly
163
+ /// capture) return false. To search it, return true.
164
+ ///
165
+ /// U->getUser() is always an Instruction.
166
+ virtual bool shouldExplore(const Use *U);
167
+
168
+ /// Use U directly captures CI.UseCC and additionally CI.ResultCC
169
+ /// through the return value of the user of U.
170
+ ///
171
+ /// Return one of Stop, Continue or ContinueIgnoringReturn to control
172
+ /// further traversal.
173
+ virtual Action captured(const Use *U, UseCaptureInfo CI) = 0;
174
+ };
175
+
176
+ /// Determine what kind of capture behaviour \p U may exhibit.
177
+ ///
178
+ /// The returned UseCaptureInfo contains the components captured directly
179
+ /// by the use (UseCC) and the components captured through the return value
180
+ /// of the user (ResultCC).
181
+ ///
182
+ /// \p Base is the starting value of the capture analysis, which is
183
+ /// relevant for address_is_null captures.
184
+ LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U,
185
+ const Value *Base);
186
+
187
+ /// PointerMayBeCaptured - Visit the value and the values derived from it and
188
+ /// find values which appear to be capturing the pointer value. This feeds
189
+ /// results into and is controlled by the CaptureTracker object.
190
+ /// MaxUsesToExplore specifies how many uses the analysis should explore for
191
+ /// one value before giving up due too "too many uses". If MaxUsesToExplore
192
+ /// is zero, a default value is assumed.
193
+ /// This function only considers captures of the passed value via its def-use
194
+ /// chain, without considering captures of values it may be based on, or
195
+ /// implicit captures such as for external globals.
196
+ LLVM_ABI void PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker,
197
+ unsigned MaxUsesToExplore = 0);
198
+ } // end namespace llvm
199
+
200
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/ConstantFolding.h ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- ConstantFolding.h - Fold instructions into constants ----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file declares routines for folding instructions into constants when all
10
+ // operands are constants, for example "sub i32 1, 0" -> "1".
11
+ //
12
+ // Also, to supplement the basic VMCore ConstantExpr simplifications,
13
+ // this file declares some additional folding routines that can make use of
14
+ // DataLayout information. These functions cannot go in VMCore due to library
15
+ // dependency issues.
16
+ //
17
+ //===----------------------------------------------------------------------===//
18
+
19
+ #ifndef LLVM_ANALYSIS_CONSTANTFOLDING_H
20
+ #define LLVM_ANALYSIS_CONSTANTFOLDING_H
21
+
22
+ #include "llvm/Support/Compiler.h"
23
+ #include <stdint.h>
24
+
25
+ namespace llvm {
26
+
27
+ namespace Intrinsic {
28
+ using ID = unsigned;
29
+ }
30
+
31
+ class APInt;
32
+ template <typename T> class ArrayRef;
33
+ class CallBase;
34
+ class Constant;
35
+ class DSOLocalEquivalent;
36
+ class DataLayout;
37
+ class Function;
38
+ class GlobalValue;
39
+ class GlobalVariable;
40
+ class Instruction;
41
+ class TargetLibraryInfo;
42
+ class Type;
43
+
44
+ /// If this constant is a constant offset from a global, return the global and
45
+ /// the constant. Because of constantexprs, this function is recursive.
46
+ /// If the global is part of a dso_local_equivalent constant, return it through
47
+ /// `Equiv` if it is provided.
48
+ LLVM_ABI bool
49
+ IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset,
50
+ const DataLayout &DL,
51
+ DSOLocalEquivalent **DSOEquiv = nullptr);
52
+
53
+ /// ConstantFoldInstruction - Try to constant fold the specified instruction.
54
+ /// If successful, the constant result is returned, if not, null is returned.
55
+ /// Note that this fails if not all of the operands are constant. Otherwise,
56
+ /// this function can only fail when attempting to fold instructions like loads
57
+ /// and stores, which have no constant expression form.
58
+ LLVM_ABI Constant *
59
+ ConstantFoldInstruction(const Instruction *I, const DataLayout &DL,
60
+ const TargetLibraryInfo *TLI = nullptr);
61
+
62
+ /// ConstantFoldConstant - Fold the constant using the specified DataLayout.
63
+ /// This function always returns a non-null constant: Either the folding result,
64
+ /// or the original constant if further folding is not possible.
65
+ LLVM_ABI Constant *ConstantFoldConstant(const Constant *C, const DataLayout &DL,
66
+ const TargetLibraryInfo *TLI = nullptr);
67
+
68
+ /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
69
+ /// specified operands. If successful, the constant result is returned, if not,
70
+ /// null is returned. Note that this function can fail when attempting to
71
+ /// fold instructions like loads and stores, which have no constant expression
72
+ /// form.
73
+ ///
74
+ /// In some cases, constant folding may return one value chosen from a set of
75
+ /// multiple legal return values. For example, the exact bit pattern of NaN
76
+ /// results is not guaranteed. Using such a result is usually only valid if
77
+ /// all uses of the original operation are replaced by the constant-folded
78
+ /// result. The \p AllowNonDeterministic parameter controls whether this is
79
+ /// allowed.
80
+ LLVM_ABI Constant *ConstantFoldInstOperands(
81
+ const Instruction *I, ArrayRef<Constant *> Ops, const DataLayout &DL,
82
+ const TargetLibraryInfo *TLI = nullptr, bool AllowNonDeterministic = true);
83
+
84
+ /// Attempt to constant fold a compare instruction (icmp/fcmp) with the
85
+ /// specified operands. Returns null or a constant expression of the specified
86
+ /// operands on failure.
87
+ /// Denormal inputs may be flushed based on the denormal handling mode.
88
+ LLVM_ABI Constant *ConstantFoldCompareInstOperands(
89
+ unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL,
90
+ const TargetLibraryInfo *TLI = nullptr, const Instruction *I = nullptr);
91
+
92
+ /// Attempt to constant fold a unary operation with the specified operand.
93
+ /// Returns null on failure.
94
+ LLVM_ABI Constant *ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
95
+ const DataLayout &DL);
96
+
97
+ /// Attempt to constant fold a binary operation with the specified operands.
98
+ /// Returns null or a constant expression of the specified operands on failure.
99
+ LLVM_ABI Constant *ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
100
+ Constant *RHS,
101
+ const DataLayout &DL);
102
+
103
+ /// Attempt to constant fold a floating point binary operation with the
104
+ /// specified operands, applying the denormal handling mod to the operands.
105
+ /// Returns null or a constant expression of the specified operands on failure.
106
+ LLVM_ABI Constant *
107
+ ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS, Constant *RHS,
108
+ const DataLayout &DL, const Instruction *I,
109
+ bool AllowNonDeterministic = true);
110
+
111
+ /// Attempt to flush float point constant according to denormal mode set in the
112
+ /// instruction's parent function attributes. If so, return a zero with the
113
+ /// correct sign, otherwise return the original constant. Inputs and outputs to
114
+ /// floating point instructions can have their mode set separately, so the
115
+ /// direction is also needed.
116
+ ///
117
+ /// If the calling function's "denormal-fp-math" input mode is "dynamic" for the
118
+ /// floating-point type, returns nullptr for denormal inputs.
119
+ LLVM_ABI Constant *FlushFPConstant(Constant *Operand, const Instruction *I,
120
+ bool IsOutput);
121
+
122
+ /// Attempt to constant fold a select instruction with the specified
123
+ /// operands. The constant result is returned if successful; if not, null is
124
+ /// returned.
125
+ LLVM_ABI Constant *ConstantFoldSelectInstruction(Constant *Cond, Constant *V1,
126
+ Constant *V2);
127
+
128
+ /// Attempt to constant fold a cast with the specified operand. If it
129
+ /// fails, it returns a constant expression of the specified operand.
130
+ LLVM_ABI Constant *ConstantFoldCastOperand(unsigned Opcode, Constant *C,
131
+ Type *DestTy, const DataLayout &DL);
132
+
133
+ /// Constant fold a zext, sext or trunc, depending on IsSigned and whether the
134
+ /// DestTy is wider or narrower than C. Returns nullptr on failure.
135
+ LLVM_ABI Constant *ConstantFoldIntegerCast(Constant *C, Type *DestTy,
136
+ bool IsSigned, const DataLayout &DL);
137
+
138
+ /// ConstantFoldInsertValueInstruction - Attempt to constant fold an insertvalue
139
+ /// instruction with the specified operands and indices. The constant result is
140
+ /// returned if successful; if not, null is returned.
141
+ LLVM_ABI Constant *ConstantFoldInsertValueInstruction(Constant *Agg,
142
+ Constant *Val,
143
+ ArrayRef<unsigned> Idxs);
144
+
145
+ /// Attempt to constant fold an extractvalue instruction with the
146
+ /// specified operands and indices. The constant result is returned if
147
+ /// successful; if not, null is returned.
148
+ LLVM_ABI Constant *ConstantFoldExtractValueInstruction(Constant *Agg,
149
+ ArrayRef<unsigned> Idxs);
150
+
151
+ /// Attempt to constant fold an insertelement instruction with the
152
+ /// specified operands and indices. The constant result is returned if
153
+ /// successful; if not, null is returned.
154
+ LLVM_ABI Constant *ConstantFoldInsertElementInstruction(Constant *Val,
155
+ Constant *Elt,
156
+ Constant *Idx);
157
+
158
+ /// Attempt to constant fold an extractelement instruction with the
159
+ /// specified operands and indices. The constant result is returned if
160
+ /// successful; if not, null is returned.
161
+ LLVM_ABI Constant *ConstantFoldExtractElementInstruction(Constant *Val,
162
+ Constant *Idx);
163
+
164
+ /// Attempt to constant fold a shufflevector instruction with the
165
+ /// specified operands and mask. See class ShuffleVectorInst for a description
166
+ /// of the mask representation. The constant result is returned if successful;
167
+ /// if not, null is returned.
168
+ LLVM_ABI Constant *ConstantFoldShuffleVectorInstruction(Constant *V1,
169
+ Constant *V2,
170
+ ArrayRef<int> Mask);
171
+
172
+ /// Extract value of C at the given Offset reinterpreted as Ty. If bits past
173
+ /// the end of C are accessed, they are assumed to be poison.
174
+ LLVM_ABI Constant *ConstantFoldLoadFromConst(Constant *C, Type *Ty,
175
+ const APInt &Offset,
176
+ const DataLayout &DL);
177
+
178
+ /// Extract value of C reinterpreted as Ty. Same as previous API with zero
179
+ /// offset.
180
+ LLVM_ABI Constant *ConstantFoldLoadFromConst(Constant *C, Type *Ty,
181
+ const DataLayout &DL);
182
+
183
+ /// Return the value that a load from C with offset Offset would produce if it
184
+ /// is constant and determinable. If this is not determinable, return null.
185
+ LLVM_ABI Constant *ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
186
+ APInt Offset,
187
+ const DataLayout &DL);
188
+
189
+ /// Return the value that a load from C would produce if it is constant and
190
+ /// determinable. If this is not determinable, return null.
191
+ LLVM_ABI Constant *ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
192
+ const DataLayout &DL);
193
+
194
+ /// If C is a uniform value where all bits are the same (either all zero, all
195
+ /// ones, all undef or all poison), return the corresponding uniform value in
196
+ /// the new type. If the value is not uniform or the result cannot be
197
+ /// represented, return null.
198
+ LLVM_ABI Constant *ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty,
199
+ const DataLayout &DL);
200
+
201
+ /// canConstantFoldCallTo - Return true if its even possible to fold a call to
202
+ /// the specified function.
203
+ LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F);
204
+
205
+ /// ConstantFoldCall - Attempt to constant fold a call to the specified function
206
+ /// with the specified arguments, returning null if unsuccessful.
207
+ LLVM_ABI Constant *ConstantFoldCall(const CallBase *Call, Function *F,
208
+ ArrayRef<Constant *> Operands,
209
+ const TargetLibraryInfo *TLI = nullptr,
210
+ bool AllowNonDeterministic = true);
211
+
212
+ LLVM_ABI Constant *ConstantFoldBinaryIntrinsic(Intrinsic::ID ID, Constant *LHS,
213
+ Constant *RHS, Type *Ty,
214
+ Instruction *FMFSource);
215
+
216
+ /// ConstantFoldLoadThroughBitcast - try to cast constant to destination type
217
+ /// returning null if unsuccessful. Can cast pointer to pointer or pointer to
218
+ /// integer and vice versa if their sizes are equal.
219
+ LLVM_ABI Constant *ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
220
+ const DataLayout &DL);
221
+
222
+ /// Check whether the given call has no side-effects.
223
+ /// Specifically checks for math routimes which sometimes set errno.
224
+ LLVM_ABI bool isMathLibCallNoop(const CallBase *Call,
225
+ const TargetLibraryInfo *TLI);
226
+
227
+ LLVM_ABI Constant *ReadByteArrayFromGlobal(const GlobalVariable *GV,
228
+ uint64_t Offset);
229
+ }
230
+
231
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/CycleAnalysis.h ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- CycleAnalysis.h - Cycle Info for LLVM IR -----------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ ///
10
+ /// This file declares an analysis pass that computes CycleInfo for
11
+ /// LLVM IR, specialized from GenericCycleInfo.
12
+ ///
13
+ //===----------------------------------------------------------------------===//
14
+
15
+ #ifndef LLVM_ANALYSIS_CYCLEANALYSIS_H
16
+ #define LLVM_ANALYSIS_CYCLEANALYSIS_H
17
+
18
+ #include "llvm/IR/CycleInfo.h"
19
+ #include "llvm/IR/PassManager.h"
20
+ #include "llvm/Pass.h"
21
+
22
+ namespace llvm {
23
+
24
+ /// Legacy analysis pass which computes a \ref CycleInfo.
25
+ class CycleInfoWrapperPass : public FunctionPass {
26
+ Function *F = nullptr;
27
+ CycleInfo CI;
28
+
29
+ public:
30
+ static char ID;
31
+
32
+ CycleInfoWrapperPass();
33
+
34
+ CycleInfo &getResult() { return CI; }
35
+ const CycleInfo &getResult() const { return CI; }
36
+
37
+ bool runOnFunction(Function &F) override;
38
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
39
+ void releaseMemory() override;
40
+ void print(raw_ostream &OS, const Module *M = nullptr) const override;
41
+
42
+ // TODO: verify analysis?
43
+ };
44
+
45
+ /// Analysis pass which computes a \ref CycleInfo.
46
+ class CycleAnalysis : public AnalysisInfoMixin<CycleAnalysis> {
47
+ friend AnalysisInfoMixin<CycleAnalysis>;
48
+ static AnalysisKey Key;
49
+
50
+ public:
51
+ /// Provide the result typedef for this analysis pass.
52
+ using Result = CycleInfo;
53
+
54
+ using LegacyWrapper = CycleInfoWrapperPass;
55
+
56
+ /// Run the analysis pass over a function and produce a dominator tree.
57
+ CycleInfo run(Function &F, FunctionAnalysisManager &);
58
+
59
+ // TODO: verify analysis?
60
+ };
61
+
62
+ class CycleInfoPrinterPass : public PassInfoMixin<CycleInfoPrinterPass> {
63
+ raw_ostream &OS;
64
+
65
+ public:
66
+ explicit CycleInfoPrinterPass(raw_ostream &OS);
67
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
68
+ static bool isRequired() { return true; }
69
+ };
70
+
71
+ struct CycleInfoVerifierPass : public PassInfoMixin<CycleInfoVerifierPass> {
72
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
73
+ static bool isRequired() { return true; }
74
+ };
75
+
76
+ } // end namespace llvm
77
+
78
+ #endif // LLVM_ANALYSIS_CYCLEANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DDG.h ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/DDG.h --------------------------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the Data-Dependence Graph (DDG).
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_DDG_H
14
+ #define LLVM_ANALYSIS_DDG_H
15
+
16
+ #include "llvm/ADT/DenseMap.h"
17
+ #include "llvm/ADT/DirectedGraph.h"
18
+ #include "llvm/Analysis/DependenceAnalysis.h"
19
+ #include "llvm/Analysis/DependenceGraphBuilder.h"
20
+ #include "llvm/Analysis/LoopAnalysisManager.h"
21
+ #include "llvm/Support/Compiler.h"
22
+
23
+ namespace llvm {
24
+ class Function;
25
+ class Loop;
26
+ class LoopInfo;
27
+ class DDGNode;
28
+ class DDGEdge;
29
+ using DDGNodeBase = DGNode<DDGNode, DDGEdge>;
30
+ using DDGEdgeBase = DGEdge<DDGNode, DDGEdge>;
31
+ using DDGBase = DirectedGraph<DDGNode, DDGEdge>;
32
+ class LPMUpdater;
33
+
34
+ /// Data Dependence Graph Node
35
+ /// The graph can represent the following types of nodes:
36
+ /// 1. Single instruction node containing just one instruction.
37
+ /// 2. Multiple instruction node where two or more instructions from
38
+ /// the same basic block are merged into one node.
39
+ /// 3. Pi-block node which is a group of other DDG nodes that are part of a
40
+ /// strongly-connected component of the graph.
41
+ /// A pi-block node contains more than one single or multiple instruction
42
+ /// nodes. The root node cannot be part of a pi-block.
43
+ /// 4. Root node is a special node that connects to all components such that
44
+ /// there is always a path from it to any node in the graph.
45
+ class LLVM_ABI DDGNode : public DDGNodeBase {
46
+ public:
47
+ using InstructionListType = SmallVectorImpl<Instruction *>;
48
+
49
+ enum class NodeKind {
50
+ Unknown,
51
+ SingleInstruction,
52
+ MultiInstruction,
53
+ PiBlock,
54
+ Root,
55
+ };
56
+
57
+ DDGNode() = delete;
58
+ DDGNode(const NodeKind K) : Kind(K) {}
59
+ DDGNode(const DDGNode &N) = default;
60
+ DDGNode(DDGNode &&N) : DDGNodeBase(std::move(N)), Kind(N.Kind) {}
61
+ virtual ~DDGNode() = 0;
62
+
63
+ DDGNode &operator=(const DDGNode &N) {
64
+ DGNode::operator=(N);
65
+ Kind = N.Kind;
66
+ return *this;
67
+ }
68
+
69
+ DDGNode &operator=(DDGNode &&N) {
70
+ DGNode::operator=(std::move(N));
71
+ Kind = N.Kind;
72
+ return *this;
73
+ }
74
+
75
+ /// Getter for the kind of this node.
76
+ NodeKind getKind() const { return Kind; }
77
+
78
+ /// Collect a list of instructions, in \p IList, for which predicate \p Pred
79
+ /// evaluates to true when iterating over instructions of this node. Return
80
+ /// true if at least one instruction was collected, and false otherwise.
81
+ bool collectInstructions(llvm::function_ref<bool(Instruction *)> const &Pred,
82
+ InstructionListType &IList) const;
83
+
84
+ protected:
85
+ /// Setter for the kind of this node.
86
+ void setKind(NodeKind K) { Kind = K; }
87
+
88
+ private:
89
+ NodeKind Kind;
90
+ };
91
+
92
+ /// Subclass of DDGNode representing the root node of the graph.
93
+ /// There should only be one such node in a given graph.
94
+ class RootDDGNode : public DDGNode {
95
+ public:
96
+ RootDDGNode() : DDGNode(NodeKind::Root) {}
97
+ RootDDGNode(const RootDDGNode &N) = delete;
98
+ RootDDGNode(RootDDGNode &&N) : DDGNode(std::move(N)) {}
99
+ ~RootDDGNode() = default;
100
+
101
+ /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
102
+ static bool classof(const DDGNode *N) {
103
+ return N->getKind() == NodeKind::Root;
104
+ }
105
+ static bool classof(const RootDDGNode *N) { return true; }
106
+ };
107
+
108
+ /// Subclass of DDGNode representing single or multi-instruction nodes.
109
+ class LLVM_ABI SimpleDDGNode : public DDGNode {
110
+ friend class DDGBuilder;
111
+
112
+ public:
113
+ SimpleDDGNode() = delete;
114
+ SimpleDDGNode(Instruction &I);
115
+ SimpleDDGNode(const SimpleDDGNode &N);
116
+ SimpleDDGNode(SimpleDDGNode &&N);
117
+ ~SimpleDDGNode();
118
+
119
+ SimpleDDGNode &operator=(const SimpleDDGNode &N) = default;
120
+
121
+ SimpleDDGNode &operator=(SimpleDDGNode &&N) {
122
+ DDGNode::operator=(std::move(N));
123
+ InstList = std::move(N.InstList);
124
+ return *this;
125
+ }
126
+
127
+ /// Get the list of instructions in this node.
128
+ const InstructionListType &getInstructions() const {
129
+ assert(!InstList.empty() && "Instruction List is empty.");
130
+ return InstList;
131
+ }
132
+ InstructionListType &getInstructions() {
133
+ return const_cast<InstructionListType &>(
134
+ static_cast<const SimpleDDGNode *>(this)->getInstructions());
135
+ }
136
+
137
+ /// Get the first/last instruction in the node.
138
+ Instruction *getFirstInstruction() const { return getInstructions().front(); }
139
+ Instruction *getLastInstruction() const { return getInstructions().back(); }
140
+
141
+ /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
142
+ static bool classof(const DDGNode *N) {
143
+ return N->getKind() == NodeKind::SingleInstruction ||
144
+ N->getKind() == NodeKind::MultiInstruction;
145
+ }
146
+ static bool classof(const SimpleDDGNode *N) { return true; }
147
+
148
+ private:
149
+ /// Append the list of instructions in \p Input to this node.
150
+ void appendInstructions(const InstructionListType &Input) {
151
+ setKind((InstList.size() == 0 && Input.size() == 1)
152
+ ? NodeKind::SingleInstruction
153
+ : NodeKind::MultiInstruction);
154
+ llvm::append_range(InstList, Input);
155
+ }
156
+ void appendInstructions(const SimpleDDGNode &Input) {
157
+ appendInstructions(Input.getInstructions());
158
+ }
159
+
160
+ /// List of instructions associated with a single or multi-instruction node.
161
+ SmallVector<Instruction *, 2> InstList;
162
+ };
163
+
164
+ /// Subclass of DDGNode representing a pi-block. A pi-block represents a group
165
+ /// of DDG nodes that are part of a strongly-connected component of the graph.
166
+ /// Replacing all the SCCs with pi-blocks results in an acyclic representation
167
+ /// of the DDG. For example if we have:
168
+ /// {a -> b}, {b -> c, d}, {c -> a}
169
+ /// the cycle a -> b -> c -> a is abstracted into a pi-block "p" as follows:
170
+ /// {p -> d} with "p" containing: {a -> b}, {b -> c}, {c -> a}
171
+ class LLVM_ABI PiBlockDDGNode : public DDGNode {
172
+ public:
173
+ using PiNodeList = SmallVector<DDGNode *, 4>;
174
+
175
+ PiBlockDDGNode() = delete;
176
+ PiBlockDDGNode(const PiNodeList &List);
177
+ PiBlockDDGNode(const PiBlockDDGNode &N);
178
+ PiBlockDDGNode(PiBlockDDGNode &&N);
179
+ ~PiBlockDDGNode();
180
+
181
+ PiBlockDDGNode &operator=(const PiBlockDDGNode &N) = default;
182
+
183
+ PiBlockDDGNode &operator=(PiBlockDDGNode &&N) {
184
+ DDGNode::operator=(std::move(N));
185
+ NodeList = std::move(N.NodeList);
186
+ return *this;
187
+ }
188
+
189
+ /// Get the list of nodes in this pi-block.
190
+ const PiNodeList &getNodes() const {
191
+ assert(!NodeList.empty() && "Node list is empty.");
192
+ return NodeList;
193
+ }
194
+ PiNodeList &getNodes() {
195
+ return const_cast<PiNodeList &>(
196
+ static_cast<const PiBlockDDGNode *>(this)->getNodes());
197
+ }
198
+
199
+ /// Define classof to be able to use isa<>, cast<>, dyn_cast<>, etc.
200
+ static bool classof(const DDGNode *N) {
201
+ return N->getKind() == NodeKind::PiBlock;
202
+ }
203
+
204
+ private:
205
+ /// List of nodes in this pi-block.
206
+ PiNodeList NodeList;
207
+ };
208
+
209
+ /// Data Dependency Graph Edge.
210
+ /// An edge in the DDG can represent a def-use relationship or
211
+ /// a memory dependence based on the result of DependenceAnalysis.
212
+ /// A rooted edge connects the root node to one of the components
213
+ /// of the graph.
214
+ class DDGEdge : public DDGEdgeBase {
215
+ public:
216
+ /// The kind of edge in the DDG
217
+ enum class EdgeKind {
218
+ Unknown,
219
+ RegisterDefUse,
220
+ MemoryDependence,
221
+ Rooted,
222
+ Last = Rooted // Must be equal to the largest enum value.
223
+ };
224
+
225
+ explicit DDGEdge(DDGNode &N) = delete;
226
+ DDGEdge(DDGNode &N, EdgeKind K) : DDGEdgeBase(N), Kind(K) {}
227
+ DDGEdge(const DDGEdge &E) : DDGEdgeBase(E), Kind(E.getKind()) {}
228
+ DDGEdge(DDGEdge &&E) : DDGEdgeBase(std::move(E)), Kind(E.Kind) {}
229
+ DDGEdge &operator=(const DDGEdge &E) = default;
230
+
231
+ DDGEdge &operator=(DDGEdge &&E) {
232
+ DDGEdgeBase::operator=(std::move(E));
233
+ Kind = E.Kind;
234
+ return *this;
235
+ }
236
+
237
+ /// Get the edge kind
238
+ EdgeKind getKind() const { return Kind; };
239
+
240
+ /// Return true if this is a def-use edge, and false otherwise.
241
+ bool isDefUse() const { return Kind == EdgeKind::RegisterDefUse; }
242
+
243
+ /// Return true if this is a memory dependence edge, and false otherwise.
244
+ bool isMemoryDependence() const { return Kind == EdgeKind::MemoryDependence; }
245
+
246
+ /// Return true if this is an edge stemming from the root node, and false
247
+ /// otherwise.
248
+ bool isRooted() const { return Kind == EdgeKind::Rooted; }
249
+
250
+ private:
251
+ EdgeKind Kind;
252
+ };
253
+
254
+ /// Encapsulate some common data and functionality needed for different
255
+ /// variations of data dependence graphs.
256
+ template <typename NodeType> class DependenceGraphInfo {
257
+ public:
258
+ using DependenceList = SmallVector<std::unique_ptr<Dependence>, 1>;
259
+
260
+ DependenceGraphInfo() = delete;
261
+ DependenceGraphInfo(const DependenceGraphInfo &G) = delete;
262
+ DependenceGraphInfo(const std::string &N, const DependenceInfo &DepInfo)
263
+ : Name(N), DI(DepInfo), Root(nullptr) {}
264
+ DependenceGraphInfo(DependenceGraphInfo &&G)
265
+ : Name(std::move(G.Name)), DI(std::move(G.DI)), Root(G.Root) {}
266
+ virtual ~DependenceGraphInfo() = default;
267
+
268
+ /// Return the label that is used to name this graph.
269
+ StringRef getName() const { return Name; }
270
+
271
+ /// Return the root node of the graph.
272
+ NodeType &getRoot() const {
273
+ assert(Root && "Root node is not available yet. Graph construction may "
274
+ "still be in progress\n");
275
+ return *Root;
276
+ }
277
+
278
+ /// Collect all the data dependency infos coming from any pair of memory
279
+ /// accesses from \p Src to \p Dst, and store them into \p Deps. Return true
280
+ /// if a dependence exists, and false otherwise.
281
+ bool getDependencies(const NodeType &Src, const NodeType &Dst,
282
+ DependenceList &Deps) const;
283
+
284
+ /// Return a string representing the type of dependence that the dependence
285
+ /// analysis identified between the two given nodes. This function assumes
286
+ /// that there is a memory dependence between the given two nodes.
287
+ std::string getDependenceString(const NodeType &Src,
288
+ const NodeType &Dst) const;
289
+
290
+ protected:
291
+ // Name of the graph.
292
+ std::string Name;
293
+
294
+ // Store a copy of DependenceInfo in the graph, so that individual memory
295
+ // dependencies don't need to be stored. Instead when the dependence is
296
+ // queried it is recomputed using @DI.
297
+ const DependenceInfo DI;
298
+
299
+ // A special node in the graph that has an edge to every connected component of
300
+ // the graph, to ensure all nodes are reachable in a graph walk.
301
+ NodeType *Root = nullptr;
302
+ };
303
+
304
+ using DDGInfo = DependenceGraphInfo<DDGNode>;
305
+
306
+ /// Data Dependency Graph
307
+ class LLVM_ABI DataDependenceGraph : public DDGBase, public DDGInfo {
308
+ friend AbstractDependenceGraphBuilder<DataDependenceGraph>;
309
+ friend class DDGBuilder;
310
+
311
+ public:
312
+ using NodeType = DDGNode;
313
+ using EdgeType = DDGEdge;
314
+
315
+ DataDependenceGraph() = delete;
316
+ DataDependenceGraph(const DataDependenceGraph &G) = delete;
317
+ DataDependenceGraph(DataDependenceGraph &&G)
318
+ : DDGBase(std::move(G)), DDGInfo(std::move(G)) {}
319
+ DataDependenceGraph(Function &F, DependenceInfo &DI);
320
+ DataDependenceGraph(Loop &L, LoopInfo &LI, DependenceInfo &DI);
321
+ ~DataDependenceGraph();
322
+
323
+ /// If node \p N belongs to a pi-block return a pointer to the pi-block,
324
+ /// otherwise return null.
325
+ const PiBlockDDGNode *getPiBlock(const NodeType &N) const;
326
+
327
+ protected:
328
+ /// Add node \p N to the graph, if it's not added yet, and keep track of the
329
+ /// root node as well as pi-blocks and their members. Return true if node is
330
+ /// successfully added.
331
+ bool addNode(NodeType &N);
332
+
333
+ private:
334
+ using PiBlockMapType = DenseMap<const NodeType *, const PiBlockDDGNode *>;
335
+
336
+ /// Mapping from graph nodes to their containing pi-blocks. If a node is not
337
+ /// part of a pi-block, it will not appear in this map.
338
+ PiBlockMapType PiBlockMap;
339
+ };
340
+
341
+ /// Concrete implementation of a pure data dependence graph builder. This class
342
+ /// provides custom implementation for the pure-virtual functions used in the
343
+ /// generic dependence graph build algorithm.
344
+ ///
345
+ /// For information about time complexity of the build algorithm see the
346
+ /// comments near the declaration of AbstractDependenceGraphBuilder.
347
+ class LLVM_ABI DDGBuilder
348
+ : public AbstractDependenceGraphBuilder<DataDependenceGraph> {
349
+ public:
350
+ DDGBuilder(DataDependenceGraph &G, DependenceInfo &D,
351
+ const BasicBlockListType &BBs)
352
+ : AbstractDependenceGraphBuilder(G, D, BBs) {}
353
+ DDGNode &createRootNode() final {
354
+ auto *RN = new RootDDGNode();
355
+ assert(RN && "Failed to allocate memory for DDG root node.");
356
+ Graph.addNode(*RN);
357
+ return *RN;
358
+ }
359
+ DDGNode &createFineGrainedNode(Instruction &I) final {
360
+ auto *SN = new SimpleDDGNode(I);
361
+ assert(SN && "Failed to allocate memory for simple DDG node.");
362
+ Graph.addNode(*SN);
363
+ return *SN;
364
+ }
365
+ DDGNode &createPiBlock(const NodeListType &L) final {
366
+ auto *Pi = new PiBlockDDGNode(L);
367
+ assert(Pi && "Failed to allocate memory for pi-block node.");
368
+ Graph.addNode(*Pi);
369
+ return *Pi;
370
+ }
371
+ DDGEdge &createDefUseEdge(DDGNode &Src, DDGNode &Tgt) final {
372
+ auto *E = new DDGEdge(Tgt, DDGEdge::EdgeKind::RegisterDefUse);
373
+ assert(E && "Failed to allocate memory for edge");
374
+ Graph.connect(Src, Tgt, *E);
375
+ return *E;
376
+ }
377
+ DDGEdge &createMemoryEdge(DDGNode &Src, DDGNode &Tgt) final {
378
+ auto *E = new DDGEdge(Tgt, DDGEdge::EdgeKind::MemoryDependence);
379
+ assert(E && "Failed to allocate memory for edge");
380
+ Graph.connect(Src, Tgt, *E);
381
+ return *E;
382
+ }
383
+ DDGEdge &createRootedEdge(DDGNode &Src, DDGNode &Tgt) final {
384
+ auto *E = new DDGEdge(Tgt, DDGEdge::EdgeKind::Rooted);
385
+ assert(E && "Failed to allocate memory for edge");
386
+ assert(isa<RootDDGNode>(Src) && "Expected root node");
387
+ Graph.connect(Src, Tgt, *E);
388
+ return *E;
389
+ }
390
+
391
+ const NodeListType &getNodesInPiBlock(const DDGNode &N) final {
392
+ auto *PiNode = dyn_cast<const PiBlockDDGNode>(&N);
393
+ assert(PiNode && "Expected a pi-block node.");
394
+ return PiNode->getNodes();
395
+ }
396
+
397
+ /// Return true if the two nodes \pSrc and \pTgt are both simple nodes and
398
+ /// the consecutive instructions after merging belong to the same basic block.
399
+ bool areNodesMergeable(const DDGNode &Src, const DDGNode &Tgt) const final;
400
+ void mergeNodes(DDGNode &Src, DDGNode &Tgt) final;
401
+ bool shouldSimplify() const final;
402
+ bool shouldCreatePiBlocks() const final;
403
+ };
404
+
405
+ LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DDGNode &N);
406
+ LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DDGNode::NodeKind K);
407
+ LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DDGEdge &E);
408
+ LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DDGEdge::EdgeKind K);
409
+ LLVM_ABI raw_ostream &operator<<(raw_ostream &OS, const DataDependenceGraph &G);
410
+
411
+ //===--------------------------------------------------------------------===//
412
+ // DDG Analysis Passes
413
+ //===--------------------------------------------------------------------===//
414
+
415
+ /// Analysis pass that builds the DDG for a loop.
416
+ class DDGAnalysis : public AnalysisInfoMixin<DDGAnalysis> {
417
+ public:
418
+ using Result = std::unique_ptr<DataDependenceGraph>;
419
+ LLVM_ABI Result run(Loop &L, LoopAnalysisManager &AM,
420
+ LoopStandardAnalysisResults &AR);
421
+
422
+ private:
423
+ friend AnalysisInfoMixin<DDGAnalysis>;
424
+ LLVM_ABI static AnalysisKey Key;
425
+ };
426
+
427
+ /// Textual printer pass for the DDG of a loop.
428
+ class DDGAnalysisPrinterPass : public PassInfoMixin<DDGAnalysisPrinterPass> {
429
+ public:
430
+ explicit DDGAnalysisPrinterPass(raw_ostream &OS) : OS(OS) {}
431
+ LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
432
+ LoopStandardAnalysisResults &AR,
433
+ LPMUpdater &U);
434
+ static bool isRequired() { return true; }
435
+
436
+ private:
437
+ raw_ostream &OS;
438
+ };
439
+
440
+ //===--------------------------------------------------------------------===//
441
+ // DependenceGraphInfo Implementation
442
+ //===--------------------------------------------------------------------===//
443
+
444
+ template <typename NodeType>
445
+ bool DependenceGraphInfo<NodeType>::getDependencies(
446
+ const NodeType &Src, const NodeType &Dst, DependenceList &Deps) const {
447
+ assert(Deps.empty() && "Expected empty output list at the start.");
448
+
449
+ // List of memory access instructions from src and dst nodes.
450
+ SmallVector<Instruction *, 8> SrcIList, DstIList;
451
+ auto isMemoryAccess = [](const Instruction *I) {
452
+ return I->mayReadOrWriteMemory();
453
+ };
454
+ Src.collectInstructions(isMemoryAccess, SrcIList);
455
+ Dst.collectInstructions(isMemoryAccess, DstIList);
456
+
457
+ for (auto *SrcI : SrcIList)
458
+ for (auto *DstI : DstIList)
459
+ if (auto Dep =
460
+ const_cast<DependenceInfo *>(&DI)->depends(SrcI, DstI))
461
+ Deps.push_back(std::move(Dep));
462
+
463
+ return !Deps.empty();
464
+ }
465
+
466
+ template <typename NodeType>
467
+ std::string
468
+ DependenceGraphInfo<NodeType>::getDependenceString(const NodeType &Src,
469
+ const NodeType &Dst) const {
470
+ std::string Str;
471
+ raw_string_ostream OS(Str);
472
+ DependenceList Deps;
473
+ if (!getDependencies(Src, Dst, Deps))
474
+ return Str;
475
+ interleaveComma(Deps, OS, [&](const std::unique_ptr<Dependence> &D) {
476
+ D->dump(OS);
477
+ // Remove the extra new-line character printed by the dump
478
+ // method
479
+ if (Str.back() == '\n')
480
+ Str.pop_back();
481
+ });
482
+
483
+ return Str;
484
+ }
485
+
486
+ //===--------------------------------------------------------------------===//
487
+ // GraphTraits specializations for the DDG
488
+ //===--------------------------------------------------------------------===//
489
+
490
+ /// non-const versions of the grapth trait specializations for DDG
491
+ template <> struct GraphTraits<DDGNode *> {
492
+ using NodeRef = DDGNode *;
493
+
494
+ static DDGNode *DDGGetTargetNode(DGEdge<DDGNode, DDGEdge> *P) {
495
+ return &P->getTargetNode();
496
+ }
497
+
498
+ // Provide a mapped iterator so that the GraphTrait-based implementations can
499
+ // find the target nodes without having to explicitly go through the edges.
500
+ using ChildIteratorType =
501
+ mapped_iterator<DDGNode::iterator, decltype(&DDGGetTargetNode)>;
502
+ using ChildEdgeIteratorType = DDGNode::iterator;
503
+
504
+ static NodeRef getEntryNode(NodeRef N) { return N; }
505
+ static ChildIteratorType child_begin(NodeRef N) {
506
+ return ChildIteratorType(N->begin(), &DDGGetTargetNode);
507
+ }
508
+ static ChildIteratorType child_end(NodeRef N) {
509
+ return ChildIteratorType(N->end(), &DDGGetTargetNode);
510
+ }
511
+
512
+ static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
513
+ return N->begin();
514
+ }
515
+ static ChildEdgeIteratorType child_edge_end(NodeRef N) { return N->end(); }
516
+ };
517
+
518
+ template <>
519
+ struct GraphTraits<DataDependenceGraph *> : public GraphTraits<DDGNode *> {
520
+ using nodes_iterator = DataDependenceGraph::iterator;
521
+ static NodeRef getEntryNode(DataDependenceGraph *DG) {
522
+ return &DG->getRoot();
523
+ }
524
+ static nodes_iterator nodes_begin(DataDependenceGraph *DG) {
525
+ return DG->begin();
526
+ }
527
+ static nodes_iterator nodes_end(DataDependenceGraph *DG) { return DG->end(); }
528
+ };
529
+
530
+ /// const versions of the grapth trait specializations for DDG
531
+ template <> struct GraphTraits<const DDGNode *> {
532
+ using NodeRef = const DDGNode *;
533
+
534
+ static const DDGNode *DDGGetTargetNode(const DGEdge<DDGNode, DDGEdge> *P) {
535
+ return &P->getTargetNode();
536
+ }
537
+
538
+ // Provide a mapped iterator so that the GraphTrait-based implementations can
539
+ // find the target nodes without having to explicitly go through the edges.
540
+ using ChildIteratorType =
541
+ mapped_iterator<DDGNode::const_iterator, decltype(&DDGGetTargetNode)>;
542
+ using ChildEdgeIteratorType = DDGNode::const_iterator;
543
+
544
+ static NodeRef getEntryNode(NodeRef N) { return N; }
545
+ static ChildIteratorType child_begin(NodeRef N) {
546
+ return ChildIteratorType(N->begin(), &DDGGetTargetNode);
547
+ }
548
+ static ChildIteratorType child_end(NodeRef N) {
549
+ return ChildIteratorType(N->end(), &DDGGetTargetNode);
550
+ }
551
+
552
+ static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
553
+ return N->begin();
554
+ }
555
+ static ChildEdgeIteratorType child_edge_end(NodeRef N) { return N->end(); }
556
+ };
557
+
558
+ template <>
559
+ struct GraphTraits<const DataDependenceGraph *>
560
+ : public GraphTraits<const DDGNode *> {
561
+ using nodes_iterator = DataDependenceGraph::const_iterator;
562
+ static NodeRef getEntryNode(const DataDependenceGraph *DG) {
563
+ return &DG->getRoot();
564
+ }
565
+ static nodes_iterator nodes_begin(const DataDependenceGraph *DG) {
566
+ return DG->begin();
567
+ }
568
+ static nodes_iterator nodes_end(const DataDependenceGraph *DG) {
569
+ return DG->end();
570
+ }
571
+ };
572
+
573
+ } // namespace llvm
574
+
575
+ #endif // LLVM_ANALYSIS_DDG_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DDGPrinter.h ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/DDGPrinter.h -------------------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ //===----------------------------------------------------------------------===//
10
+ //
11
+ // This file defines the DOT printer for the Data-Dependence Graph (DDG).
12
+ //
13
+ //===----------------------------------------------------------------------===//
14
+
15
+ #ifndef LLVM_ANALYSIS_DDGPRINTER_H
16
+ #define LLVM_ANALYSIS_DDGPRINTER_H
17
+
18
+ #include "llvm/Analysis/DDG.h"
19
+ #include "llvm/Support/DOTGraphTraits.h"
20
+
21
+ namespace llvm {
22
+ class LPMUpdater;
23
+ class Loop;
24
+
25
+ //===--------------------------------------------------------------------===//
26
+ // Implementation of DDG DOT Printer for a loop.
27
+ //===--------------------------------------------------------------------===//
28
+ class DDGDotPrinterPass : public PassInfoMixin<DDGDotPrinterPass> {
29
+ public:
30
+ PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
31
+ LoopStandardAnalysisResults &AR, LPMUpdater &U);
32
+ static bool isRequired() { return true; }
33
+ };
34
+
35
+ //===--------------------------------------------------------------------===//
36
+ // Specialization of DOTGraphTraits.
37
+ //===--------------------------------------------------------------------===//
38
+ template <>
39
+ struct DOTGraphTraits<const DataDependenceGraph *>
40
+ : public DefaultDOTGraphTraits {
41
+
42
+ DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
43
+
44
+ /// Generate a title for the graph in DOT format
45
+ std::string getGraphName(const DataDependenceGraph *G) {
46
+ assert(G && "expected a valid pointer to the graph.");
47
+ return "DDG for '" + std::string(G->getName()) + "'";
48
+ }
49
+
50
+ /// Print a DDG node either in concise form (-ddg-dot-only) or
51
+ /// verbose mode (-ddg-dot).
52
+ std::string getNodeLabel(const DDGNode *Node,
53
+ const DataDependenceGraph *Graph);
54
+
55
+ /// Print attributes of an edge in the DDG graph. If the edge
56
+ /// is a MemoryDependence edge, then detailed dependence info
57
+ /// available from DependenceAnalysis is displayed.
58
+ std::string
59
+ getEdgeAttributes(const DDGNode *Node,
60
+ GraphTraits<const DDGNode *>::ChildIteratorType I,
61
+ const DataDependenceGraph *G);
62
+
63
+ /// Do not print nodes that are part of a pi-block separately. They
64
+ /// will be printed when their containing pi-block is being printed.
65
+ bool isNodeHidden(const DDGNode *Node, const DataDependenceGraph *G);
66
+
67
+ private:
68
+ /// Print a DDG node in concise form.
69
+ static std::string getSimpleNodeLabel(const DDGNode *Node,
70
+ const DataDependenceGraph *G);
71
+
72
+ /// Print a DDG node with more information including containing instructions
73
+ /// and detailed information about the dependence edges.
74
+ static std::string getVerboseNodeLabel(const DDGNode *Node,
75
+ const DataDependenceGraph *G);
76
+
77
+ /// Print a DDG edge in concise form.
78
+ static std::string getSimpleEdgeAttributes(const DDGNode *Src,
79
+ const DDGEdge *Edge,
80
+ const DataDependenceGraph *G);
81
+
82
+ /// Print a DDG edge with more information including detailed information
83
+ /// about the dependence edges.
84
+ static std::string getVerboseEdgeAttributes(const DDGNode *Src,
85
+ const DDGEdge *Edge,
86
+ const DataDependenceGraph *G);
87
+ };
88
+
89
+ using DDGDotGraphTraits = DOTGraphTraits<const DataDependenceGraph *>;
90
+
91
+ } // namespace llvm
92
+
93
+ #endif // LLVM_ANALYSIS_DDGPRINTER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DOTGraphTraitsPass.h ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- DOTGraphTraitsPass.h - Print/View dotty graphs-----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // Templates to create dotty viewer and printer passes for GraphTraits graphs.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_DOTGRAPHTRAITSPASS_H
14
+ #define LLVM_ANALYSIS_DOTGRAPHTRAITSPASS_H
15
+
16
+ #include "llvm/Analysis/CFGPrinter.h"
17
+ #include "llvm/Support/FileSystem.h"
18
+ #include "llvm/Support/GraphWriter.h"
19
+ #include <unordered_set>
20
+
21
+ static std::unordered_set<std::string> nameObj;
22
+
23
+ namespace llvm {
24
+
25
+ /// Default traits class for extracting a graph from an analysis pass.
26
+ ///
27
+ /// This assumes that 'GraphT' is 'AnalysisT::Result *', and pass it through
28
+ template <typename Result, typename GraphT = Result *>
29
+ struct DefaultAnalysisGraphTraits {
30
+ static GraphT getGraph(Result R) { return &R; }
31
+ };
32
+
33
+ template <typename GraphT>
34
+ void viewGraphForFunction(Function &F, GraphT Graph, StringRef Name,
35
+ bool IsSimple) {
36
+ std::string GraphName = DOTGraphTraits<GraphT *>::getGraphName(&Graph);
37
+
38
+ ViewGraph(Graph, Name, IsSimple,
39
+ GraphName + " for '" + F.getName() + "' function");
40
+ }
41
+
42
+ template <typename AnalysisT, bool IsSimple,
43
+ typename GraphT = typename AnalysisT::Result *,
44
+ typename AnalysisGraphTraitsT =
45
+ DefaultAnalysisGraphTraits<typename AnalysisT::Result &, GraphT>>
46
+ struct DOTGraphTraitsViewer
47
+ : PassInfoMixin<DOTGraphTraitsViewer<AnalysisT, IsSimple, GraphT,
48
+ AnalysisGraphTraitsT>> {
49
+ DOTGraphTraitsViewer(StringRef GraphName) : Name(GraphName) {}
50
+
51
+ /// Return true if this function should be processed.
52
+ ///
53
+ /// An implementation of this class my override this function to indicate that
54
+ /// only certain functions should be viewed.
55
+ ///
56
+ /// @param Result The current analysis result for this function.
57
+ virtual bool processFunction(Function &F,
58
+ const typename AnalysisT::Result &Result) {
59
+ return true;
60
+ }
61
+
62
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM) {
63
+ auto &Result = FAM.getResult<AnalysisT>(F);
64
+ if (!processFunction(F, Result))
65
+ return PreservedAnalyses::all();
66
+
67
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(Result);
68
+ viewGraphForFunction(F, Graph, Name, IsSimple);
69
+
70
+ return PreservedAnalyses::all();
71
+ };
72
+
73
+ protected:
74
+ /// Avoid compiler warning "has virtual functions but non-virtual destructor
75
+ /// [-Wnon-virtual-dtor]" in derived classes.
76
+ ///
77
+ /// DOTGraphTraitsViewer is also used as a mixin for avoiding repeated
78
+ /// implementation of viewer passes, ie there should be no
79
+ /// runtime-polymorphisms/downcasting involving this class and hence no
80
+ /// virtual destructor needed. Making this dtor protected stops accidental
81
+ /// invocation when the derived class destructor should have been called.
82
+ /// Those derived classes sould be marked final to avoid the warning.
83
+ ~DOTGraphTraitsViewer() {}
84
+
85
+ private:
86
+ StringRef Name;
87
+ };
88
+
89
+ static inline void shortenFileName(std::string &FN, unsigned char len = 250) {
90
+ if (FN.length() > len)
91
+ FN.resize(len);
92
+ auto strLen = FN.length();
93
+ while (strLen > 0) {
94
+ if (nameObj.insert(FN).second)
95
+ break;
96
+ FN.resize(--len);
97
+ strLen--;
98
+ }
99
+ }
100
+
101
+ template <typename GraphT>
102
+ void printGraphForFunction(Function &F, GraphT Graph, StringRef Name,
103
+ bool IsSimple) {
104
+ std::string Filename = Name.str() + "." + F.getName().str();
105
+ shortenFileName(Filename);
106
+ Filename = Filename + ".dot";
107
+ std::error_code EC;
108
+
109
+ errs() << "Writing '" << Filename << "'...";
110
+
111
+ raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
112
+ std::string GraphName = DOTGraphTraits<GraphT>::getGraphName(Graph);
113
+
114
+ if (!EC)
115
+ WriteGraph(File, Graph, IsSimple,
116
+ GraphName + " for '" + F.getName() + "' function");
117
+ else
118
+ errs() << " error opening file for writing!";
119
+ errs() << "\n";
120
+ }
121
+
122
+ template <typename AnalysisT, bool IsSimple,
123
+ typename GraphT = typename AnalysisT::Result *,
124
+ typename AnalysisGraphTraitsT =
125
+ DefaultAnalysisGraphTraits<typename AnalysisT::Result &, GraphT>>
126
+ struct DOTGraphTraitsPrinter
127
+ : PassInfoMixin<DOTGraphTraitsPrinter<AnalysisT, IsSimple, GraphT,
128
+ AnalysisGraphTraitsT>> {
129
+ DOTGraphTraitsPrinter(StringRef GraphName) : Name(GraphName) {}
130
+
131
+ /// Return true if this function should be processed.
132
+ ///
133
+ /// An implementation of this class my override this function to indicate that
134
+ /// only certain functions should be viewed.
135
+ ///
136
+ /// @param Result The current analysis result for this function.
137
+ virtual bool processFunction(Function &F,
138
+ const typename AnalysisT::Result &Result) {
139
+ return true;
140
+ }
141
+
142
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM) {
143
+ auto &Result = FAM.getResult<AnalysisT>(F);
144
+ if (!processFunction(F, Result))
145
+ return PreservedAnalyses::all();
146
+
147
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(Result);
148
+
149
+ printGraphForFunction(F, Graph, Name, IsSimple);
150
+
151
+ return PreservedAnalyses::all();
152
+ };
153
+
154
+ protected:
155
+ /// Avoid compiler warning "has virtual functions but non-virtual destructor
156
+ /// [-Wnon-virtual-dtor]" in derived classes.
157
+ ///
158
+ /// DOTGraphTraitsPrinter is also used as a mixin for avoiding repeated
159
+ /// implementation of printer passes, ie there should be no
160
+ /// runtime-polymorphisms/downcasting involving this class and hence no
161
+ /// virtual destructor needed. Making this dtor protected stops accidental
162
+ /// invocation when the derived class destructor should have been called.
163
+ /// Those derived classes sould be marked final to avoid the warning.
164
+ ~DOTGraphTraitsPrinter() {}
165
+
166
+ private:
167
+ StringRef Name;
168
+ };
169
+
170
+ /// Default traits class for extracting a graph from an analysis pass.
171
+ ///
172
+ /// This assumes that 'GraphT' is 'AnalysisT *' and so just passes it through.
173
+ template <typename AnalysisT, typename GraphT = AnalysisT *>
174
+ struct LegacyDefaultAnalysisGraphTraits {
175
+ static GraphT getGraph(AnalysisT *A) { return A; }
176
+ };
177
+
178
+ template <typename AnalysisT, bool IsSimple, typename GraphT = AnalysisT *,
179
+ typename AnalysisGraphTraitsT =
180
+ LegacyDefaultAnalysisGraphTraits<AnalysisT, GraphT>>
181
+ class DOTGraphTraitsViewerWrapperPass : public FunctionPass {
182
+ public:
183
+ DOTGraphTraitsViewerWrapperPass(StringRef GraphName, char &ID)
184
+ : FunctionPass(ID), Name(GraphName) {}
185
+
186
+ /// Return true if this function should be processed.
187
+ ///
188
+ /// An implementation of this class my override this function to indicate that
189
+ /// only certain functions should be viewed.
190
+ ///
191
+ /// @param Analysis The current analysis result for this function.
192
+ virtual bool processFunction(Function &F, AnalysisT &Analysis) {
193
+ return true;
194
+ }
195
+
196
+ bool runOnFunction(Function &F) override {
197
+ auto &Analysis = getAnalysis<AnalysisT>();
198
+
199
+ if (!processFunction(F, Analysis))
200
+ return false;
201
+
202
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(&Analysis);
203
+ viewGraphForFunction(F, Graph, Name, IsSimple);
204
+
205
+ return false;
206
+ }
207
+
208
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
209
+ AU.setPreservesAll();
210
+ AU.addRequired<AnalysisT>();
211
+ }
212
+
213
+ private:
214
+ std::string Name;
215
+ };
216
+
217
+ template <typename AnalysisT, bool IsSimple, typename GraphT = AnalysisT *,
218
+ typename AnalysisGraphTraitsT =
219
+ LegacyDefaultAnalysisGraphTraits<AnalysisT, GraphT>>
220
+ class DOTGraphTraitsPrinterWrapperPass : public FunctionPass {
221
+ public:
222
+ DOTGraphTraitsPrinterWrapperPass(StringRef GraphName, char &ID)
223
+ : FunctionPass(ID), Name(GraphName) {}
224
+
225
+ /// Return true if this function should be processed.
226
+ ///
227
+ /// An implementation of this class my override this function to indicate that
228
+ /// only certain functions should be printed.
229
+ ///
230
+ /// @param Analysis The current analysis result for this function.
231
+ virtual bool processFunction(Function &F, AnalysisT &Analysis) {
232
+ return true;
233
+ }
234
+
235
+ bool runOnFunction(Function &F) override {
236
+ auto &Analysis = getAnalysis<AnalysisT>();
237
+
238
+ if (!processFunction(F, Analysis))
239
+ return false;
240
+
241
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(&Analysis);
242
+ printGraphForFunction(F, Graph, Name, IsSimple);
243
+
244
+ return false;
245
+ }
246
+
247
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
248
+ AU.setPreservesAll();
249
+ AU.addRequired<AnalysisT>();
250
+ }
251
+
252
+ private:
253
+ std::string Name;
254
+ };
255
+
256
+ template <typename AnalysisT, bool IsSimple, typename GraphT = AnalysisT *,
257
+ typename AnalysisGraphTraitsT =
258
+ LegacyDefaultAnalysisGraphTraits<AnalysisT, GraphT>>
259
+ class DOTGraphTraitsModuleViewerWrapperPass : public ModulePass {
260
+ public:
261
+ DOTGraphTraitsModuleViewerWrapperPass(StringRef GraphName, char &ID)
262
+ : ModulePass(ID), Name(GraphName) {}
263
+
264
+ bool runOnModule(Module &M) override {
265
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(&getAnalysis<AnalysisT>());
266
+ std::string Title = DOTGraphTraits<GraphT>::getGraphName(Graph);
267
+
268
+ ViewGraph(Graph, Name, IsSimple, Title);
269
+
270
+ return false;
271
+ }
272
+
273
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
274
+ AU.setPreservesAll();
275
+ AU.addRequired<AnalysisT>();
276
+ }
277
+
278
+ private:
279
+ std::string Name;
280
+ };
281
+
282
+ template <typename AnalysisT, bool IsSimple, typename GraphT = AnalysisT *,
283
+ typename AnalysisGraphTraitsT =
284
+ LegacyDefaultAnalysisGraphTraits<AnalysisT, GraphT>>
285
+ class DOTGraphTraitsModulePrinterWrapperPass : public ModulePass {
286
+ public:
287
+ DOTGraphTraitsModulePrinterWrapperPass(StringRef GraphName, char &ID)
288
+ : ModulePass(ID), Name(GraphName) {}
289
+
290
+ bool runOnModule(Module &M) override {
291
+ GraphT Graph = AnalysisGraphTraitsT::getGraph(&getAnalysis<AnalysisT>());
292
+ shortenFileName(Name);
293
+ std::string Filename = Name + ".dot";
294
+ std::error_code EC;
295
+
296
+ errs() << "Writing '" << Filename << "'...";
297
+
298
+ raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
299
+ std::string Title = DOTGraphTraits<GraphT>::getGraphName(Graph);
300
+
301
+ if (!EC)
302
+ WriteGraph(File, Graph, IsSimple, Title);
303
+ else
304
+ errs() << " error opening file for writing!";
305
+ errs() << "\n";
306
+
307
+ return false;
308
+ }
309
+
310
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
311
+ AU.setPreservesAll();
312
+ AU.addRequired<AnalysisT>();
313
+ }
314
+
315
+ private:
316
+ std::string Name;
317
+ };
318
+
319
+ template <typename GraphT>
320
+ void WriteDOTGraphToFile(Function &F, GraphT &&Graph,
321
+ std::string FileNamePrefix, bool IsSimple) {
322
+ std::string Filename = FileNamePrefix + "." + F.getName().str();
323
+ shortenFileName(Filename);
324
+ Filename = Filename + ".dot";
325
+ std::error_code EC;
326
+
327
+ errs() << "Writing '" << Filename << "'...";
328
+
329
+ raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
330
+ std::string GraphName = DOTGraphTraits<GraphT>::getGraphName(Graph);
331
+ std::string Title = GraphName + " for '" + F.getName().str() + "' function";
332
+
333
+ if (!EC)
334
+ WriteGraph(File, Graph, IsSimple, Title);
335
+ else
336
+ errs() << " error opening file for writing!";
337
+ errs() << "\n";
338
+ }
339
+
340
+ } // end namespace llvm
341
+
342
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/DXILMetadataAnalysis.h ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //=- DXILMetadataAnalysis.h - Representation of Module metadata --*- C++ -*-=//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ #ifndef LLVM_ANALYSIS_DXILMETADATA_H
10
+ #define LLVM_ANALYSIS_DXILMETADATA_H
11
+
12
+ #include "llvm/ADT/SmallVector.h"
13
+ #include "llvm/IR/PassManager.h"
14
+ #include "llvm/Pass.h"
15
+ #include "llvm/Support/VersionTuple.h"
16
+ #include "llvm/TargetParser/Triple.h"
17
+
18
+ namespace llvm {
19
+
20
+ class Function;
21
+ namespace dxil {
22
+
23
+ struct EntryProperties {
24
+ const Function *Entry{nullptr};
25
+ // Specific target shader stage may be specified for entry functions
26
+ Triple::EnvironmentType ShaderStage{Triple::UnknownEnvironment};
27
+ unsigned NumThreadsX{0}; // X component
28
+ unsigned NumThreadsY{0}; // Y component
29
+ unsigned NumThreadsZ{0}; // Z component
30
+
31
+ EntryProperties(const Function *Fn = nullptr) : Entry(Fn) {};
32
+ };
33
+
34
+ struct ModuleMetadataInfo {
35
+ VersionTuple DXILVersion{};
36
+ VersionTuple ShaderModelVersion{};
37
+ Triple::EnvironmentType ShaderProfile{Triple::UnknownEnvironment};
38
+ VersionTuple ValidatorVersion{};
39
+ SmallVector<EntryProperties> EntryPropertyVec{};
40
+ void print(raw_ostream &OS) const;
41
+ };
42
+
43
+ } // namespace dxil
44
+
45
+ // Module metadata analysis pass for new pass manager
46
+ class DXILMetadataAnalysis : public AnalysisInfoMixin<DXILMetadataAnalysis> {
47
+ friend AnalysisInfoMixin<DXILMetadataAnalysis>;
48
+
49
+ static AnalysisKey Key;
50
+
51
+ public:
52
+ using Result = dxil::ModuleMetadataInfo;
53
+ /// Gather module metadata info for the module \c M.
54
+ dxil::ModuleMetadataInfo run(Module &M, ModuleAnalysisManager &AM);
55
+ };
56
+
57
+ /// Printer pass for the \c DXILMetadataAnalysis results.
58
+ class DXILMetadataAnalysisPrinterPass
59
+ : public PassInfoMixin<DXILMetadataAnalysisPrinterPass> {
60
+ raw_ostream &OS;
61
+
62
+ public:
63
+ explicit DXILMetadataAnalysisPrinterPass(raw_ostream &OS) : OS(OS) {}
64
+
65
+ PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
66
+
67
+ static bool isRequired() { return true; }
68
+ };
69
+
70
+ /// Legacy pass
71
+ class DXILMetadataAnalysisWrapperPass : public ModulePass {
72
+ std::unique_ptr<dxil::ModuleMetadataInfo> MetadataInfo;
73
+
74
+ public:
75
+ static char ID; // Class identification, replacement for typeinfo
76
+
77
+ DXILMetadataAnalysisWrapperPass();
78
+ ~DXILMetadataAnalysisWrapperPass() override;
79
+
80
+ const dxil::ModuleMetadataInfo &getModuleMetadata() const {
81
+ return *MetadataInfo;
82
+ }
83
+ dxil::ModuleMetadataInfo &getModuleMetadata() { return *MetadataInfo; }
84
+
85
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
86
+ bool runOnModule(Module &M) override;
87
+ void releaseMemory() override;
88
+
89
+ void print(raw_ostream &OS, const Module *M) const override;
90
+ void dump() const;
91
+ };
92
+
93
+ } // namespace llvm
94
+
95
+ #endif // LLVM_ANALYSIS_DXILMETADATA_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DependenceGraphBuilder.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/DependenceGraphBuilder.h -------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines a builder interface that can be used to populate dependence
10
+ // graphs such as DDG and PDG.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_DEPENDENCEGRAPHBUILDER_H
15
+ #define LLVM_ANALYSIS_DEPENDENCEGRAPHBUILDER_H
16
+
17
+ #include "llvm/ADT/DenseMap.h"
18
+ #include "llvm/ADT/EquivalenceClasses.h"
19
+ #include "llvm/ADT/SmallVector.h"
20
+ #include "llvm/Support/Compiler.h"
21
+
22
+ namespace llvm {
23
+
24
+ class BasicBlock;
25
+ class DependenceInfo;
26
+ class Instruction;
27
+
28
+ /// This abstract builder class defines a set of high-level steps for creating
29
+ /// DDG-like graphs. The client code is expected to inherit from this class and
30
+ /// define concrete implementation for each of the pure virtual functions used
31
+ /// in the high-level algorithm.
32
+ template <class GraphType> class LLVM_ABI AbstractDependenceGraphBuilder {
33
+ protected:
34
+ using BasicBlockListType = SmallVectorImpl<BasicBlock *>;
35
+
36
+ private:
37
+ using NodeType = typename GraphType::NodeType;
38
+ using EdgeType = typename GraphType::EdgeType;
39
+
40
+ public:
41
+ using ClassesType = EquivalenceClasses<BasicBlock *>;
42
+ using NodeListType = SmallVector<NodeType *, 4>;
43
+
44
+ AbstractDependenceGraphBuilder(GraphType &G, DependenceInfo &D,
45
+ const BasicBlockListType &BBs)
46
+ : Graph(G), DI(D), BBList(BBs) {}
47
+ virtual ~AbstractDependenceGraphBuilder() = default;
48
+
49
+ /// The main entry to the graph construction algorithm. It starts by
50
+ /// creating nodes in increasing order of granularity and then
51
+ /// adds def-use and memory edges. As one of the final stages, it
52
+ /// also creates pi-block nodes to facilitate codegen in transformations
53
+ /// that use dependence graphs.
54
+ ///
55
+ /// The algorithmic complexity of this implementation is O(V^2 * I^2), where V
56
+ /// is the number of vertecies (nodes) and I is the number of instructions in
57
+ /// each node. The total number of instructions, N, is equal to V * I,
58
+ /// therefore the worst-case time complexity is O(N^2). The average time
59
+ /// complexity is O((N^2)/2).
60
+ void populate() {
61
+ computeInstructionOrdinals();
62
+ createFineGrainedNodes();
63
+ createDefUseEdges();
64
+ createMemoryDependencyEdges();
65
+ simplify();
66
+ createAndConnectRootNode();
67
+ createPiBlocks();
68
+ sortNodesTopologically();
69
+ }
70
+
71
+ /// Compute ordinal numbers for each instruction and store them in a map for
72
+ /// future look up. These ordinals are used to compute node ordinals which are
73
+ /// in turn used to order nodes that are part of a cycle.
74
+ /// Instruction ordinals are assigned based on lexical program order.
75
+ void computeInstructionOrdinals();
76
+
77
+ /// Create fine grained nodes. These are typically atomic nodes that
78
+ /// consist of a single instruction.
79
+ void createFineGrainedNodes();
80
+
81
+ /// Analyze the def-use chains and create edges from the nodes containing
82
+ /// definitions to the nodes containing the uses.
83
+ void createDefUseEdges();
84
+
85
+ /// Analyze data dependencies that exist between memory loads or stores,
86
+ /// in the graph nodes and create edges between them.
87
+ void createMemoryDependencyEdges();
88
+
89
+ /// Create a root node and add edges such that each node in the graph is
90
+ /// reachable from the root.
91
+ void createAndConnectRootNode();
92
+
93
+ /// Apply graph abstraction to groups of nodes that belong to a strongly
94
+ /// connected component of the graph to create larger compound nodes
95
+ /// called pi-blocks. The purpose of this abstraction is to isolate sets of
96
+ /// program elements that need to stay together during codegen and turn
97
+ /// the dependence graph into an acyclic graph.
98
+ void createPiBlocks();
99
+
100
+ /// Go through all the nodes in the graph and collapse any two nodes
101
+ /// 'a' and 'b' if all of the following are true:
102
+ /// - the only edge from 'a' is a def-use edge to 'b' and
103
+ /// - the only edge to 'b' is a def-use edge from 'a' and
104
+ /// - there is no cyclic edge from 'b' to 'a' and
105
+ /// - all instructions in 'a' and 'b' belong to the same basic block and
106
+ /// - both 'a' and 'b' are simple (single or multi instruction) nodes.
107
+ void simplify();
108
+
109
+ /// Topologically sort the graph nodes.
110
+ void sortNodesTopologically();
111
+
112
+ protected:
113
+ /// Create the root node of the graph.
114
+ virtual NodeType &createRootNode() = 0;
115
+
116
+ /// Create an atomic node in the graph given a single instruction.
117
+ virtual NodeType &createFineGrainedNode(Instruction &I) = 0;
118
+
119
+ /// Create a pi-block node in the graph representing a group of nodes in an
120
+ /// SCC of the graph.
121
+ virtual NodeType &createPiBlock(const NodeListType &L) = 0;
122
+
123
+ /// Create a def-use edge going from \p Src to \p Tgt.
124
+ virtual EdgeType &createDefUseEdge(NodeType &Src, NodeType &Tgt) = 0;
125
+
126
+ /// Create a memory dependence edge going from \p Src to \p Tgt.
127
+ virtual EdgeType &createMemoryEdge(NodeType &Src, NodeType &Tgt) = 0;
128
+
129
+ /// Create a rooted edge going from \p Src to \p Tgt .
130
+ virtual EdgeType &createRootedEdge(NodeType &Src, NodeType &Tgt) = 0;
131
+
132
+ /// Given a pi-block node, return a vector of all the nodes contained within
133
+ /// it.
134
+ virtual const NodeListType &getNodesInPiBlock(const NodeType &N) = 0;
135
+
136
+ /// Deallocate memory of edge \p E.
137
+ virtual void destroyEdge(EdgeType &E) { delete &E; }
138
+
139
+ /// Deallocate memory of node \p N.
140
+ virtual void destroyNode(NodeType &N) { delete &N; }
141
+
142
+ /// Return true if creation of pi-blocks are supported and desired,
143
+ /// and false otherwise.
144
+ virtual bool shouldCreatePiBlocks() const { return true; }
145
+
146
+ /// Return true if graph simplification step is requested, and false
147
+ /// otherwise.
148
+ virtual bool shouldSimplify() const { return true; }
149
+
150
+ /// Return true if it's safe to merge the two nodes.
151
+ virtual bool areNodesMergeable(const NodeType &A,
152
+ const NodeType &B) const = 0;
153
+
154
+ /// Append the content of node \p B into node \p A and remove \p B and
155
+ /// the edge between \p A and \p B from the graph.
156
+ virtual void mergeNodes(NodeType &A, NodeType &B) = 0;
157
+
158
+ /// Given an instruction \p I return its associated ordinal number.
159
+ size_t getOrdinal(Instruction &I) {
160
+ assert(InstOrdinalMap.contains(&I) &&
161
+ "No ordinal computed for this instruction.");
162
+ return InstOrdinalMap[&I];
163
+ }
164
+
165
+ /// Given a node \p N return its associated ordinal number.
166
+ size_t getOrdinal(NodeType &N) {
167
+ assert(NodeOrdinalMap.contains(&N) && "No ordinal computed for this node.");
168
+ return NodeOrdinalMap[&N];
169
+ }
170
+
171
+ /// Map types to map instructions to nodes used when populating the graph.
172
+ using InstToNodeMap = DenseMap<Instruction *, NodeType *>;
173
+
174
+ /// Map Types to map instruction/nodes to an ordinal number.
175
+ using InstToOrdinalMap = DenseMap<Instruction *, size_t>;
176
+ using NodeToOrdinalMap = DenseMap<NodeType *, size_t>;
177
+
178
+ /// Reference to the graph that gets built by a concrete implementation of
179
+ /// this builder.
180
+ GraphType &Graph;
181
+
182
+ /// Dependence information used to create memory dependence edges in the
183
+ /// graph.
184
+ DependenceInfo &DI;
185
+
186
+ /// The list of basic blocks to consider when building the graph.
187
+ const BasicBlockListType &BBList;
188
+
189
+ /// A mapping from instructions to the corresponding nodes in the graph.
190
+ InstToNodeMap IMap;
191
+
192
+ /// A mapping from each instruction to an ordinal number. This map is used to
193
+ /// populate the \p NodeOrdinalMap.
194
+ InstToOrdinalMap InstOrdinalMap;
195
+
196
+ /// A mapping from nodes to an ordinal number. This map is used to sort nodes
197
+ /// in a pi-block based on program order.
198
+ NodeToOrdinalMap NodeOrdinalMap;
199
+ };
200
+
201
+ } // namespace llvm
202
+
203
+ #endif // LLVM_ANALYSIS_DEPENDENCEGRAPHBUILDER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DomConditionCache.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/DomConditionCache.h ------------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // Cache for branch conditions that affect a certain value for use by
10
+ // ValueTracking. Unlike AssumptionCache, this class does not perform any
11
+ // automatic analysis or invalidation. The caller is responsible for registering
12
+ // all relevant branches (and re-registering them if they change), and for
13
+ // removing invalidated values from the cache.
14
+ //
15
+ //===----------------------------------------------------------------------===//
16
+
17
+ #ifndef LLVM_ANALYSIS_DOMCONDITIONCACHE_H
18
+ #define LLVM_ANALYSIS_DOMCONDITIONCACHE_H
19
+
20
+ #include "llvm/ADT/ArrayRef.h"
21
+ #include "llvm/ADT/DenseMap.h"
22
+ #include "llvm/ADT/SmallVector.h"
23
+
24
+ namespace llvm {
25
+
26
+ class Value;
27
+ class BranchInst;
28
+
29
+ class DomConditionCache {
30
+ private:
31
+ /// A map of values about which a branch might be providing information.
32
+ using AffectedValuesMap = DenseMap<Value *, SmallVector<BranchInst *, 1>>;
33
+ AffectedValuesMap AffectedValues;
34
+
35
+ public:
36
+ /// Add a branch condition to the cache.
37
+ void registerBranch(BranchInst *BI);
38
+
39
+ /// Remove a value from the cache, e.g. because it will be erased.
40
+ void removeValue(Value *V) { AffectedValues.erase(V); }
41
+
42
+ /// Access the list of branches which affect this value.
43
+ ArrayRef<BranchInst *> conditionsFor(const Value *V) const {
44
+ auto AVI = AffectedValues.find_as(const_cast<Value *>(V));
45
+ if (AVI == AffectedValues.end())
46
+ return ArrayRef<BranchInst *>();
47
+
48
+ return AVI->second;
49
+ }
50
+ };
51
+
52
+ } // end namespace llvm
53
+
54
+ #endif // LLVM_ANALYSIS_DOMCONDITIONCACHE_H
deps/exla/cache/xla_extension/include/llvm/Analysis/DominanceFrontierImpl.h ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/DominanceFrontier.h - Dominator Frontiers --*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This is the generic implementation of the DominanceFrontier class, which
10
+ // calculate and holds the dominance frontier for a function for.
11
+ //
12
+ // This should be considered deprecated, don't add any more uses of this data
13
+ // structure.
14
+ //
15
+ //===----------------------------------------------------------------------===//
16
+
17
+ #ifndef LLVM_ANALYSIS_DOMINANCEFRONTIERIMPL_H
18
+ #define LLVM_ANALYSIS_DOMINANCEFRONTIERIMPL_H
19
+
20
+ #include "llvm/ADT/SmallPtrSet.h"
21
+ #include "llvm/Analysis/DominanceFrontier.h"
22
+ #include "llvm/Config/llvm-config.h"
23
+ #include "llvm/Support/Debug.h"
24
+ #include "llvm/Support/GenericDomTree.h"
25
+ #include "llvm/Support/raw_ostream.h"
26
+ #include <cassert>
27
+ #include <set>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ namespace llvm {
32
+
33
+ template <class BlockT>
34
+ class DFCalculateWorkObject {
35
+ public:
36
+ using DomTreeNodeT = DomTreeNodeBase<BlockT>;
37
+
38
+ DFCalculateWorkObject(BlockT *B, BlockT *P, const DomTreeNodeT *N,
39
+ const DomTreeNodeT *PN)
40
+ : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
41
+
42
+ BlockT *currentBB;
43
+ BlockT *parentBB;
44
+ const DomTreeNodeT *Node;
45
+ const DomTreeNodeT *parentNode;
46
+ };
47
+
48
+ template <class BlockT, bool IsPostDom>
49
+ void DominanceFrontierBase<BlockT, IsPostDom>::print(raw_ostream &OS) const {
50
+ for (const_iterator I = begin(), E = end(); I != E; ++I) {
51
+ OS << " DomFrontier for BB ";
52
+ if (I->first)
53
+ I->first->printAsOperand(OS, false);
54
+ else
55
+ OS << " <<exit node>>";
56
+ OS << " is:\t";
57
+
58
+ const SetVector<BlockT *> &BBs = I->second;
59
+
60
+ for (const BlockT *BB : BBs) {
61
+ OS << ' ';
62
+ if (BB)
63
+ BB->printAsOperand(OS, false);
64
+ else
65
+ OS << "<<exit node>>";
66
+ }
67
+ OS << '\n';
68
+ }
69
+ }
70
+
71
+ #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
72
+ template <class BlockT, bool IsPostDom>
73
+ void DominanceFrontierBase<BlockT, IsPostDom>::dump() const {
74
+ print(dbgs());
75
+ }
76
+ #endif
77
+
78
+ template <class BlockT>
79
+ const typename ForwardDominanceFrontierBase<BlockT>::DomSetType &
80
+ ForwardDominanceFrontierBase<BlockT>::calculate(const DomTreeT &DT,
81
+ const DomTreeNodeT *Node) {
82
+ BlockT *BB = Node->getBlock();
83
+ DomSetType *Result = nullptr;
84
+
85
+ std::vector<DFCalculateWorkObject<BlockT>> workList;
86
+ SmallPtrSet<BlockT *, 32> visited;
87
+
88
+ workList.push_back(DFCalculateWorkObject<BlockT>(BB, nullptr, Node, nullptr));
89
+ do {
90
+ DFCalculateWorkObject<BlockT> *currentW = &workList.back();
91
+ assert(currentW && "Missing work object.");
92
+
93
+ BlockT *currentBB = currentW->currentBB;
94
+ BlockT *parentBB = currentW->parentBB;
95
+ const DomTreeNodeT *currentNode = currentW->Node;
96
+ const DomTreeNodeT *parentNode = currentW->parentNode;
97
+ assert(currentBB && "Invalid work object. Missing current Basic Block");
98
+ assert(currentNode && "Invalid work object. Missing current Node");
99
+ DomSetType &S = this->Frontiers[currentBB];
100
+
101
+ // Visit each block only once.
102
+ if (visited.insert(currentBB).second) {
103
+ // Loop over CFG successors to calculate DFlocal[currentNode]
104
+ for (const auto Succ : children<BlockT *>(currentBB)) {
105
+ // Does Node immediately dominate this successor?
106
+ if (DT[Succ]->getIDom() != currentNode)
107
+ S.insert(Succ);
108
+ }
109
+ }
110
+
111
+ // At this point, S is DFlocal. Now we union in DFup's of our children...
112
+ // Loop through and visit the nodes that Node immediately dominates (Node's
113
+ // children in the IDomTree)
114
+ bool visitChild = false;
115
+ for (typename DomTreeNodeT::const_iterator NI = currentNode->begin(),
116
+ NE = currentNode->end();
117
+ NI != NE; ++NI) {
118
+ DomTreeNodeT *IDominee = *NI;
119
+ BlockT *childBB = IDominee->getBlock();
120
+ if (visited.count(childBB) == 0) {
121
+ workList.push_back(DFCalculateWorkObject<BlockT>(
122
+ childBB, currentBB, IDominee, currentNode));
123
+ visitChild = true;
124
+ }
125
+ }
126
+
127
+ // If all children are visited or there is any child then pop this block
128
+ // from the workList.
129
+ if (!visitChild) {
130
+ if (!parentBB) {
131
+ Result = &S;
132
+ break;
133
+ }
134
+
135
+ typename DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
136
+ DomSetType &parentSet = this->Frontiers[parentBB];
137
+ for (; CDFI != CDFE; ++CDFI) {
138
+ if (!DT.properlyDominates(parentNode, DT[*CDFI]))
139
+ parentSet.insert(*CDFI);
140
+ }
141
+ workList.pop_back();
142
+ }
143
+
144
+ } while (!workList.empty());
145
+
146
+ return *Result;
147
+ }
148
+
149
+ } // end namespace llvm
150
+
151
+ #endif // LLVM_ANALYSIS_DOMINANCEFRONTIERIMPL_H
deps/exla/cache/xla_extension/include/llvm/Analysis/FloatingPointPredicateUtils.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/FloatingPointPredicateUtils.h ------------*- C++ -*---===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ #ifndef LLVM_ANALYSIS_FLOATINGPOINTPREDICATEUTILS_H
10
+ #define LLVM_ANALYSIS_FLOATINGPOINTPREDICATEUTILS_H
11
+
12
+ #include "llvm/IR/GenericFloatingPointPredicateUtils.h"
13
+ #include "llvm/IR/SSAContext.h"
14
+ #include "llvm/Support/Compiler.h"
15
+
16
+ namespace llvm {
17
+
18
+ using FloatingPointPredicateUtils =
19
+ GenericFloatingPointPredicateUtils<SSAContext>;
20
+
21
+ template <>
22
+ LLVM_ABI DenormalMode
23
+ FloatingPointPredicateUtils::queryDenormalMode(const Function &F, Value *Val);
24
+
25
+ template <>
26
+ LLVM_ABI bool FloatingPointPredicateUtils::lookThroughFAbs(const Function &F,
27
+ Value *LHS,
28
+ Value *&Src);
29
+
30
+ template <>
31
+ LLVM_ABI std::optional<APFloat>
32
+ FloatingPointPredicateUtils::matchConstantFloat(const Function &F, Value *Val);
33
+
34
+ /// Returns a pair of values, which if passed to llvm.is.fpclass, returns the
35
+ /// same result as an fcmp with the given operands.
36
+ ///
37
+ /// If \p LookThroughSrc is true, consider the input value when computing the
38
+ /// mask.
39
+ ///
40
+ /// If \p LookThroughSrc is false, ignore the source value (i.e. the first pair
41
+ /// element will always be LHS.
42
+ inline std::pair<Value *, FPClassTest>
43
+ fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS,
44
+ Value *RHS, bool LookThroughSrc = true) {
45
+ return FloatingPointPredicateUtils::fcmpToClassTest(Pred, F, LHS, RHS,
46
+ LookThroughSrc = true);
47
+ }
48
+
49
+ /// Returns a pair of values, which if passed to llvm.is.fpclass, returns the
50
+ /// same result as an fcmp with the given operands.
51
+ ///
52
+ /// If \p LookThroughSrc is true, consider the input value when computing the
53
+ /// mask.
54
+ ///
55
+ /// If \p LookThroughSrc is false, ignore the source value (i.e. the first pair
56
+ /// element will always be LHS.
57
+ inline std::pair<Value *, FPClassTest>
58
+ fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS,
59
+ const APFloat *ConstRHS, bool LookThroughSrc = true) {
60
+ return FloatingPointPredicateUtils::fcmpToClassTest(Pred, F, LHS, *ConstRHS,
61
+ LookThroughSrc);
62
+ }
63
+
64
+ inline std::tuple<Value *, FPClassTest, FPClassTest>
65
+ fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS,
66
+ FPClassTest RHSClass, bool LookThroughSrc = true) {
67
+ return FloatingPointPredicateUtils::fcmpImpliesClass(Pred, F, LHS, RHSClass,
68
+ LookThroughSrc);
69
+ }
70
+
71
+ inline std::tuple<Value *, FPClassTest, FPClassTest>
72
+ fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS,
73
+ const APFloat &ConstRHS, bool LookThroughSrc = true) {
74
+ return FloatingPointPredicateUtils::fcmpImpliesClass(Pred, F, LHS, ConstRHS,
75
+ LookThroughSrc);
76
+ }
77
+
78
+ inline std::tuple<Value *, FPClassTest, FPClassTest>
79
+ fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS,
80
+ Value *RHS, bool LookThroughSrc = true) {
81
+ return FloatingPointPredicateUtils::fcmpImpliesClass(Pred, F, LHS, RHS,
82
+ LookThroughSrc);
83
+ }
84
+
85
+ } // namespace llvm
86
+
87
+ #endif // LLVM_ANALYSIS_FLOATINGPOINTPREDICATEUTILS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/FunctionPropertiesAnalysis.h ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //=- FunctionPropertiesAnalysis.h - Function Properties Analysis --*- C++ -*-=//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the FunctionPropertiesInfo and FunctionPropertiesAnalysis
10
+ // classes used to extract function properties.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_FUNCTIONPROPERTIESANALYSIS_H
15
+ #define LLVM_ANALYSIS_FUNCTIONPROPERTIESANALYSIS_H
16
+
17
+ #include "llvm/ADT/DenseSet.h"
18
+ #include "llvm/IR/Dominators.h"
19
+ #include "llvm/IR/PassManager.h"
20
+ #include "llvm/Support/Compiler.h"
21
+
22
+ namespace llvm {
23
+ class BasicBlock;
24
+ class CallBase;
25
+ class DominatorTree;
26
+ class Function;
27
+ class LoopInfo;
28
+
29
+ class FunctionPropertiesInfo {
30
+ friend class FunctionPropertiesUpdater;
31
+ void updateForBB(const BasicBlock &BB, int64_t Direction);
32
+ void updateAggregateStats(const Function &F, const LoopInfo &LI);
33
+ void reIncludeBB(const BasicBlock &BB);
34
+
35
+ public:
36
+ LLVM_ABI static FunctionPropertiesInfo
37
+ getFunctionPropertiesInfo(const Function &F, const DominatorTree &DT,
38
+ const LoopInfo &LI);
39
+
40
+ LLVM_ABI static FunctionPropertiesInfo
41
+ getFunctionPropertiesInfo(Function &F, FunctionAnalysisManager &FAM);
42
+
43
+ bool operator==(const FunctionPropertiesInfo &FPI) const {
44
+ return std::memcmp(this, &FPI, sizeof(FunctionPropertiesInfo)) == 0;
45
+ }
46
+
47
+ bool operator!=(const FunctionPropertiesInfo &FPI) const {
48
+ return !(*this == FPI);
49
+ }
50
+
51
+ LLVM_ABI void print(raw_ostream &OS) const;
52
+
53
+ /// Number of basic blocks
54
+ int64_t BasicBlockCount = 0;
55
+
56
+ /// Number of blocks reached from a conditional instruction, or that are
57
+ /// 'cases' of a SwitchInstr.
58
+ // FIXME: We may want to replace this with a more meaningful metric, like
59
+ // number of conditionally executed blocks:
60
+ // 'if (a) s();' would be counted here as 2 blocks, just like
61
+ // 'if (a) s(); else s2(); s3();' would.
62
+ int64_t BlocksReachedFromConditionalInstruction = 0;
63
+
64
+ /// Number of uses of this function, plus 1 if the function is callable
65
+ /// outside the module.
66
+ int64_t Uses = 0;
67
+
68
+ /// Number of direct calls made from this function to other functions
69
+ /// defined in this module.
70
+ int64_t DirectCallsToDefinedFunctions = 0;
71
+
72
+ // Load Instruction Count
73
+ int64_t LoadInstCount = 0;
74
+
75
+ // Store Instruction Count
76
+ int64_t StoreInstCount = 0;
77
+
78
+ // Maximum Loop Depth in the Function
79
+ int64_t MaxLoopDepth = 0;
80
+
81
+ // Number of Top Level Loops in the Function
82
+ int64_t TopLevelLoopCount = 0;
83
+
84
+ // All non-debug instructions
85
+ int64_t TotalInstructionCount = 0;
86
+
87
+ // Basic blocks grouped by number of successors.
88
+ int64_t BasicBlocksWithSingleSuccessor = 0;
89
+ int64_t BasicBlocksWithTwoSuccessors = 0;
90
+ int64_t BasicBlocksWithMoreThanTwoSuccessors = 0;
91
+
92
+ // Basic blocks grouped by number of predecessors.
93
+ int64_t BasicBlocksWithSinglePredecessor = 0;
94
+ int64_t BasicBlocksWithTwoPredecessors = 0;
95
+ int64_t BasicBlocksWithMoreThanTwoPredecessors = 0;
96
+
97
+ // Basic blocks grouped by size as determined by the number of non-debug
98
+ // instructions that they contain.
99
+ int64_t BigBasicBlocks = 0;
100
+ int64_t MediumBasicBlocks = 0;
101
+ int64_t SmallBasicBlocks = 0;
102
+
103
+ // The number of cast instructions inside the function.
104
+ int64_t CastInstructionCount = 0;
105
+
106
+ // The number of floating point instructions inside the function.
107
+ int64_t FloatingPointInstructionCount = 0;
108
+
109
+ // The number of integer instructions inside the function.
110
+ int64_t IntegerInstructionCount = 0;
111
+
112
+ // Operand type couns
113
+ int64_t ConstantIntOperandCount = 0;
114
+ int64_t ConstantFPOperandCount = 0;
115
+ int64_t ConstantOperandCount = 0;
116
+ int64_t InstructionOperandCount = 0;
117
+ int64_t BasicBlockOperandCount = 0;
118
+ int64_t GlobalValueOperandCount = 0;
119
+ int64_t InlineAsmOperandCount = 0;
120
+ int64_t ArgumentOperandCount = 0;
121
+ int64_t UnknownOperandCount = 0;
122
+
123
+ // Additional CFG Properties
124
+ int64_t CriticalEdgeCount = 0;
125
+ int64_t ControlFlowEdgeCount = 0;
126
+ int64_t UnconditionalBranchCount = 0;
127
+
128
+ // Call related instructions
129
+ int64_t IntrinsicCount = 0;
130
+ int64_t DirectCallCount = 0;
131
+ int64_t IndirectCallCount = 0;
132
+ int64_t CallReturnsIntegerCount = 0;
133
+ int64_t CallReturnsFloatCount = 0;
134
+ int64_t CallReturnsPointerCount = 0;
135
+ int64_t CallReturnsVectorIntCount = 0;
136
+ int64_t CallReturnsVectorFloatCount = 0;
137
+ int64_t CallReturnsVectorPointerCount = 0;
138
+ int64_t CallWithManyArgumentsCount = 0;
139
+ int64_t CallWithPointerArgumentCount = 0;
140
+ };
141
+
142
+ // Analysis pass
143
+ class FunctionPropertiesAnalysis
144
+ : public AnalysisInfoMixin<FunctionPropertiesAnalysis> {
145
+
146
+ public:
147
+ LLVM_ABI static AnalysisKey Key;
148
+
149
+ using Result = const FunctionPropertiesInfo;
150
+
151
+ LLVM_ABI FunctionPropertiesInfo run(Function &F,
152
+ FunctionAnalysisManager &FAM);
153
+ };
154
+
155
+ /// Printer pass for the FunctionPropertiesAnalysis results.
156
+ class FunctionPropertiesPrinterPass
157
+ : public PassInfoMixin<FunctionPropertiesPrinterPass> {
158
+ raw_ostream &OS;
159
+
160
+ public:
161
+ explicit FunctionPropertiesPrinterPass(raw_ostream &OS) : OS(OS) {}
162
+
163
+ LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
164
+
165
+ static bool isRequired() { return true; }
166
+ };
167
+
168
+ /// Correctly update FunctionPropertiesInfo post-inlining. A
169
+ /// FunctionPropertiesUpdater keeps the state necessary for tracking the changes
170
+ /// llvm::InlineFunction makes. The idea is that inlining will at most modify
171
+ /// a few BBs of the Caller (maybe the entry BB and definitely the callsite BB)
172
+ /// and potentially affect exception handling BBs in the case of invoke
173
+ /// inlining.
174
+ class FunctionPropertiesUpdater {
175
+ public:
176
+ LLVM_ABI FunctionPropertiesUpdater(FunctionPropertiesInfo &FPI, CallBase &CB);
177
+
178
+ LLVM_ABI void finish(FunctionAnalysisManager &FAM) const;
179
+ bool finishAndTest(FunctionAnalysisManager &FAM) const {
180
+ finish(FAM);
181
+ return isUpdateValid(Caller, FPI, FAM);
182
+ }
183
+
184
+ private:
185
+ FunctionPropertiesInfo &FPI;
186
+ BasicBlock &CallSiteBB;
187
+ Function &Caller;
188
+
189
+ LLVM_ABI static bool isUpdateValid(Function &F,
190
+ const FunctionPropertiesInfo &FPI,
191
+ FunctionAnalysisManager &FAM);
192
+
193
+ DominatorTree &getUpdatedDominatorTree(FunctionAnalysisManager &FAM) const;
194
+
195
+ DenseSet<const BasicBlock *> Successors;
196
+
197
+ // Edges we might potentially need to remove from the dominator tree.
198
+ SmallVector<DominatorTree::UpdateType, 2> DomTreeUpdates;
199
+ };
200
+ } // namespace llvm
201
+ #endif // LLVM_ANALYSIS_FUNCTIONPROPERTIESANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/GlobalsModRef.h ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- GlobalsModRef.h - Simple Mod/Ref AA for Globals ----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ /// This is the interface for a simple mod/ref and alias analysis over globals.
10
+ ///
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_GLOBALSMODREF_H
14
+ #define LLVM_ANALYSIS_GLOBALSMODREF_H
15
+
16
+ #include "llvm/Analysis/AliasAnalysis.h"
17
+ #include "llvm/IR/PassManager.h"
18
+ #include "llvm/IR/ValueHandle.h"
19
+ #include "llvm/Pass.h"
20
+ #include "llvm/Support/Compiler.h"
21
+ #include <list>
22
+
23
+ namespace llvm {
24
+ class CallGraph;
25
+ class Function;
26
+
27
+ /// An alias analysis result set for globals.
28
+ ///
29
+ /// This focuses on handling aliasing properties of globals and interprocedural
30
+ /// function call mod/ref information.
31
+ class GlobalsAAResult : public AAResultBase {
32
+ class FunctionInfo;
33
+
34
+ const DataLayout &DL;
35
+ std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
36
+
37
+ /// The globals that do not have their addresses taken.
38
+ SmallPtrSet<const GlobalValue *, 8> NonAddressTakenGlobals;
39
+
40
+ /// Are there functions with local linkage that may modify globals.
41
+ bool UnknownFunctionsWithLocalLinkage = false;
42
+
43
+ /// IndirectGlobals - The memory pointed to by this global is known to be
44
+ /// 'owned' by the global.
45
+ SmallPtrSet<const GlobalValue *, 8> IndirectGlobals;
46
+
47
+ /// AllocsForIndirectGlobals - If an instruction allocates memory for an
48
+ /// indirect global, this map indicates which one.
49
+ DenseMap<const Value *, const GlobalValue *> AllocsForIndirectGlobals;
50
+
51
+ /// For each function, keep track of what globals are modified or read.
52
+ DenseMap<const Function *, FunctionInfo> FunctionInfos;
53
+
54
+ /// A map of functions to SCC. The SCCs are described by a simple integer
55
+ /// ID that is only useful for comparing for equality (are two functions
56
+ /// in the same SCC or not?)
57
+ DenseMap<const Function *, unsigned> FunctionToSCCMap;
58
+
59
+ /// Handle to clear this analysis on deletion of values.
60
+ struct LLVM_ABI DeletionCallbackHandle final : CallbackVH {
61
+ GlobalsAAResult *GAR;
62
+ std::list<DeletionCallbackHandle>::iterator I;
63
+
64
+ DeletionCallbackHandle(GlobalsAAResult &GAR, Value *V)
65
+ : CallbackVH(V), GAR(&GAR) {}
66
+
67
+ void deleted() override;
68
+ };
69
+
70
+ /// List of callbacks for globals being tracked by this analysis. Note that
71
+ /// these objects are quite large, but we only anticipate having one per
72
+ /// global tracked by this analysis. There are numerous optimizations we
73
+ /// could perform to the memory utilization here if this becomes a problem.
74
+ std::list<DeletionCallbackHandle> Handles;
75
+
76
+ explicit GlobalsAAResult(
77
+ const DataLayout &DL,
78
+ std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
79
+
80
+ friend struct RecomputeGlobalsAAPass;
81
+
82
+ public:
83
+ LLVM_ABI GlobalsAAResult(GlobalsAAResult &&Arg);
84
+ LLVM_ABI ~GlobalsAAResult();
85
+
86
+ LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA,
87
+ ModuleAnalysisManager::Invalidator &);
88
+
89
+ LLVM_ABI static GlobalsAAResult
90
+ analyzeModule(Module &M,
91
+ std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
92
+ CallGraph &CG);
93
+
94
+ //------------------------------------------------
95
+ // Implement the AliasAnalysis API
96
+ //
97
+ LLVM_ABI AliasResult alias(const MemoryLocation &LocA,
98
+ const MemoryLocation &LocB, AAQueryInfo &AAQI,
99
+ const Instruction *CtxI);
100
+
101
+ using AAResultBase::getModRefInfo;
102
+ LLVM_ABI ModRefInfo getModRefInfo(const CallBase *Call,
103
+ const MemoryLocation &Loc,
104
+ AAQueryInfo &AAQI);
105
+
106
+ using AAResultBase::getMemoryEffects;
107
+ /// getMemoryEffects - Return the behavior of the specified function if
108
+ /// called from the specified call site. The call site may be null in which
109
+ /// case the most generic behavior of this function should be returned.
110
+ LLVM_ABI MemoryEffects getMemoryEffects(const Function *F);
111
+
112
+ private:
113
+ FunctionInfo *getFunctionInfo(const Function *F);
114
+
115
+ void AnalyzeGlobals(Module &M);
116
+ void AnalyzeCallGraph(CallGraph &CG, Module &M);
117
+ bool AnalyzeUsesOfPointer(Value *V,
118
+ SmallPtrSetImpl<Function *> *Readers = nullptr,
119
+ SmallPtrSetImpl<Function *> *Writers = nullptr,
120
+ GlobalValue *OkayStoreDest = nullptr);
121
+ bool AnalyzeIndirectGlobalMemory(GlobalVariable *GV);
122
+ void CollectSCCMembership(CallGraph &CG);
123
+
124
+ bool isNonEscapingGlobalNoAlias(const GlobalValue *GV, const Value *V,
125
+ const Instruction *CtxI);
126
+ ModRefInfo getModRefInfoForArgument(const CallBase *Call,
127
+ const GlobalValue *GV, AAQueryInfo &AAQI);
128
+ };
129
+
130
+ /// Analysis pass providing a never-invalidated alias analysis result.
131
+ class GlobalsAA : public AnalysisInfoMixin<GlobalsAA> {
132
+ friend AnalysisInfoMixin<GlobalsAA>;
133
+ LLVM_ABI static AnalysisKey Key;
134
+
135
+ public:
136
+ typedef GlobalsAAResult Result;
137
+
138
+ LLVM_ABI GlobalsAAResult run(Module &M, ModuleAnalysisManager &AM);
139
+ };
140
+
141
+ struct RecomputeGlobalsAAPass : PassInfoMixin<RecomputeGlobalsAAPass> {
142
+ LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
143
+ };
144
+
145
+ /// Legacy wrapper pass to provide the GlobalsAAResult object.
146
+ class LLVM_ABI GlobalsAAWrapperPass : public ModulePass {
147
+ std::unique_ptr<GlobalsAAResult> Result;
148
+
149
+ public:
150
+ static char ID;
151
+
152
+ GlobalsAAWrapperPass();
153
+
154
+ GlobalsAAResult &getResult() { return *Result; }
155
+ const GlobalsAAResult &getResult() const { return *Result; }
156
+
157
+ bool runOnModule(Module &M) override;
158
+ bool doFinalization(Module &M) override;
159
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
160
+ };
161
+
162
+ //===--------------------------------------------------------------------===//
163
+ //
164
+ // createGlobalsAAWrapperPass - This pass provides alias and mod/ref info for
165
+ // global values that do not have their addresses taken.
166
+ //
167
+ LLVM_ABI ModulePass *createGlobalsAAWrapperPass();
168
+ }
169
+
170
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/GuardUtils.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- GuardUtils.h - Utils for work with guards ---------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ // Utils that are used to perform analyzes related to guards and their
9
+ // conditions.
10
+ //===----------------------------------------------------------------------===//
11
+
12
+ #ifndef LLVM_ANALYSIS_GUARDUTILS_H
13
+ #define LLVM_ANALYSIS_GUARDUTILS_H
14
+
15
+ namespace llvm {
16
+
17
+ class BasicBlock;
18
+ class Use;
19
+ class User;
20
+ class Value;
21
+ template <typename T> class SmallVectorImpl;
22
+
23
+ /// Returns true iff \p U has semantics of a guard expressed in a form of call
24
+ /// of llvm.experimental.guard intrinsic.
25
+ bool isGuard(const User *U);
26
+
27
+ /// Returns true iff \p V has semantics of llvm.experimental.widenable.condition
28
+ /// call
29
+ bool isWidenableCondition(const Value *V);
30
+
31
+ /// Returns true iff \p U is a widenable branch (that is,
32
+ /// extractWidenableCondition returns widenable condition).
33
+ bool isWidenableBranch(const User *U);
34
+
35
+ /// Returns true iff \p U has semantics of a guard expressed in a form of a
36
+ /// widenable conditional branch to deopt block.
37
+ bool isGuardAsWidenableBranch(const User *U);
38
+
39
+ /// If U is widenable branch looking like:
40
+ /// %cond = ...
41
+ /// %wc = call i1 @llvm.experimental.widenable.condition()
42
+ /// %branch_cond = and i1 %cond, %wc
43
+ /// br i1 %branch_cond, label %if_true_bb, label %if_false_bb ; <--- U
44
+ /// The function returns true, and the values %cond and %wc and blocks
45
+ /// %if_true_bb, if_false_bb are returned in
46
+ /// the parameters (Condition, WidenableCondition, IfTrueBB and IfFalseFF)
47
+ /// respectively. If \p U does not match this pattern, return false.
48
+ bool parseWidenableBranch(const User *U, Value *&Condition,
49
+ Value *&WidenableCondition, BasicBlock *&IfTrueBB,
50
+ BasicBlock *&IfFalseBB);
51
+
52
+ /// Analogous to the above, but return the Uses so that they can be
53
+ /// modified. Unlike previous version, Condition is optional and may be null.
54
+ bool parseWidenableBranch(User *U, Use *&Cond, Use *&WC, BasicBlock *&IfTrueBB,
55
+ BasicBlock *&IfFalseBB);
56
+
57
+ // The guard condition is expected to be in form of:
58
+ // cond1 && cond2 && cond3 ...
59
+ // or in case of widenable branch:
60
+ // cond1 && cond2 && cond3 && widenable_contidion ...
61
+ // Method collects the list of checks, but skips widenable_condition.
62
+ void parseWidenableGuard(const User *U, llvm::SmallVectorImpl<Value *> &Checks);
63
+
64
+ // Returns widenable_condition if it exists in the expression tree rooting from
65
+ // \p U and has only one use.
66
+ Value *extractWidenableCondition(const User *U);
67
+ } // llvm
68
+
69
+ #endif // LLVM_ANALYSIS_GUARDUTILS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/HeatUtils.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- HeatUtils.h - Utility for printing heat colors ----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // Utility for printing heat colors based on profiling information.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_HEATUTILS_H
14
+ #define LLVM_ANALYSIS_HEATUTILS_H
15
+
16
+ #include "llvm/Support/Compiler.h"
17
+ #include <cstdint>
18
+ #include <string>
19
+
20
+ namespace llvm {
21
+
22
+ class BlockFrequencyInfo;
23
+ class Function;
24
+
25
+ // Returns number of calls of calledFunction by callerFunction.
26
+ LLVM_ABI uint64_t getNumOfCalls(Function &callerFunction,
27
+ Function &calledFunction);
28
+
29
+ // Returns the maximum frequency of a BB in a function.
30
+ LLVM_ABI uint64_t getMaxFreq(const Function &F, const BlockFrequencyInfo *BFI);
31
+
32
+ // Calculates heat color based on current and maximum frequencies.
33
+ LLVM_ABI std::string getHeatColor(uint64_t freq, uint64_t maxFreq);
34
+
35
+ // Calculates heat color based on percent of "hotness".
36
+ LLVM_ABI std::string getHeatColor(double percent);
37
+
38
+ } // namespace llvm
39
+
40
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/IndirectCallVisitor.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- IndirectCallVisitor.h - indirect call visitor ---------------------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file implements defines a visitor class and a helper function that find
10
+ // all indirect call-sites in a function.
11
+
12
+ #ifndef LLVM_ANALYSIS_INDIRECTCALLVISITOR_H
13
+ #define LLVM_ANALYSIS_INDIRECTCALLVISITOR_H
14
+
15
+ #include "llvm/IR/InstVisitor.h"
16
+ #include <vector>
17
+
18
+ namespace llvm {
19
+ // Visitor class that finds indirect calls or instructions that gives vtable
20
+ // value, depending on Type.
21
+ struct PGOIndirectCallVisitor : public InstVisitor<PGOIndirectCallVisitor> {
22
+ enum class InstructionType {
23
+ kIndirectCall = 0,
24
+ kVTableVal = 1,
25
+ };
26
+ std::vector<CallBase *> IndirectCalls;
27
+ std::vector<Instruction *> ProfiledAddresses;
28
+ PGOIndirectCallVisitor(InstructionType Type) : Type(Type) {}
29
+
30
+ // Given an indirect call instruction, try to find the the following pattern
31
+ //
32
+ // %vtable = load ptr, ptr %obj
33
+ // %vfn = getelementptr inbounds ptr, ptr %vtable, i64 1
34
+ // %2 = load ptr, ptr %vfn
35
+ // $call = tail call i32 %2
36
+ //
37
+ // A heuristic is used to find the address feeding instructions.
38
+ static Instruction *tryGetVTableInstruction(CallBase *CB) {
39
+ assert(CB != nullptr && "Caller guaranteed");
40
+ if (!CB->isIndirectCall())
41
+ return nullptr;
42
+
43
+ LoadInst *LI = dyn_cast<LoadInst>(CB->getCalledOperand());
44
+ if (LI != nullptr) {
45
+ Value *FuncPtr = LI->getPointerOperand(); // GEP (or bitcast)
46
+ Value *VTablePtr = FuncPtr->stripInBoundsConstantOffsets();
47
+ // FIXME: Add support in the frontend so LLVM type intrinsics are
48
+ // emitted without LTO. This way, added intrinsics could filter
49
+ // non-vtable instructions and reduce instrumentation overhead.
50
+ // Since a non-vtable profiled address is not within the address
51
+ // range of vtable objects, it's stored as zero in indexed profiles.
52
+ // A pass that looks up symbol with an zero hash will (almost) always
53
+ // find nullptr and skip the actual transformation (e.g., comparison
54
+ // of symbols). So the performance overhead from non-vtable profiled
55
+ // address is negligible if exists at all. Comparing loaded address
56
+ // with symbol address guarantees correctness.
57
+ if (VTablePtr != nullptr && isa<Instruction>(VTablePtr))
58
+ return cast<Instruction>(VTablePtr);
59
+ }
60
+ return nullptr;
61
+ }
62
+
63
+ void visitCallBase(CallBase &Call) {
64
+ if (Call.isIndirectCall()) {
65
+ IndirectCalls.push_back(&Call);
66
+
67
+ if (Type != InstructionType::kVTableVal)
68
+ return;
69
+
70
+ Instruction *VPtr =
71
+ PGOIndirectCallVisitor::tryGetVTableInstruction(&Call);
72
+ if (VPtr)
73
+ ProfiledAddresses.push_back(VPtr);
74
+ }
75
+ }
76
+
77
+ private:
78
+ InstructionType Type;
79
+ };
80
+
81
+ inline std::vector<CallBase *> findIndirectCalls(Function &F) {
82
+ PGOIndirectCallVisitor ICV(
83
+ PGOIndirectCallVisitor::InstructionType::kIndirectCall);
84
+ ICV.visit(F);
85
+ return ICV.IndirectCalls;
86
+ }
87
+
88
+ inline std::vector<Instruction *> findVTableAddrs(Function &F) {
89
+ PGOIndirectCallVisitor ICV(
90
+ PGOIndirectCallVisitor::InstructionType::kVTableVal);
91
+ ICV.visit(F);
92
+ return ICV.ProfiledAddresses;
93
+ }
94
+
95
+ } // namespace llvm
96
+
97
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/InlineSizeEstimatorAnalysis.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- InlineSizeEstimatorAnalysis.h - ML size estimator --------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+
10
+ #ifndef LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
11
+ #define LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
12
+
13
+ #include "llvm/IR/PassManager.h"
14
+
15
+ namespace llvm {
16
+ class Function;
17
+
18
+ class TFModelEvaluator;
19
+ class InlineSizeEstimatorAnalysis
20
+ : public AnalysisInfoMixin<InlineSizeEstimatorAnalysis> {
21
+ public:
22
+ InlineSizeEstimatorAnalysis();
23
+ InlineSizeEstimatorAnalysis(InlineSizeEstimatorAnalysis &&);
24
+ ~InlineSizeEstimatorAnalysis();
25
+
26
+ static AnalysisKey Key;
27
+ using Result = std::optional<size_t>;
28
+ Result run(const Function &F, FunctionAnalysisManager &FAM);
29
+ static bool isEvaluatorRequested();
30
+
31
+ private:
32
+ std::unique_ptr<TFModelEvaluator> Evaluator;
33
+ };
34
+
35
+ class InlineSizeEstimatorAnalysisPrinterPass
36
+ : public PassInfoMixin<InlineSizeEstimatorAnalysisPrinterPass> {
37
+ raw_ostream &OS;
38
+
39
+ public:
40
+ explicit InlineSizeEstimatorAnalysisPrinterPass(raw_ostream &OS) : OS(OS) {}
41
+
42
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
43
+
44
+ static bool isRequired() { return true; }
45
+ };
46
+ } // namespace llvm
47
+ #endif // LLVM_ANALYSIS_INLINESIZEESTIMATORANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/InstCount.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- InstCount.h - Collects the count of all instructions -----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This pass collects the count of all instructions and reports them
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_INSTCOUNT_H
14
+ #define LLVM_ANALYSIS_INSTCOUNT_H
15
+
16
+ #include "llvm/IR/PassManager.h"
17
+
18
+ namespace llvm {
19
+
20
+ class Function;
21
+
22
+ struct InstCountPass : PassInfoMixin<InstCountPass> {
23
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &);
24
+ };
25
+
26
+ } // end namespace llvm
27
+
28
+ #endif // LLVM_ANALYSIS_INSTCOUNT_H
deps/exla/cache/xla_extension/include/llvm/Analysis/InstructionPrecedenceTracking.h ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- InstructionPrecedenceTracking.h -------------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ // Implements a class that is able to define some instructions as "special"
9
+ // (e.g. as having implicit control flow, or writing memory, or having another
10
+ // interesting property) and then efficiently answers queries of the types:
11
+ // 1. Are there any special instructions in the block of interest?
12
+ // 2. Return first of the special instructions in the given block;
13
+ // 3. Check if the given instruction is preceeded by the first special
14
+ // instruction in the same block.
15
+ // The class provides caching that allows to answer these queries quickly. The
16
+ // user must make sure that the cached data is invalidated properly whenever
17
+ // a content of some tracked block is changed.
18
+ //===----------------------------------------------------------------------===//
19
+
20
+ #ifndef LLVM_ANALYSIS_INSTRUCTIONPRECEDENCETRACKING_H
21
+ #define LLVM_ANALYSIS_INSTRUCTIONPRECEDENCETRACKING_H
22
+
23
+ #include "llvm/ADT/DenseMap.h"
24
+ #include "llvm/Support/Compiler.h"
25
+
26
+ namespace llvm {
27
+
28
+ class BasicBlock;
29
+ class Instruction;
30
+
31
+ class InstructionPrecedenceTracking {
32
+ // Maps a block to the topmost special instruction in it. If the value is
33
+ // nullptr, it means that it is known that this block does not contain any
34
+ // special instructions.
35
+ DenseMap<const BasicBlock *, const Instruction *> FirstSpecialInsts;
36
+
37
+ #ifndef NDEBUG
38
+ /// Asserts that the cached info for \p BB is up-to-date. This helps to catch
39
+ /// the usage error of accessing a block without properly invalidating after a
40
+ /// previous transform.
41
+ void validate(const BasicBlock *BB) const;
42
+
43
+ /// Asserts whether or not the contents of this tracking is up-to-date. This
44
+ /// helps to catch the usage error of accessing a block without properly
45
+ /// invalidating after a previous transform.
46
+ void validateAll() const;
47
+ #endif
48
+
49
+ protected:
50
+ /// Returns the topmost special instruction from the block \p BB. Returns
51
+ /// nullptr if there is no special instructions in the block.
52
+ LLVM_ABI const Instruction *getFirstSpecialInstruction(const BasicBlock *BB);
53
+
54
+ /// Returns true iff at least one instruction from the basic block \p BB is
55
+ /// special.
56
+ LLVM_ABI bool hasSpecialInstructions(const BasicBlock *BB);
57
+
58
+ /// Returns true iff the first special instruction of \p Insn's block exists
59
+ /// and dominates \p Insn.
60
+ LLVM_ABI bool isPreceededBySpecialInstruction(const Instruction *Insn);
61
+
62
+ /// A predicate that defines whether or not the instruction \p Insn is
63
+ /// considered special and needs to be tracked. Implementing this method in
64
+ /// children classes allows to implement tracking of implicit control flow,
65
+ /// memory writing instructions or any other kinds of instructions we might
66
+ /// be interested in.
67
+ virtual bool isSpecialInstruction(const Instruction *Insn) const = 0;
68
+
69
+ virtual ~InstructionPrecedenceTracking() = default;
70
+
71
+ public:
72
+ /// Notifies this tracking that we are going to insert a new instruction \p
73
+ /// Inst to the basic block \p BB. It makes all necessary updates to internal
74
+ /// caches to keep them consistent.
75
+ LLVM_ABI void insertInstructionTo(const Instruction *Inst,
76
+ const BasicBlock *BB);
77
+
78
+ /// Notifies this tracking that we are going to remove the instruction \p Inst
79
+ /// It makes all necessary updates to internal caches to keep them consistent.
80
+ LLVM_ABI void removeInstruction(const Instruction *Inst);
81
+
82
+ /// Notifies this tracking that we are going to replace all uses of \p Inst.
83
+ /// It makes all necessary updates to internal caches to keep them consistent.
84
+ /// Should typically be called before a RAUW.
85
+ LLVM_ABI void removeUsersOf(const Instruction *Inst);
86
+
87
+ /// Invalidates all information from this tracking.
88
+ LLVM_ABI void clear();
89
+ };
90
+
91
+ /// This class allows to keep track on instructions with implicit control flow.
92
+ /// These are instructions that may not pass execution to their successors. For
93
+ /// example, throwing calls and guards do not always do this. If we need to know
94
+ /// for sure that some instruction is guaranteed to execute if the given block
95
+ /// is reached, then we need to make sure that there is no implicit control flow
96
+ /// instruction (ICFI) preceding it. For example, this check is required if we
97
+ /// perform PRE moving non-speculable instruction to other place.
98
+ class LLVM_ABI ImplicitControlFlowTracking
99
+ : public InstructionPrecedenceTracking {
100
+ public:
101
+ /// Returns the topmost instruction with implicit control flow from the given
102
+ /// basic block. Returns nullptr if there is no such instructions in the block.
103
+ const Instruction *getFirstICFI(const BasicBlock *BB) {
104
+ return getFirstSpecialInstruction(BB);
105
+ }
106
+
107
+ /// Returns true if at least one instruction from the given basic block has
108
+ /// implicit control flow.
109
+ bool hasICF(const BasicBlock *BB) {
110
+ return hasSpecialInstructions(BB);
111
+ }
112
+
113
+ /// Returns true if the first ICFI of Insn's block exists and dominates Insn.
114
+ bool isDominatedByICFIFromSameBlock(const Instruction *Insn) {
115
+ return isPreceededBySpecialInstruction(Insn);
116
+ }
117
+
118
+ bool isSpecialInstruction(const Instruction *Insn) const override;
119
+ };
120
+
121
+ class LLVM_ABI MemoryWriteTracking : public InstructionPrecedenceTracking {
122
+ public:
123
+ /// Returns the topmost instruction that may write memory from the given
124
+ /// basic block. Returns nullptr if there is no such instructions in the block.
125
+ const Instruction *getFirstMemoryWrite(const BasicBlock *BB) {
126
+ return getFirstSpecialInstruction(BB);
127
+ }
128
+
129
+ /// Returns true if at least one instruction from the given basic block may
130
+ /// write memory.
131
+ bool mayWriteToMemory(const BasicBlock *BB) {
132
+ return hasSpecialInstructions(BB);
133
+ }
134
+
135
+ /// Returns true if the first memory writing instruction of Insn's block
136
+ /// exists and dominates Insn.
137
+ bool isDominatedByMemoryWriteFromSameBlock(const Instruction *Insn) {
138
+ return isPreceededBySpecialInstruction(Insn);
139
+ }
140
+
141
+ bool isSpecialInstruction(const Instruction *Insn) const override;
142
+ };
143
+
144
+ } // llvm
145
+
146
+ #endif // LLVM_ANALYSIS_INSTRUCTIONPRECEDENCETRACKING_H
deps/exla/cache/xla_extension/include/llvm/Analysis/InstructionSimplify.h ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- InstructionSimplify.h - Fold instrs into simpler forms --*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file declares routines for folding instructions into simpler forms
10
+ // that do not require creating new instructions. This does constant folding
11
+ // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12
+ // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13
+ // ("and i32 %x, %x" -> "%x"). If the simplification is also an instruction
14
+ // then it dominates the original instruction.
15
+ //
16
+ // These routines implicitly resolve undef uses. The easiest way to be safe when
17
+ // using these routines to obtain simplified values for existing instructions is
18
+ // to always replace all uses of the instructions with the resulting simplified
19
+ // values. This will prevent other code from seeing the same undef uses and
20
+ // resolving them to different values.
21
+ //
22
+ // They require that all the IR that they encounter be valid and inserted into a
23
+ // parent function.
24
+ //
25
+ // Additionally, these routines can't simplify to the instructions that are not
26
+ // def-reachable, meaning we can't just scan the basic block for instructions
27
+ // to simplify to.
28
+ //
29
+ //===----------------------------------------------------------------------===//
30
+
31
+ #ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
32
+ #define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
33
+
34
+ #include "llvm/Analysis/SimplifyQuery.h"
35
+ #include "llvm/IR/FPEnv.h"
36
+ #include "llvm/Support/Compiler.h"
37
+
38
+ namespace llvm {
39
+
40
+ template <typename T, typename... TArgs> class AnalysisManager;
41
+ template <class T> class ArrayRef;
42
+ class AssumptionCache;
43
+ class CallBase;
44
+ class DataLayout;
45
+ class DominatorTree;
46
+ class Function;
47
+ class Instruction;
48
+ class CmpPredicate;
49
+ class LoadInst;
50
+ struct LoopStandardAnalysisResults;
51
+ class Pass;
52
+ template <class T, unsigned n> class SmallSetVector;
53
+ class TargetLibraryInfo;
54
+ class Type;
55
+ class Value;
56
+
57
+ // NOTE: the explicit multiple argument versions of these functions are
58
+ // deprecated.
59
+ // Please use the SimplifyQuery versions in new code.
60
+
61
+ /// Given operands for an Add, fold the result or return null.
62
+ LLVM_ABI Value *simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
63
+ const SimplifyQuery &Q);
64
+
65
+ /// Given operands for a Sub, fold the result or return null.
66
+ LLVM_ABI Value *simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
67
+ const SimplifyQuery &Q);
68
+
69
+ /// Given operands for a Mul, fold the result or return null.
70
+ LLVM_ABI Value *simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
71
+ const SimplifyQuery &Q);
72
+
73
+ /// Given operands for an SDiv, fold the result or return null.
74
+ LLVM_ABI Value *simplifySDivInst(Value *LHS, Value *RHS, bool IsExact,
75
+ const SimplifyQuery &Q);
76
+
77
+ /// Given operands for a UDiv, fold the result or return null.
78
+ LLVM_ABI Value *simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact,
79
+ const SimplifyQuery &Q);
80
+
81
+ /// Given operands for an SRem, fold the result or return null.
82
+ LLVM_ABI Value *simplifySRemInst(Value *LHS, Value *RHS,
83
+ const SimplifyQuery &Q);
84
+
85
+ /// Given operands for a URem, fold the result or return null.
86
+ LLVM_ABI Value *simplifyURemInst(Value *LHS, Value *RHS,
87
+ const SimplifyQuery &Q);
88
+
89
+ /// Given operand for an FNeg, fold the result or return null.
90
+ LLVM_ABI Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
91
+ const SimplifyQuery &Q);
92
+
93
+ /// Given operands for an FAdd, fold the result or return null.
94
+ LLVM_ABI Value *
95
+ simplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
96
+ const SimplifyQuery &Q,
97
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
98
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
99
+
100
+ /// Given operands for an FSub, fold the result or return null.
101
+ LLVM_ABI Value *
102
+ simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
103
+ const SimplifyQuery &Q,
104
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
105
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
106
+
107
+ /// Given operands for an FMul, fold the result or return null.
108
+ LLVM_ABI Value *
109
+ simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
110
+ const SimplifyQuery &Q,
111
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
112
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
113
+
114
+ /// Given operands for the multiplication of a FMA, fold the result or return
115
+ /// null. In contrast to simplifyFMulInst, this function will not perform
116
+ /// simplifications whose unrounded results differ when rounded to the argument
117
+ /// type.
118
+ LLVM_ABI Value *
119
+ simplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
120
+ const SimplifyQuery &Q,
121
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
122
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
123
+
124
+ /// Given operands for an FDiv, fold the result or return null.
125
+ LLVM_ABI Value *
126
+ simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
127
+ const SimplifyQuery &Q,
128
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
129
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
130
+
131
+ /// Given operands for an FRem, fold the result or return null.
132
+ LLVM_ABI Value *
133
+ simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
134
+ const SimplifyQuery &Q,
135
+ fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
136
+ RoundingMode Rounding = RoundingMode::NearestTiesToEven);
137
+
138
+ /// Given operands for a Shl, fold the result or return null.
139
+ LLVM_ABI Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
140
+ const SimplifyQuery &Q);
141
+
142
+ /// Given operands for a LShr, fold the result or return null.
143
+ LLVM_ABI Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
144
+ const SimplifyQuery &Q);
145
+
146
+ /// Given operands for a AShr, fold the result or return nulll.
147
+ LLVM_ABI Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
148
+ const SimplifyQuery &Q);
149
+
150
+ /// Given operands for an And, fold the result or return null.
151
+ LLVM_ABI Value *simplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
152
+
153
+ /// Given operands for an Or, fold the result or return null.
154
+ LLVM_ABI Value *simplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
155
+
156
+ /// Given operands for an Xor, fold the result or return null.
157
+ LLVM_ABI Value *simplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
158
+
159
+ /// Given operands for an ICmpInst, fold the result or return null.
160
+ LLVM_ABI Value *simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS,
161
+ const SimplifyQuery &Q);
162
+
163
+ /// Given operands for an FCmpInst, fold the result or return null.
164
+ LLVM_ABI Value *simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
165
+ FastMathFlags FMF, const SimplifyQuery &Q);
166
+
167
+ /// Given operands for a SelectInst, fold the result or return null.
168
+ LLVM_ABI Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
169
+ const SimplifyQuery &Q);
170
+
171
+ /// Given operands for a GetElementPtrInst, fold the result or return null.
172
+ LLVM_ABI Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
173
+ ArrayRef<Value *> Indices, GEPNoWrapFlags NW,
174
+ const SimplifyQuery &Q);
175
+
176
+ /// Given operands for an InsertValueInst, fold the result or return null.
177
+ LLVM_ABI Value *simplifyInsertValueInst(Value *Agg, Value *Val,
178
+ ArrayRef<unsigned> Idxs,
179
+ const SimplifyQuery &Q);
180
+
181
+ /// Given operands for an InsertElement, fold the result or return null.
182
+ LLVM_ABI Value *simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
183
+ const SimplifyQuery &Q);
184
+
185
+ /// Given operands for an ExtractValueInst, fold the result or return null.
186
+ LLVM_ABI Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
187
+ const SimplifyQuery &Q);
188
+
189
+ /// Given operands for an ExtractElementInst, fold the result or return null.
190
+ LLVM_ABI Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
191
+ const SimplifyQuery &Q);
192
+
193
+ /// Given operands for a CastInst, fold the result or return null.
194
+ LLVM_ABI Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
195
+ const SimplifyQuery &Q);
196
+
197
+ /// Given operands for a BinaryIntrinsic, fold the result or return null.
198
+ LLVM_ABI Value *simplifyBinaryIntrinsic(Intrinsic::ID IID, Type *ReturnType,
199
+ Value *Op0, Value *Op1,
200
+ const SimplifyQuery &Q,
201
+ const CallBase *Call);
202
+
203
+ /// Given operands for a ShuffleVectorInst, fold the result or return null.
204
+ /// See class ShuffleVectorInst for a description of the mask representation.
205
+ LLVM_ABI Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
206
+ ArrayRef<int> Mask, Type *RetTy,
207
+ const SimplifyQuery &Q);
208
+
209
+ //=== Helper functions for higher up the class hierarchy.
210
+
211
+ /// Given operands for a CmpInst, fold the result or return null.
212
+ LLVM_ABI Value *simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
213
+ const SimplifyQuery &Q);
214
+
215
+ /// Given operand for a UnaryOperator, fold the result or return null.
216
+ LLVM_ABI Value *simplifyUnOp(unsigned Opcode, Value *Op,
217
+ const SimplifyQuery &Q);
218
+
219
+ /// Given operand for a UnaryOperator, fold the result or return null.
220
+ /// Try to use FastMathFlags when folding the result.
221
+ LLVM_ABI Value *simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
222
+ const SimplifyQuery &Q);
223
+
224
+ /// Given operands for a BinaryOperator, fold the result or return null.
225
+ LLVM_ABI Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
226
+ const SimplifyQuery &Q);
227
+
228
+ /// Given operands for a BinaryOperator, fold the result or return null.
229
+ /// Try to use FastMathFlags when folding the result.
230
+ LLVM_ABI Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
231
+ FastMathFlags FMF, const SimplifyQuery &Q);
232
+
233
+ /// Given a callsite, callee, and arguments, fold the result or return null.
234
+ LLVM_ABI Value *simplifyCall(CallBase *Call, Value *Callee,
235
+ ArrayRef<Value *> Args, const SimplifyQuery &Q);
236
+
237
+ /// Given a constrained FP intrinsic call, tries to compute its simplified
238
+ /// version. Returns a simplified result or null.
239
+ ///
240
+ /// This function provides an additional contract: it guarantees that if
241
+ /// simplification succeeds that the intrinsic is side effect free. As a result,
242
+ /// successful simplification can be used to delete the intrinsic not just
243
+ /// replace its result.
244
+ LLVM_ABI Value *simplifyConstrainedFPCall(CallBase *Call,
245
+ const SimplifyQuery &Q);
246
+
247
+ /// Given an operand for a Freeze, see if we can fold the result.
248
+ /// If not, this returns null.
249
+ LLVM_ABI Value *simplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
250
+
251
+ /// Given a load instruction and its pointer operand, fold the result or return
252
+ /// null.
253
+ LLVM_ABI Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
254
+ const SimplifyQuery &Q);
255
+
256
+ /// See if we can compute a simplified version of this instruction. If not,
257
+ /// return null.
258
+ LLVM_ABI Value *simplifyInstruction(Instruction *I, const SimplifyQuery &Q);
259
+
260
+ /// Like \p simplifyInstruction but the operands of \p I are replaced with
261
+ /// \p NewOps. Returns a simplified value, or null if none was found.
262
+ LLVM_ABI Value *simplifyInstructionWithOperands(Instruction *I,
263
+ ArrayRef<Value *> NewOps,
264
+ const SimplifyQuery &Q);
265
+
266
+ /// See if V simplifies when its operand Op is replaced with RepOp. If not,
267
+ /// return null.
268
+ /// AllowRefinement specifies whether the simplification can be a refinement
269
+ /// (e.g. 0 instead of poison), or whether it needs to be strictly identical.
270
+ /// Op and RepOp can be assumed to not be poison when determining refinement.
271
+ ///
272
+ /// If DropFlags is passed, then the replacement result is only valid if
273
+ /// poison-generating flags/metadata on those instructions are dropped. This
274
+ /// is only useful in conjunction with AllowRefinement=false.
275
+ LLVM_ABI Value *
276
+ simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
277
+ const SimplifyQuery &Q, bool AllowRefinement,
278
+ SmallVectorImpl<Instruction *> *DropFlags = nullptr);
279
+
280
+ /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
281
+ ///
282
+ /// This first performs a normal RAUW of I with SimpleV. It then recursively
283
+ /// attempts to simplify those users updated by the operation. The 'I'
284
+ /// instruction must not be equal to the simplified value 'SimpleV'.
285
+ /// If UnsimplifiedUsers is provided, instructions that could not be simplified
286
+ /// are added to it.
287
+ ///
288
+ /// The function returns true if any simplifications were performed.
289
+ LLVM_ABI bool replaceAndRecursivelySimplify(
290
+ Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
291
+ const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
292
+ SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
293
+
294
+ // These helper functions return a SimplifyQuery structure that contains as
295
+ // many of the optional analysis we use as are currently valid. This is the
296
+ // strongly preferred way of constructing SimplifyQuery in passes.
297
+ LLVM_ABI const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
298
+ template <class T, class... TArgs>
299
+ const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
300
+ Function &);
301
+ LLVM_ABI const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
302
+ const DataLayout &);
303
+ } // end namespace llvm
304
+
305
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/InteractiveModelRunner.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- InteractiveModelRunner.h ---- "gym" ML model runner -----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+
10
+ #ifndef LLVM_ANALYSIS_INTERACTIVEMODELRUNNER_H
11
+ #define LLVM_ANALYSIS_INTERACTIVEMODELRUNNER_H
12
+
13
+ #include "llvm/Analysis/MLModelRunner.h"
14
+ #include "llvm/Analysis/TensorSpec.h"
15
+ #include "llvm/Analysis/Utils/TrainingLogger.h"
16
+ #include "llvm/Support/Compiler.h"
17
+ #include <system_error>
18
+
19
+ namespace llvm {
20
+
21
+ /// A MLModelRunner that asks for advice from an external agent, or host. It
22
+ /// uses 2 files - ideally named pipes - one to send data to that agent, and
23
+ /// one to receive advice.
24
+ /// The data exchange uses the training logger (Utils/TrainingLogger.h) format.
25
+ /// Specifically, the compiler will send the log header, set the context, and
26
+ /// send observations; the host is expected to reply with a tensor value after
27
+ /// each observation as a binary buffer that's conforming to the shape of the
28
+ /// advice. Interleaved, the data closely resembles the training log for a
29
+ /// log where we don't capture the reward signal.
30
+ ///
31
+ /// Note that the correctness of the received data is the responsibility of the
32
+ /// host. In particular, if insufficient data were sent, the compiler will block
33
+ /// when waiting for an advice.
34
+ ///
35
+ /// Note that the host can either open the pipes RW, or open first the pipe to
36
+ /// the compiler - i.e. the "Inbound" - and then the "Outbound", to avoid
37
+ /// deadlock. This is because the compiler first tries to open the inbound
38
+ /// (which will hang until there's a writer on the other end).
39
+ class LLVM_ABI InteractiveModelRunner : public MLModelRunner {
40
+ public:
41
+ InteractiveModelRunner(LLVMContext &Ctx,
42
+ const std::vector<TensorSpec> &Inputs,
43
+ const TensorSpec &Advice, StringRef OutboundName,
44
+ StringRef InboundName);
45
+
46
+ static bool classof(const MLModelRunner *R) {
47
+ return R->getKind() == MLModelRunner::Kind::Interactive;
48
+ }
49
+ void switchContext(StringRef Name) override {
50
+ Log->switchContext(Name);
51
+ Log->flush();
52
+ }
53
+
54
+ virtual ~InteractiveModelRunner();
55
+
56
+ private:
57
+ void *evaluateUntyped() override;
58
+ // This must be declared before InEC if we want to initialize it in the
59
+ // ctor initializer list.
60
+ int Inbound = -1;
61
+ const std::vector<TensorSpec> InputSpecs;
62
+ const TensorSpec OutputSpec;
63
+ std::error_code OutEC;
64
+ std::error_code InEC;
65
+ std::vector<char> OutputBuffer;
66
+ std::unique_ptr<Logger> Log;
67
+ };
68
+ } // namespace llvm
69
+ #endif // LLVM_ANALYSIS_INTERACTIVEMODELRUNNER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/KernelInfo.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //=- KernelInfo.h - Kernel Analysis -------------------------------*- C++ -*-=//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the KernelInfoPrinter class used to emit remarks about
10
+ // function properties from a GPU kernel.
11
+ //
12
+ // See llvm/docs/KernelInfo.rst.
13
+ // ===---------------------------------------------------------------------===//
14
+
15
+ #ifndef LLVM_ANALYSIS_KERNELINFO_H
16
+ #define LLVM_ANALYSIS_KERNELINFO_H
17
+
18
+ #include "llvm/IR/PassManager.h"
19
+
20
+ namespace llvm {
21
+
22
+ class TargetMachine;
23
+
24
+ class KernelInfoPrinter : public PassInfoMixin<KernelInfoPrinter> {
25
+ TargetMachine *TM;
26
+
27
+ public:
28
+ explicit KernelInfoPrinter(TargetMachine *TM) : TM(TM) {}
29
+
30
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
31
+
32
+ static bool isRequired() { return true; }
33
+ };
34
+ } // namespace llvm
35
+ #endif // LLVM_ANALYSIS_KERNELINFO_H
deps/exla/cache/xla_extension/include/llvm/Analysis/LastRunTrackingAnalysis.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- LastRunTrackingAnalysis.h - Avoid running redundant pass -*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This is an analysis pass to track a set of passes that have been run, so that
10
+ // we can avoid running a pass again if there is no change since the last run of
11
+ // the pass.
12
+ //
13
+ // In this analysis we track a set of passes S for each function with the
14
+ // following transition rules:
15
+ // 1. If pass P makes changes, set S = {P}.
16
+ // 2. If pass P doesn't make changes, set S = S + {P}.
17
+ //
18
+ // Before running a pass P which satisfies P(P(x)) == P(x), we check if P is in
19
+ // S. If so, we skip this pass since we know that there will be no change.
20
+ //
21
+ // Notes:
22
+ // 1. Some transform passes have parameters that may vary in the optimization
23
+ // pipeline. We should check if parameters in current run is compatible with
24
+ // that in the last run.
25
+ // 2. This pass only tracks at the module/function level. Loop passes are not
26
+ // supported for now.
27
+ //
28
+ //===----------------------------------------------------------------------===//
29
+
30
+ #ifndef LLVM_ANALYSIS_LASTRUNTRACKINGANALYSIS_H
31
+ #define LLVM_ANALYSIS_LASTRUNTRACKINGANALYSIS_H
32
+
33
+ #include "llvm/ADT/DenseMap.h"
34
+ #include "llvm/IR/PassManager.h"
35
+ #include "llvm/Support/Compiler.h"
36
+ #include <functional>
37
+
38
+ namespace llvm {
39
+
40
+ /// This class is used to track the last run of a set of module/function passes.
41
+ /// Invalidation are conservatively handled by the pass manager if a pass
42
+ /// doesn't explicitly preserve the result.
43
+ /// If we want to skip a pass, we should define a unique ID \p PassID to
44
+ /// identify the pass, which is usually a pointer to a static member. If a pass
45
+ /// has parameters, they should be stored in a struct \p OptionT with a method
46
+ /// bool isCompatibleWith(const OptionT& LastOpt) const to check compatibility.
47
+ class LastRunTrackingInfo {
48
+ public:
49
+ using PassID = const void *;
50
+ using OptionPtr = const void *;
51
+ // CompatibilityCheckFn is a closure that stores the parameters of last run.
52
+ using CompatibilityCheckFn = std::function<bool(OptionPtr)>;
53
+
54
+ /// Check if we should skip a pass.
55
+ /// \param ID The unique ID of the pass.
56
+ /// \param Opt The parameters of the pass. If the pass has no parameters, use
57
+ /// shouldSkip(PassID ID) instead.
58
+ /// \return True if we should skip the pass.
59
+ /// \sa shouldSkip(PassID ID)
60
+ template <typename OptionT>
61
+ bool shouldSkip(PassID ID, const OptionT &Opt) const {
62
+ return shouldSkipImpl(ID, &Opt);
63
+ }
64
+ bool shouldSkip(PassID ID) const { return shouldSkipImpl(ID, nullptr); }
65
+
66
+ /// Update the tracking info.
67
+ /// \param ID The unique ID of the pass.
68
+ /// \param Changed Whether the pass makes changes.
69
+ /// \param Opt The parameters of the pass. It must have the same type as the
70
+ /// parameters of the last run. If the pass has no parameters, use
71
+ /// update(PassID ID, bool Changed) instead.
72
+ /// \sa update(PassID ID, bool Changed)
73
+ template <typename OptionT>
74
+ void update(PassID ID, bool Changed, const OptionT &Opt) {
75
+ updateImpl(ID, Changed, [Opt](OptionPtr Ptr) {
76
+ return static_cast<const OptionT *>(Ptr)->isCompatibleWith(Opt);
77
+ });
78
+ }
79
+ void update(PassID ID, bool Changed) {
80
+ updateImpl(ID, Changed, CompatibilityCheckFn{});
81
+ }
82
+
83
+ private:
84
+ LLVM_ABI bool shouldSkipImpl(PassID ID, OptionPtr Ptr) const;
85
+ LLVM_ABI void updateImpl(PassID ID, bool Changed,
86
+ CompatibilityCheckFn CheckFn);
87
+
88
+ DenseMap<PassID, CompatibilityCheckFn> TrackedPasses;
89
+ };
90
+
91
+ /// A function/module analysis which provides an empty \c LastRunTrackingInfo.
92
+ class LastRunTrackingAnalysis final
93
+ : public AnalysisInfoMixin<LastRunTrackingAnalysis> {
94
+ friend AnalysisInfoMixin<LastRunTrackingAnalysis>;
95
+ LLVM_ABI static AnalysisKey Key;
96
+
97
+ public:
98
+ using Result = LastRunTrackingInfo;
99
+ LastRunTrackingInfo run(Function &F, FunctionAnalysisManager &) {
100
+ return LastRunTrackingInfo();
101
+ }
102
+ LastRunTrackingInfo run(Module &M, ModuleAnalysisManager &) {
103
+ return LastRunTrackingInfo();
104
+ }
105
+ };
106
+
107
+ } // namespace llvm
108
+
109
+ #endif // LLVM_ANALYSIS_LASTRUNTRACKINGANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/LazyBlockFrequencyInfo.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- LazyBlockFrequencyInfo.h - Lazy Block Frequency Analysis -*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This is an alternative analysis pass to BlockFrequencyInfoWrapperPass. The
10
+ // difference is that with this pass the block frequencies are not computed when
11
+ // the analysis pass is executed but rather when the BFI result is explicitly
12
+ // requested by the analysis client.
13
+ //
14
+ //===----------------------------------------------------------------------===//
15
+
16
+ #ifndef LLVM_ANALYSIS_LAZYBLOCKFREQUENCYINFO_H
17
+ #define LLVM_ANALYSIS_LAZYBLOCKFREQUENCYINFO_H
18
+
19
+ #include "llvm/Analysis/BlockFrequencyInfo.h"
20
+ #include "llvm/Analysis/LazyBranchProbabilityInfo.h"
21
+ #include "llvm/Pass.h"
22
+
23
+ namespace llvm {
24
+ class Function;
25
+ class LoopInfo;
26
+
27
+ /// Wraps a BFI to allow lazy computation of the block frequencies.
28
+ ///
29
+ /// A pass that only conditionally uses BFI can uncondtionally require the
30
+ /// analysis without paying for the overhead if BFI doesn't end up being used.
31
+ template <typename FunctionT, typename BranchProbabilityInfoPassT,
32
+ typename LoopInfoT, typename BlockFrequencyInfoT>
33
+ class LazyBlockFrequencyInfo {
34
+ public:
35
+ LazyBlockFrequencyInfo() = default;
36
+
37
+ /// Set up the per-function input.
38
+ void setAnalysis(const FunctionT *F, BranchProbabilityInfoPassT *BPIPass,
39
+ const LoopInfoT *LI) {
40
+ this->F = F;
41
+ this->BPIPass = BPIPass;
42
+ this->LI = LI;
43
+ }
44
+
45
+ /// Retrieve the BFI with the block frequencies computed.
46
+ BlockFrequencyInfoT &getCalculated() {
47
+ if (!Calculated) {
48
+ assert(F && BPIPass && LI && "call setAnalysis");
49
+ BFI.calculate(
50
+ *F, BPIPassTrait<BranchProbabilityInfoPassT>::getBPI(BPIPass), *LI);
51
+ Calculated = true;
52
+ }
53
+ return BFI;
54
+ }
55
+
56
+ const BlockFrequencyInfoT &getCalculated() const {
57
+ return const_cast<LazyBlockFrequencyInfo *>(this)->getCalculated();
58
+ }
59
+
60
+ void releaseMemory() {
61
+ BFI.releaseMemory();
62
+ Calculated = false;
63
+ setAnalysis(nullptr, nullptr, nullptr);
64
+ }
65
+
66
+ private:
67
+ BlockFrequencyInfoT BFI;
68
+ bool Calculated = false;
69
+ const FunctionT *F = nullptr;
70
+ BranchProbabilityInfoPassT *BPIPass = nullptr;
71
+ const LoopInfoT *LI = nullptr;
72
+ };
73
+
74
+ /// This is an alternative analysis pass to
75
+ /// BlockFrequencyInfoWrapperPass. The difference is that with this pass the
76
+ /// block frequencies are not computed when the analysis pass is executed but
77
+ /// rather when the BFI result is explicitly requested by the analysis client.
78
+ ///
79
+ /// There are some additional requirements for any client pass that wants to use
80
+ /// the analysis:
81
+ ///
82
+ /// 1. The pass needs to initialize dependent passes with:
83
+ ///
84
+ /// INITIALIZE_PASS_DEPENDENCY(LazyBFIPass)
85
+ ///
86
+ /// 2. Similarly, getAnalysisUsage should call:
87
+ ///
88
+ /// LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU)
89
+ ///
90
+ /// 3. The computed BFI should be requested with
91
+ /// getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() before either LoopInfo
92
+ /// or BPI could be invalidated for example by changing the CFG.
93
+ ///
94
+ /// Note that it is expected that we wouldn't need this functionality for the
95
+ /// new PM since with the new PM, analyses are executed on demand.
96
+
97
+ class LazyBlockFrequencyInfoPass : public FunctionPass {
98
+ private:
99
+ LazyBlockFrequencyInfo<Function, LazyBranchProbabilityInfoPass, LoopInfo,
100
+ BlockFrequencyInfo>
101
+ LBFI;
102
+
103
+ public:
104
+ static char ID;
105
+
106
+ LazyBlockFrequencyInfoPass();
107
+
108
+ /// Compute and return the block frequencies.
109
+ BlockFrequencyInfo &getBFI() { return LBFI.getCalculated(); }
110
+
111
+ /// Compute and return the block frequencies.
112
+ const BlockFrequencyInfo &getBFI() const { return LBFI.getCalculated(); }
113
+
114
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
115
+
116
+ /// Helper for client passes to set up the analysis usage on behalf of this
117
+ /// pass.
118
+ static void getLazyBFIAnalysisUsage(AnalysisUsage &AU);
119
+
120
+ bool runOnFunction(Function &F) override;
121
+ void releaseMemory() override;
122
+ void print(raw_ostream &OS, const Module *M) const override;
123
+ };
124
+
125
+ } // namespace llvm
126
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/LazyValueInfo.h ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- LazyValueInfo.h - Value constraint analysis --------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the interface for lazy computation of value constraint
10
+ // information.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_LAZYVALUEINFO_H
15
+ #define LLVM_ANALYSIS_LAZYVALUEINFO_H
16
+
17
+ #include "llvm/IR/InstrTypes.h"
18
+ #include "llvm/IR/PassManager.h"
19
+ #include "llvm/Pass.h"
20
+
21
+ namespace llvm {
22
+ class AssumptionCache;
23
+ class BasicBlock;
24
+ class Constant;
25
+ class DataLayout;
26
+ class DominatorTree;
27
+ class Instruction;
28
+ class Value;
29
+ class Use;
30
+ class LazyValueInfoImpl;
31
+ /// This pass computes, caches, and vends lazy value constraint information.
32
+ class LazyValueInfo {
33
+ friend class LazyValueInfoWrapperPass;
34
+ AssumptionCache *AC = nullptr;
35
+ const DataLayout *DL = nullptr;
36
+ LazyValueInfoImpl *PImpl = nullptr;
37
+ LazyValueInfo(const LazyValueInfo &) = delete;
38
+ void operator=(const LazyValueInfo &) = delete;
39
+
40
+ LazyValueInfoImpl *getImpl();
41
+ LazyValueInfoImpl &getOrCreateImpl(const Module *M);
42
+
43
+ public:
44
+ ~LazyValueInfo();
45
+ LazyValueInfo() = default;
46
+ LazyValueInfo(AssumptionCache *AC_, const DataLayout *DL_)
47
+ : AC(AC_), DL(DL_) {}
48
+ LazyValueInfo(LazyValueInfo &&Arg)
49
+ : AC(Arg.AC), DL(Arg.DL), PImpl(Arg.PImpl) {
50
+ Arg.PImpl = nullptr;
51
+ }
52
+ LazyValueInfo &operator=(LazyValueInfo &&Arg) {
53
+ releaseMemory();
54
+ AC = Arg.AC;
55
+ DL = Arg.DL;
56
+ PImpl = Arg.PImpl;
57
+ Arg.PImpl = nullptr;
58
+ return *this;
59
+ }
60
+
61
+ // Public query interface.
62
+
63
+ /// Determine whether the specified value comparison with a constant is
64
+ /// known to be true or false on the specified CFG edge. Pred is a CmpInst
65
+ /// predicate.
66
+ Constant *getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C,
67
+ BasicBlock *FromBB, BasicBlock *ToBB,
68
+ Instruction *CxtI = nullptr);
69
+
70
+ /// Determine whether the specified value comparison with a constant is
71
+ /// known to be true or false at the specified instruction. \p Pred is a
72
+ /// CmpInst predicate. If \p UseBlockValue is true, the block value is also
73
+ /// taken into account.
74
+ Constant *getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C,
75
+ Instruction *CxtI, bool UseBlockValue);
76
+
77
+ /// Determine whether the specified value comparison is known to be true
78
+ /// or false at the specified instruction. While this takes two Value's,
79
+ /// it still requires that one of them is a constant.
80
+ /// \p Pred is a CmpInst predicate.
81
+ /// If \p UseBlockValue is true, the block value is also taken into account.
82
+ Constant *getPredicateAt(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
83
+ Instruction *CxtI, bool UseBlockValue);
84
+
85
+ /// Determine whether the specified value is known to be a constant at the
86
+ /// specified instruction. Return null if not.
87
+ Constant *getConstant(Value *V, Instruction *CxtI);
88
+
89
+ /// Return the ConstantRange constraint that is known to hold for the
90
+ /// specified value at the specified instruction. This may only be called
91
+ /// on integer-typed Values.
92
+ ConstantRange getConstantRange(Value *V, Instruction *CxtI,
93
+ bool UndefAllowed);
94
+
95
+ /// Return the ConstantRange constraint that is known to hold for the value
96
+ /// at a specific use-site.
97
+ ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed);
98
+
99
+ /// Determine whether the specified value is known to be a
100
+ /// constant on the specified edge. Return null if not.
101
+ Constant *getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
102
+ Instruction *CxtI = nullptr);
103
+
104
+ /// Return the ConstantRage constraint that is known to hold for the
105
+ /// specified value on the specified edge. This may be only be called
106
+ /// on integer-typed Values.
107
+ ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB,
108
+ BasicBlock *ToBB,
109
+ Instruction *CxtI = nullptr);
110
+
111
+ /// Inform the analysis cache that we have threaded an edge from
112
+ /// PredBB to OldSucc to be from PredBB to NewSucc instead.
113
+ void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
114
+ BasicBlock *NewSucc);
115
+
116
+ /// Remove information related to this value from the cache.
117
+ void forgetValue(Value *V);
118
+
119
+ /// Inform the analysis cache that we have erased a block.
120
+ void eraseBlock(BasicBlock *BB);
121
+
122
+ /// Complete flush all previously computed values
123
+ void clear();
124
+
125
+ /// Print the \LazyValueInfo Analysis.
126
+ /// We pass in the DTree that is required for identifying which basic blocks
127
+ /// we can solve/print for, in the LVIPrinter.
128
+ void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS);
129
+
130
+ // For old PM pass. Delete once LazyValueInfoWrapperPass is gone.
131
+ void releaseMemory();
132
+
133
+ /// Handle invalidation events in the new pass manager.
134
+ bool invalidate(Function &F, const PreservedAnalyses &PA,
135
+ FunctionAnalysisManager::Invalidator &Inv);
136
+ };
137
+
138
+ /// Analysis to compute lazy value information.
139
+ class LazyValueAnalysis : public AnalysisInfoMixin<LazyValueAnalysis> {
140
+ public:
141
+ typedef LazyValueInfo Result;
142
+ Result run(Function &F, FunctionAnalysisManager &FAM);
143
+
144
+ private:
145
+ static AnalysisKey Key;
146
+ friend struct AnalysisInfoMixin<LazyValueAnalysis>;
147
+ };
148
+
149
+ /// Printer pass for the LazyValueAnalysis results.
150
+ class LazyValueInfoPrinterPass
151
+ : public PassInfoMixin<LazyValueInfoPrinterPass> {
152
+ raw_ostream &OS;
153
+
154
+ public:
155
+ explicit LazyValueInfoPrinterPass(raw_ostream &OS) : OS(OS) {}
156
+
157
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
158
+
159
+ static bool isRequired() { return true; }
160
+ };
161
+
162
+ /// Wrapper around LazyValueInfo.
163
+ class LazyValueInfoWrapperPass : public FunctionPass {
164
+ LazyValueInfoWrapperPass(const LazyValueInfoWrapperPass&) = delete;
165
+ void operator=(const LazyValueInfoWrapperPass&) = delete;
166
+ public:
167
+ static char ID;
168
+ LazyValueInfoWrapperPass();
169
+ ~LazyValueInfoWrapperPass() override {
170
+ assert(!Info.PImpl && "releaseMemory not called");
171
+ }
172
+
173
+ LazyValueInfo &getLVI();
174
+
175
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
176
+ void releaseMemory() override;
177
+ bool runOnFunction(Function &F) override;
178
+ private:
179
+ LazyValueInfo Info;
180
+ };
181
+
182
+ } // end namespace llvm
183
+
184
+ #endif
185
+
deps/exla/cache/xla_extension/include/llvm/Analysis/LoopAccessAnalysis.h ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/LoopAccessAnalysis.h -----------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the interface for the loop memory dependence framework that
10
+ // was originally developed for the Loop Vectorizer.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
15
+ #define LLVM_ANALYSIS_LOOPACCESSANALYSIS_H
16
+
17
+ #include "llvm/ADT/EquivalenceClasses.h"
18
+ #include "llvm/Analysis/ScalarEvolution.h"
19
+ #include "llvm/IR/DiagnosticInfo.h"
20
+ #include "llvm/Support/Compiler.h"
21
+ #include <optional>
22
+ #include <variant>
23
+
24
+ namespace llvm {
25
+
26
+ class AAResults;
27
+ class DataLayout;
28
+ class Loop;
29
+ class raw_ostream;
30
+ class TargetTransformInfo;
31
+
32
+ /// Collection of parameters shared beetween the Loop Vectorizer and the
33
+ /// Loop Access Analysis.
34
+ struct VectorizerParams {
35
+ /// Maximum SIMD width.
36
+ LLVM_ABI static const unsigned MaxVectorWidth;
37
+
38
+ /// VF as overridden by the user.
39
+ LLVM_ABI static unsigned VectorizationFactor;
40
+ /// Interleave factor as overridden by the user.
41
+ LLVM_ABI static unsigned VectorizationInterleave;
42
+ /// True if force-vector-interleave was specified by the user.
43
+ LLVM_ABI static bool isInterleaveForced();
44
+
45
+ /// \When performing memory disambiguation checks at runtime do not
46
+ /// make more than this number of comparisons.
47
+ LLVM_ABI static unsigned RuntimeMemoryCheckThreshold;
48
+
49
+ // When creating runtime checks for nested loops, where possible try to
50
+ // write the checks in a form that allows them to be easily hoisted out of
51
+ // the outermost loop. For example, we can do this by expanding the range of
52
+ // addresses considered to include the entire nested loop so that they are
53
+ // loop invariant.
54
+ LLVM_ABI static bool HoistRuntimeChecks;
55
+ };
56
+
57
+ /// Checks memory dependences among accesses to the same underlying
58
+ /// object to determine whether there vectorization is legal or not (and at
59
+ /// which vectorization factor).
60
+ ///
61
+ /// Note: This class will compute a conservative dependence for access to
62
+ /// different underlying pointers. Clients, such as the loop vectorizer, will
63
+ /// sometimes deal these potential dependencies by emitting runtime checks.
64
+ ///
65
+ /// We use the ScalarEvolution framework to symbolically evalutate access
66
+ /// functions pairs. Since we currently don't restructure the loop we can rely
67
+ /// on the program order of memory accesses to determine their safety.
68
+ /// At the moment we will only deem accesses as safe for:
69
+ /// * A negative constant distance assuming program order.
70
+ ///
71
+ /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
72
+ /// a[i] = tmp; y = a[i];
73
+ ///
74
+ /// The latter case is safe because later checks guarantuee that there can't
75
+ /// be a cycle through a phi node (that is, we check that "x" and "y" is not
76
+ /// the same variable: a header phi can only be an induction or a reduction, a
77
+ /// reduction can't have a memory sink, an induction can't have a memory
78
+ /// source). This is important and must not be violated (or we have to
79
+ /// resort to checking for cycles through memory).
80
+ ///
81
+ /// * A positive constant distance assuming program order that is bigger
82
+ /// than the biggest memory access.
83
+ ///
84
+ /// tmp = a[i] OR b[i] = x
85
+ /// a[i+2] = tmp y = b[i+2];
86
+ ///
87
+ /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
88
+ ///
89
+ /// * Zero distances and all accesses have the same size.
90
+ ///
91
+ class MemoryDepChecker {
92
+ public:
93
+ typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
94
+ typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList;
95
+ /// Set of potential dependent memory accesses.
96
+ typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
97
+
98
+ /// Type to keep track of the status of the dependence check. The order of
99
+ /// the elements is important and has to be from most permissive to least
100
+ /// permissive.
101
+ enum class VectorizationSafetyStatus {
102
+ // Can vectorize safely without RT checks. All dependences are known to be
103
+ // safe.
104
+ Safe,
105
+ // Can possibly vectorize with RT checks to overcome unknown dependencies.
106
+ PossiblySafeWithRtChecks,
107
+ // Cannot vectorize due to known unsafe dependencies.
108
+ Unsafe,
109
+ };
110
+
111
+ /// Dependece between memory access instructions.
112
+ struct Dependence {
113
+ /// The type of the dependence.
114
+ enum DepType {
115
+ // No dependence.
116
+ NoDep,
117
+ // We couldn't determine the direction or the distance.
118
+ Unknown,
119
+ // At least one of the memory access instructions may access a loop
120
+ // varying object, e.g. the address of underlying object is loaded inside
121
+ // the loop, like A[B[i]]. We cannot determine direction or distance in
122
+ // those cases, and also are unable to generate any runtime checks.
123
+ IndirectUnsafe,
124
+
125
+ // Lexically forward.
126
+ //
127
+ // FIXME: If we only have loop-independent forward dependences (e.g. a
128
+ // read and write of A[i]), LAA will locally deem the dependence "safe"
129
+ // without querying the MemoryDepChecker. Therefore we can miss
130
+ // enumerating loop-independent forward dependences in
131
+ // getDependences. Note that as soon as there are different
132
+ // indices used to access the same array, the MemoryDepChecker *is*
133
+ // queried and the dependence list is complete.
134
+ Forward,
135
+ // Forward, but if vectorized, is likely to prevent store-to-load
136
+ // forwarding.
137
+ ForwardButPreventsForwarding,
138
+ // Lexically backward.
139
+ Backward,
140
+ // Backward, but the distance allows a vectorization factor of dependent
141
+ // on MinDepDistBytes.
142
+ BackwardVectorizable,
143
+ // Same, but may prevent store-to-load forwarding.
144
+ BackwardVectorizableButPreventsForwarding
145
+ };
146
+
147
+ /// String version of the types.
148
+ LLVM_ABI static const char *DepName[];
149
+
150
+ /// Index of the source of the dependence in the InstMap vector.
151
+ unsigned Source;
152
+ /// Index of the destination of the dependence in the InstMap vector.
153
+ unsigned Destination;
154
+ /// The type of the dependence.
155
+ DepType Type;
156
+
157
+ Dependence(unsigned Source, unsigned Destination, DepType Type)
158
+ : Source(Source), Destination(Destination), Type(Type) {}
159
+
160
+ /// Return the source instruction of the dependence.
161
+ Instruction *getSource(const MemoryDepChecker &DepChecker) const;
162
+ /// Return the destination instruction of the dependence.
163
+ Instruction *getDestination(const MemoryDepChecker &DepChecker) const;
164
+
165
+ /// Dependence types that don't prevent vectorization.
166
+ LLVM_ABI static VectorizationSafetyStatus
167
+ isSafeForVectorization(DepType Type);
168
+
169
+ /// Lexically forward dependence.
170
+ LLVM_ABI bool isForward() const;
171
+ /// Lexically backward dependence.
172
+ LLVM_ABI bool isBackward() const;
173
+
174
+ /// May be a lexically backward dependence type (includes Unknown).
175
+ LLVM_ABI bool isPossiblyBackward() const;
176
+
177
+ /// Print the dependence. \p Instr is used to map the instruction
178
+ /// indices to instructions.
179
+ LLVM_ABI void print(raw_ostream &OS, unsigned Depth,
180
+ const SmallVectorImpl<Instruction *> &Instrs) const;
181
+ };
182
+
183
+ MemoryDepChecker(PredicatedScalarEvolution &PSE, const Loop *L,
184
+ const DenseMap<Value *, const SCEV *> &SymbolicStrides,
185
+ unsigned MaxTargetVectorWidthInBits)
186
+ : PSE(PSE), InnermostLoop(L), SymbolicStrides(SymbolicStrides),
187
+ MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits) {}
188
+
189
+ /// Register the location (instructions are given increasing numbers)
190
+ /// of a write access.
191
+ LLVM_ABI void addAccess(StoreInst *SI);
192
+
193
+ /// Register the location (instructions are given increasing numbers)
194
+ /// of a write access.
195
+ LLVM_ABI void addAccess(LoadInst *LI);
196
+
197
+ /// Check whether the dependencies between the accesses are safe, and records
198
+ /// the dependence information in Dependences if so.
199
+ ///
200
+ /// Only checks sets with elements in \p CheckDeps.
201
+ LLVM_ABI bool areDepsSafe(const DepCandidates &AccessSets,
202
+ const MemAccessInfoList &CheckDeps);
203
+
204
+ /// No memory dependence was encountered that would inhibit
205
+ /// vectorization.
206
+ bool isSafeForVectorization() const {
207
+ return Status == VectorizationSafetyStatus::Safe;
208
+ }
209
+
210
+ /// Return true if the number of elements that are safe to operate on
211
+ /// simultaneously is not bounded.
212
+ bool isSafeForAnyVectorWidth() const {
213
+ return MaxSafeVectorWidthInBits == UINT_MAX;
214
+ }
215
+
216
+ /// Return the number of elements that are safe to operate on
217
+ /// simultaneously, multiplied by the size of the element in bits.
218
+ uint64_t getMaxSafeVectorWidthInBits() const {
219
+ return MaxSafeVectorWidthInBits;
220
+ }
221
+
222
+ /// Return true if there are no store-load forwarding dependencies.
223
+ bool isSafeForAnyStoreLoadForwardDistances() const {
224
+ return MaxStoreLoadForwardSafeDistanceInBits ==
225
+ std::numeric_limits<uint64_t>::max();
226
+ }
227
+
228
+ /// Return safe power-of-2 number of elements, which do not prevent store-load
229
+ /// forwarding, multiplied by the size of the elements in bits.
230
+ uint64_t getStoreLoadForwardSafeDistanceInBits() const {
231
+ assert(!isSafeForAnyStoreLoadForwardDistances() &&
232
+ "Expected the distance, that prevent store-load forwarding, to be "
233
+ "set.");
234
+ return MaxStoreLoadForwardSafeDistanceInBits;
235
+ }
236
+
237
+ /// In same cases when the dependency check fails we can still
238
+ /// vectorize the loop with a dynamic array access check.
239
+ bool shouldRetryWithRuntimeCheck() const {
240
+ return FoundNonConstantDistanceDependence &&
241
+ Status == VectorizationSafetyStatus::PossiblySafeWithRtChecks;
242
+ }
243
+
244
+ /// Returns the memory dependences. If null is returned we exceeded
245
+ /// the MaxDependences threshold and this information is not
246
+ /// available.
247
+ const SmallVectorImpl<Dependence> *getDependences() const {
248
+ return RecordDependences ? &Dependences : nullptr;
249
+ }
250
+
251
+ void clearDependences() { Dependences.clear(); }
252
+
253
+ /// The vector of memory access instructions. The indices are used as
254
+ /// instruction identifiers in the Dependence class.
255
+ const SmallVectorImpl<Instruction *> &getMemoryInstructions() const {
256
+ return InstMap;
257
+ }
258
+
259
+ /// Generate a mapping between the memory instructions and their
260
+ /// indices according to program order.
261
+ DenseMap<Instruction *, unsigned> generateInstructionOrderMap() const {
262
+ DenseMap<Instruction *, unsigned> OrderMap;
263
+
264
+ for (unsigned I = 0; I < InstMap.size(); ++I)
265
+ OrderMap[InstMap[I]] = I;
266
+
267
+ return OrderMap;
268
+ }
269
+
270
+ /// Find the set of instructions that read or write via \p Ptr.
271
+ LLVM_ABI SmallVector<Instruction *, 4>
272
+ getInstructionsForAccess(Value *Ptr, bool isWrite) const;
273
+
274
+ /// Return the program order indices for the access location (Ptr, IsWrite).
275
+ /// Returns an empty ArrayRef if there are no accesses for the location.
276
+ ArrayRef<unsigned> getOrderForAccess(Value *Ptr, bool IsWrite) const {
277
+ auto I = Accesses.find({Ptr, IsWrite});
278
+ if (I != Accesses.end())
279
+ return I->second;
280
+ return {};
281
+ }
282
+
283
+ const Loop *getInnermostLoop() const { return InnermostLoop; }
284
+
285
+ DenseMap<std::pair<const SCEV *, Type *>,
286
+ std::pair<const SCEV *, const SCEV *>> &
287
+ getPointerBounds() {
288
+ return PointerBounds;
289
+ }
290
+
291
+ private:
292
+ /// A wrapper around ScalarEvolution, used to add runtime SCEV checks, and
293
+ /// applies dynamic knowledge to simplify SCEV expressions and convert them
294
+ /// to a more usable form. We need this in case assumptions about SCEV
295
+ /// expressions need to be made in order to avoid unknown dependences. For
296
+ /// example we might assume a unit stride for a pointer in order to prove
297
+ /// that a memory access is strided and doesn't wrap.
298
+ PredicatedScalarEvolution &PSE;
299
+ const Loop *InnermostLoop;
300
+
301
+ /// Reference to map of pointer values to
302
+ /// their stride symbols, if they have a symbolic stride.
303
+ const DenseMap<Value *, const SCEV *> &SymbolicStrides;
304
+
305
+ /// Maps access locations (ptr, read/write) to program order.
306
+ DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
307
+
308
+ /// Memory access instructions in program order.
309
+ SmallVector<Instruction *, 16> InstMap;
310
+
311
+ /// The program order index to be used for the next instruction.
312
+ unsigned AccessIdx = 0;
313
+
314
+ /// The smallest dependence distance in bytes in the loop. This may not be
315
+ /// the same as the maximum number of bytes that are safe to operate on
316
+ /// simultaneously.
317
+ uint64_t MinDepDistBytes = 0;
318
+
319
+ /// Number of elements (from consecutive iterations) that are safe to
320
+ /// operate on simultaneously, multiplied by the size of the element in bits.
321
+ /// The size of the element is taken from the memory access that is most
322
+ /// restrictive.
323
+ uint64_t MaxSafeVectorWidthInBits = -1U;
324
+
325
+ /// Maximum power-of-2 number of elements, which do not prevent store-load
326
+ /// forwarding, multiplied by the size of the elements in bits.
327
+ uint64_t MaxStoreLoadForwardSafeDistanceInBits =
328
+ std::numeric_limits<uint64_t>::max();
329
+
330
+ /// If we see a non-constant dependence distance we can still try to
331
+ /// vectorize this loop with runtime checks.
332
+ bool FoundNonConstantDistanceDependence = false;
333
+
334
+ /// Result of the dependence checks, indicating whether the checked
335
+ /// dependences are safe for vectorization, require RT checks or are known to
336
+ /// be unsafe.
337
+ VectorizationSafetyStatus Status = VectorizationSafetyStatus::Safe;
338
+
339
+ //// True if Dependences reflects the dependences in the
340
+ //// loop. If false we exceeded MaxDependences and
341
+ //// Dependences is invalid.
342
+ bool RecordDependences = true;
343
+
344
+ /// Memory dependences collected during the analysis. Only valid if
345
+ /// RecordDependences is true.
346
+ SmallVector<Dependence, 8> Dependences;
347
+
348
+ /// The maximum width of a target's vector registers multiplied by 2 to also
349
+ /// roughly account for additional interleaving. Is used to decide if a
350
+ /// backwards dependence with non-constant stride should be classified as
351
+ /// backwards-vectorizable or unknown (triggering a runtime check).
352
+ unsigned MaxTargetVectorWidthInBits = 0;
353
+
354
+ /// Mapping of SCEV expressions to their expanded pointer bounds (pair of
355
+ /// start and end pointer expressions).
356
+ DenseMap<std::pair<const SCEV *, Type *>,
357
+ std::pair<const SCEV *, const SCEV *>>
358
+ PointerBounds;
359
+
360
+ /// Cache for the loop guards of InnermostLoop.
361
+ std::optional<ScalarEvolution::LoopGuards> LoopGuards;
362
+
363
+ /// Check whether there is a plausible dependence between the two
364
+ /// accesses.
365
+ ///
366
+ /// Access \p A must happen before \p B in program order. The two indices
367
+ /// identify the index into the program order map.
368
+ ///
369
+ /// This function checks whether there is a plausible dependence (or the
370
+ /// absence of such can't be proved) between the two accesses. If there is a
371
+ /// plausible dependence but the dependence distance is bigger than one
372
+ /// element access it records this distance in \p MinDepDistBytes (if this
373
+ /// distance is smaller than any other distance encountered so far).
374
+ /// Otherwise, this function returns true signaling a possible dependence.
375
+ Dependence::DepType isDependent(const MemAccessInfo &A, unsigned AIdx,
376
+ const MemAccessInfo &B, unsigned BIdx);
377
+
378
+ /// Check whether the data dependence could prevent store-load
379
+ /// forwarding.
380
+ ///
381
+ /// \return false if we shouldn't vectorize at all or avoid larger
382
+ /// vectorization factors by limiting MinDepDistBytes.
383
+ bool couldPreventStoreLoadForward(uint64_t Distance, uint64_t TypeByteSize,
384
+ unsigned CommonStride = 0);
385
+
386
+ /// Updates the current safety status with \p S. We can go from Safe to
387
+ /// either PossiblySafeWithRtChecks or Unsafe and from
388
+ /// PossiblySafeWithRtChecks to Unsafe.
389
+ void mergeInStatus(VectorizationSafetyStatus S);
390
+
391
+ struct DepDistanceStrideAndSizeInfo {
392
+ const SCEV *Dist;
393
+
394
+ /// Strides here are scaled; i.e. in bytes, taking the size of the
395
+ /// underlying type into account.
396
+ uint64_t MaxStride;
397
+ std::optional<uint64_t> CommonStride;
398
+
399
+ bool ShouldRetryWithRuntimeCheck;
400
+
401
+ /// TypeByteSize is either the common store size of both accesses, or 0 when
402
+ /// store sizes mismatch.
403
+ uint64_t TypeByteSize;
404
+
405
+ bool AIsWrite;
406
+ bool BIsWrite;
407
+
408
+ DepDistanceStrideAndSizeInfo(const SCEV *Dist, uint64_t MaxStride,
409
+ std::optional<uint64_t> CommonStride,
410
+ bool ShouldRetryWithRuntimeCheck,
411
+ uint64_t TypeByteSize, bool AIsWrite,
412
+ bool BIsWrite)
413
+ : Dist(Dist), MaxStride(MaxStride), CommonStride(CommonStride),
414
+ ShouldRetryWithRuntimeCheck(ShouldRetryWithRuntimeCheck),
415
+ TypeByteSize(TypeByteSize), AIsWrite(AIsWrite), BIsWrite(BIsWrite) {}
416
+ };
417
+
418
+ /// Get the dependence distance, strides, type size and whether it is a write
419
+ /// for the dependence between A and B. Returns a DepType, if we can prove
420
+ /// there's no dependence or the analysis fails. Outlined to lambda to limit
421
+ /// he scope of various temporary variables, like A/BPtr, StrideA/BPtr and
422
+ /// others. Returns either the dependence result, if it could already be
423
+ /// determined, or a DepDistanceStrideAndSizeInfo struct, noting that
424
+ /// TypeByteSize could be 0 when store sizes mismatch, and this should be
425
+ /// checked in the caller.
426
+ std::variant<Dependence::DepType, DepDistanceStrideAndSizeInfo>
427
+ getDependenceDistanceStrideAndSize(const MemAccessInfo &A, Instruction *AInst,
428
+ const MemAccessInfo &B,
429
+ Instruction *BInst);
430
+ };
431
+
432
+ class RuntimePointerChecking;
433
+ /// A grouping of pointers. A single memcheck is required between
434
+ /// two groups.
435
+ struct RuntimeCheckingPtrGroup {
436
+ /// Create a new pointer checking group containing a single
437
+ /// pointer, with index \p Index in RtCheck.
438
+ LLVM_ABI RuntimeCheckingPtrGroup(unsigned Index,
439
+ const RuntimePointerChecking &RtCheck);
440
+
441
+ /// Tries to add the pointer recorded in RtCheck at index
442
+ /// \p Index to this pointer checking group. We can only add a pointer
443
+ /// to a checking group if we will still be able to get
444
+ /// the upper and lower bounds of the check. Returns true in case
445
+ /// of success, false otherwise.
446
+ LLVM_ABI bool addPointer(unsigned Index,
447
+ const RuntimePointerChecking &RtCheck);
448
+ LLVM_ABI bool addPointer(unsigned Index, const SCEV *Start, const SCEV *End,
449
+ unsigned AS, bool NeedsFreeze, ScalarEvolution &SE);
450
+
451
+ /// The SCEV expression which represents the upper bound of all the
452
+ /// pointers in this group.
453
+ const SCEV *High;
454
+ /// The SCEV expression which represents the lower bound of all the
455
+ /// pointers in this group.
456
+ const SCEV *Low;
457
+ /// Indices of all the pointers that constitute this grouping.
458
+ SmallVector<unsigned, 2> Members;
459
+ /// Address space of the involved pointers.
460
+ unsigned AddressSpace;
461
+ /// Whether the pointer needs to be frozen after expansion, e.g. because it
462
+ /// may be poison outside the loop.
463
+ bool NeedsFreeze = false;
464
+ };
465
+
466
+ /// A memcheck which made up of a pair of grouped pointers.
467
+ typedef std::pair<const RuntimeCheckingPtrGroup *,
468
+ const RuntimeCheckingPtrGroup *>
469
+ RuntimePointerCheck;
470
+
471
+ struct PointerDiffInfo {
472
+ const SCEV *SrcStart;
473
+ const SCEV *SinkStart;
474
+ unsigned AccessSize;
475
+ bool NeedsFreeze;
476
+
477
+ PointerDiffInfo(const SCEV *SrcStart, const SCEV *SinkStart,
478
+ unsigned AccessSize, bool NeedsFreeze)
479
+ : SrcStart(SrcStart), SinkStart(SinkStart), AccessSize(AccessSize),
480
+ NeedsFreeze(NeedsFreeze) {}
481
+ };
482
+
483
+ /// Holds information about the memory runtime legality checks to verify
484
+ /// that a group of pointers do not overlap.
485
+ class RuntimePointerChecking {
486
+ friend struct RuntimeCheckingPtrGroup;
487
+
488
+ public:
489
+ struct PointerInfo {
490
+ /// Holds the pointer value that we need to check.
491
+ TrackingVH<Value> PointerValue;
492
+ /// Holds the smallest byte address accessed by the pointer throughout all
493
+ /// iterations of the loop.
494
+ const SCEV *Start;
495
+ /// Holds the largest byte address accessed by the pointer throughout all
496
+ /// iterations of the loop, plus 1.
497
+ const SCEV *End;
498
+ /// Holds the information if this pointer is used for writing to memory.
499
+ bool IsWritePtr;
500
+ /// Holds the id of the set of pointers that could be dependent because of a
501
+ /// shared underlying object.
502
+ unsigned DependencySetId;
503
+ /// Holds the id of the disjoint alias set to which this pointer belongs.
504
+ unsigned AliasSetId;
505
+ /// SCEV for the access.
506
+ const SCEV *Expr;
507
+ /// True if the pointer expressions needs to be frozen after expansion.
508
+ bool NeedsFreeze;
509
+
510
+ PointerInfo(Value *PointerValue, const SCEV *Start, const SCEV *End,
511
+ bool IsWritePtr, unsigned DependencySetId, unsigned AliasSetId,
512
+ const SCEV *Expr, bool NeedsFreeze)
513
+ : PointerValue(PointerValue), Start(Start), End(End),
514
+ IsWritePtr(IsWritePtr), DependencySetId(DependencySetId),
515
+ AliasSetId(AliasSetId), Expr(Expr), NeedsFreeze(NeedsFreeze) {}
516
+ };
517
+
518
+ RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE)
519
+ : DC(DC), SE(SE) {}
520
+
521
+ /// Reset the state of the pointer runtime information.
522
+ void reset() {
523
+ Need = false;
524
+ CanUseDiffCheck = true;
525
+ Pointers.clear();
526
+ Checks.clear();
527
+ DiffChecks.clear();
528
+ CheckingGroups.clear();
529
+ }
530
+
531
+ /// Insert a pointer and calculate the start and end SCEVs.
532
+ /// We need \p PSE in order to compute the SCEV expression of the pointer
533
+ /// according to the assumptions that we've made during the analysis.
534
+ /// The method might also version the pointer stride according to \p Strides,
535
+ /// and add new predicates to \p PSE.
536
+ LLVM_ABI void insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
537
+ Type *AccessTy, bool WritePtr, unsigned DepSetId,
538
+ unsigned ASId, PredicatedScalarEvolution &PSE,
539
+ bool NeedsFreeze);
540
+
541
+ /// No run-time memory checking is necessary.
542
+ bool empty() const { return Pointers.empty(); }
543
+
544
+ /// Generate the checks and store it. This also performs the grouping
545
+ /// of pointers to reduce the number of memchecks necessary.
546
+ LLVM_ABI void generateChecks(MemoryDepChecker::DepCandidates &DepCands,
547
+ bool UseDependencies);
548
+
549
+ /// Returns the checks that generateChecks created. They can be used to ensure
550
+ /// no read/write accesses overlap across all loop iterations.
551
+ const SmallVectorImpl<RuntimePointerCheck> &getChecks() const {
552
+ return Checks;
553
+ }
554
+
555
+ // Returns an optional list of (pointer-difference expressions, access size)
556
+ // pairs that can be used to prove that there are no vectorization-preventing
557
+ // dependencies at runtime. There are is a vectorization-preventing dependency
558
+ // if any pointer-difference is <u VF * InterleaveCount * access size. Returns
559
+ // std::nullopt if pointer-difference checks cannot be used.
560
+ std::optional<ArrayRef<PointerDiffInfo>> getDiffChecks() const {
561
+ if (!CanUseDiffCheck)
562
+ return std::nullopt;
563
+ return {DiffChecks};
564
+ }
565
+
566
+ /// Decide if we need to add a check between two groups of pointers,
567
+ /// according to needsChecking.
568
+ LLVM_ABI bool needsChecking(const RuntimeCheckingPtrGroup &M,
569
+ const RuntimeCheckingPtrGroup &N) const;
570
+
571
+ /// Returns the number of run-time checks required according to
572
+ /// needsChecking.
573
+ unsigned getNumberOfChecks() const { return Checks.size(); }
574
+
575
+ /// Print the list run-time memory checks necessary.
576
+ LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
577
+
578
+ /// Print \p Checks.
579
+ LLVM_ABI void printChecks(raw_ostream &OS,
580
+ const SmallVectorImpl<RuntimePointerCheck> &Checks,
581
+ unsigned Depth = 0) const;
582
+
583
+ /// This flag indicates if we need to add the runtime check.
584
+ bool Need = false;
585
+
586
+ /// Information about the pointers that may require checking.
587
+ SmallVector<PointerInfo, 2> Pointers;
588
+
589
+ /// Holds a partitioning of pointers into "check groups".
590
+ SmallVector<RuntimeCheckingPtrGroup, 2> CheckingGroups;
591
+
592
+ /// Check if pointers are in the same partition
593
+ ///
594
+ /// \p PtrToPartition contains the partition number for pointers (-1 if the
595
+ /// pointer belongs to multiple partitions).
596
+ LLVM_ABI static bool
597
+ arePointersInSamePartition(const SmallVectorImpl<int> &PtrToPartition,
598
+ unsigned PtrIdx1, unsigned PtrIdx2);
599
+
600
+ /// Decide whether we need to issue a run-time check for pointer at
601
+ /// index \p I and \p J to prove their independence.
602
+ LLVM_ABI bool needsChecking(unsigned I, unsigned J) const;
603
+
604
+ /// Return PointerInfo for pointer at index \p PtrIdx.
605
+ const PointerInfo &getPointerInfo(unsigned PtrIdx) const {
606
+ return Pointers[PtrIdx];
607
+ }
608
+
609
+ ScalarEvolution *getSE() const { return SE; }
610
+
611
+ private:
612
+ /// Groups pointers such that a single memcheck is required
613
+ /// between two different groups. This will clear the CheckingGroups vector
614
+ /// and re-compute it. We will only group dependecies if \p UseDependencies
615
+ /// is true, otherwise we will create a separate group for each pointer.
616
+ void groupChecks(MemoryDepChecker::DepCandidates &DepCands,
617
+ bool UseDependencies);
618
+
619
+ /// Generate the checks and return them.
620
+ SmallVector<RuntimePointerCheck, 4> generateChecks();
621
+
622
+ /// Try to create add a new (pointer-difference, access size) pair to
623
+ /// DiffCheck for checking groups \p CGI and \p CGJ. If pointer-difference
624
+ /// checks cannot be used for the groups, set CanUseDiffCheck to false.
625
+ bool tryToCreateDiffCheck(const RuntimeCheckingPtrGroup &CGI,
626
+ const RuntimeCheckingPtrGroup &CGJ);
627
+
628
+ MemoryDepChecker &DC;
629
+
630
+ /// Holds a pointer to the ScalarEvolution analysis.
631
+ ScalarEvolution *SE;
632
+
633
+ /// Set of run-time checks required to establish independence of
634
+ /// otherwise may-aliasing pointers in the loop.
635
+ SmallVector<RuntimePointerCheck, 4> Checks;
636
+
637
+ /// Flag indicating if pointer-difference checks can be used
638
+ bool CanUseDiffCheck = true;
639
+
640
+ /// A list of (pointer-difference, access size) pairs that can be used to
641
+ /// prove that there are no vectorization-preventing dependencies.
642
+ SmallVector<PointerDiffInfo> DiffChecks;
643
+ };
644
+
645
+ /// Drive the analysis of memory accesses in the loop
646
+ ///
647
+ /// This class is responsible for analyzing the memory accesses of a loop. It
648
+ /// collects the accesses and then its main helper the AccessAnalysis class
649
+ /// finds and categorizes the dependences in buildDependenceSets.
650
+ ///
651
+ /// For memory dependences that can be analyzed at compile time, it determines
652
+ /// whether the dependence is part of cycle inhibiting vectorization. This work
653
+ /// is delegated to the MemoryDepChecker class.
654
+ ///
655
+ /// For memory dependences that cannot be determined at compile time, it
656
+ /// generates run-time checks to prove independence. This is done by
657
+ /// AccessAnalysis::canCheckPtrAtRT and the checks are maintained by the
658
+ /// RuntimePointerCheck class. \p AllowPartial determines whether partial checks
659
+ /// are generated when not all pointers could be analyzed.
660
+ ///
661
+ /// If pointers can wrap or can't be expressed as affine AddRec expressions by
662
+ /// ScalarEvolution, we will generate run-time checks by emitting a
663
+ /// SCEVUnionPredicate.
664
+ ///
665
+ /// Checks for both memory dependences and the SCEV predicates contained in the
666
+ /// PSE must be emitted in order for the results of this analysis to be valid.
667
+ class LoopAccessInfo {
668
+ public:
669
+ LLVM_ABI LoopAccessInfo(Loop *L, ScalarEvolution *SE,
670
+ const TargetTransformInfo *TTI,
671
+ const TargetLibraryInfo *TLI, AAResults *AA,
672
+ DominatorTree *DT, LoopInfo *LI,
673
+ bool AllowPartial = false);
674
+
675
+ /// Return true we can analyze the memory accesses in the loop and there are
676
+ /// no memory dependence cycles. Note that for dependences between loads &
677
+ /// stores with uniform addresses,
678
+ /// hasStoreStoreDependenceInvolvingLoopInvariantAddress and
679
+ /// hasLoadStoreDependenceInvolvingLoopInvariantAddress also need to be
680
+ /// checked.
681
+ bool canVectorizeMemory() const { return CanVecMem; }
682
+
683
+ /// Return true if there is a convergent operation in the loop. There may
684
+ /// still be reported runtime pointer checks that would be required, but it is
685
+ /// not legal to insert them.
686
+ bool hasConvergentOp() const { return HasConvergentOp; }
687
+
688
+ /// Return true if, when runtime pointer checking does not have complete
689
+ /// results, it instead has partial results for those memory accesses that
690
+ /// could be analyzed.
691
+ bool hasAllowPartial() const { return AllowPartial; }
692
+
693
+ const RuntimePointerChecking *getRuntimePointerChecking() const {
694
+ return PtrRtChecking.get();
695
+ }
696
+
697
+ /// Number of memchecks required to prove independence of otherwise
698
+ /// may-alias pointers.
699
+ unsigned getNumRuntimePointerChecks() const {
700
+ return PtrRtChecking->getNumberOfChecks();
701
+ }
702
+
703
+ /// Return true if the block BB needs to be predicated in order for the loop
704
+ /// to be vectorized.
705
+ LLVM_ABI static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop,
706
+ DominatorTree *DT);
707
+
708
+ /// Returns true if value \p V is loop invariant.
709
+ LLVM_ABI bool isInvariant(Value *V) const;
710
+
711
+ unsigned getNumStores() const { return NumStores; }
712
+ unsigned getNumLoads() const { return NumLoads;}
713
+
714
+ /// The diagnostics report generated for the analysis. E.g. why we
715
+ /// couldn't analyze the loop.
716
+ const OptimizationRemarkAnalysis *getReport() const { return Report.get(); }
717
+
718
+ /// the Memory Dependence Checker which can determine the
719
+ /// loop-independent and loop-carried dependences between memory accesses.
720
+ const MemoryDepChecker &getDepChecker() const { return *DepChecker; }
721
+
722
+ /// Return the list of instructions that use \p Ptr to read or write
723
+ /// memory.
724
+ SmallVector<Instruction *, 4> getInstructionsForAccess(Value *Ptr,
725
+ bool isWrite) const {
726
+ return DepChecker->getInstructionsForAccess(Ptr, isWrite);
727
+ }
728
+
729
+ /// If an access has a symbolic strides, this maps the pointer value to
730
+ /// the stride symbol.
731
+ const DenseMap<Value *, const SCEV *> &getSymbolicStrides() const {
732
+ return SymbolicStrides;
733
+ }
734
+
735
+ /// Print the information about the memory accesses in the loop.
736
+ LLVM_ABI void print(raw_ostream &OS, unsigned Depth = 0) const;
737
+
738
+ /// Return true if the loop has memory dependence involving two stores to an
739
+ /// invariant address, else return false.
740
+ bool hasStoreStoreDependenceInvolvingLoopInvariantAddress() const {
741
+ return HasStoreStoreDependenceInvolvingLoopInvariantAddress;
742
+ }
743
+
744
+ /// Return true if the loop has memory dependence involving a load and a store
745
+ /// to an invariant address, else return false.
746
+ bool hasLoadStoreDependenceInvolvingLoopInvariantAddress() const {
747
+ return HasLoadStoreDependenceInvolvingLoopInvariantAddress;
748
+ }
749
+
750
+ /// Return the list of stores to invariant addresses.
751
+ ArrayRef<StoreInst *> getStoresToInvariantAddresses() const {
752
+ return StoresToInvariantAddresses;
753
+ }
754
+
755
+ /// Used to add runtime SCEV checks. Simplifies SCEV expressions and converts
756
+ /// them to a more usable form. All SCEV expressions during the analysis
757
+ /// should be re-written (and therefore simplified) according to PSE.
758
+ /// A user of LoopAccessAnalysis will need to emit the runtime checks
759
+ /// associated with this predicate.
760
+ const PredicatedScalarEvolution &getPSE() const { return *PSE; }
761
+
762
+ private:
763
+ /// Analyze the loop. Returns true if all memory access in the loop can be
764
+ /// vectorized.
765
+ bool analyzeLoop(AAResults *AA, const LoopInfo *LI,
766
+ const TargetLibraryInfo *TLI, DominatorTree *DT);
767
+
768
+ /// Check if the structure of the loop allows it to be analyzed by this
769
+ /// pass.
770
+ bool canAnalyzeLoop();
771
+
772
+ /// Save the analysis remark.
773
+ ///
774
+ /// LAA does not directly emits the remarks. Instead it stores it which the
775
+ /// client can retrieve and presents as its own analysis
776
+ /// (e.g. -Rpass-analysis=loop-vectorize).
777
+ OptimizationRemarkAnalysis &
778
+ recordAnalysis(StringRef RemarkName, const Instruction *Instr = nullptr);
779
+
780
+ /// Collect memory access with loop invariant strides.
781
+ ///
782
+ /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
783
+ /// invariant.
784
+ void collectStridedAccess(Value *LoadOrStoreInst);
785
+
786
+ // Emits the first unsafe memory dependence in a loop.
787
+ // Emits nothing if there are no unsafe dependences
788
+ // or if the dependences were not recorded.
789
+ void emitUnsafeDependenceRemark();
790
+
791
+ std::unique_ptr<PredicatedScalarEvolution> PSE;
792
+
793
+ /// We need to check that all of the pointers in this list are disjoint
794
+ /// at runtime. Using std::unique_ptr to make using move ctor simpler.
795
+ /// If AllowPartial is true then this list may contain only partial
796
+ /// information when we've failed to analyze all the memory accesses in the
797
+ /// loop, in which case HasCompletePtrRtChecking will be false.
798
+ std::unique_ptr<RuntimePointerChecking> PtrRtChecking;
799
+
800
+ /// The Memory Dependence Checker which can determine the
801
+ /// loop-independent and loop-carried dependences between memory accesses.
802
+ /// This will be empty if we've failed to analyze all the memory access in the
803
+ /// loop (i.e. CanVecMem is false).
804
+ std::unique_ptr<MemoryDepChecker> DepChecker;
805
+
806
+ Loop *TheLoop;
807
+
808
+ /// Determines whether we should generate partial runtime checks when not all
809
+ /// memory accesses could be analyzed.
810
+ bool AllowPartial;
811
+
812
+ unsigned NumLoads = 0;
813
+ unsigned NumStores = 0;
814
+
815
+ /// Cache the result of analyzeLoop.
816
+ bool CanVecMem = false;
817
+ bool HasConvergentOp = false;
818
+ bool HasCompletePtrRtChecking = false;
819
+
820
+ /// Indicator that there are two non vectorizable stores to the same uniform
821
+ /// address.
822
+ bool HasStoreStoreDependenceInvolvingLoopInvariantAddress = false;
823
+ /// Indicator that there is non vectorizable load and store to the same
824
+ /// uniform address.
825
+ bool HasLoadStoreDependenceInvolvingLoopInvariantAddress = false;
826
+
827
+ /// List of stores to invariant addresses.
828
+ SmallVector<StoreInst *> StoresToInvariantAddresses;
829
+
830
+ /// The diagnostics report generated for the analysis. E.g. why we
831
+ /// couldn't analyze the loop.
832
+ std::unique_ptr<OptimizationRemarkAnalysis> Report;
833
+
834
+ /// If an access has a symbolic strides, this maps the pointer value to
835
+ /// the stride symbol.
836
+ DenseMap<Value *, const SCEV *> SymbolicStrides;
837
+ };
838
+
839
+ /// Return the SCEV corresponding to a pointer with the symbolic stride
840
+ /// replaced with constant one, assuming the SCEV predicate associated with
841
+ /// \p PSE is true.
842
+ ///
843
+ /// If necessary this method will version the stride of the pointer according
844
+ /// to \p PtrToStride and therefore add further predicates to \p PSE.
845
+ ///
846
+ /// \p PtrToStride provides the mapping between the pointer value and its
847
+ /// stride as collected by LoopVectorizationLegality::collectStridedAccess.
848
+ LLVM_ABI const SCEV *
849
+ replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE,
850
+ const DenseMap<Value *, const SCEV *> &PtrToStride,
851
+ Value *Ptr);
852
+
853
+ /// If the pointer has a constant stride return it in units of the access type
854
+ /// size. If the pointer is loop-invariant, return 0. Otherwise return
855
+ /// std::nullopt.
856
+ ///
857
+ /// Ensure that it does not wrap in the address space, assuming the predicate
858
+ /// associated with \p PSE is true.
859
+ ///
860
+ /// If necessary this method will version the stride of the pointer according
861
+ /// to \p PtrToStride and therefore add further predicates to \p PSE.
862
+ /// The \p Assume parameter indicates if we are allowed to make additional
863
+ /// run-time assumptions.
864
+ ///
865
+ /// Note that the analysis results are defined if-and-only-if the original
866
+ /// memory access was defined. If that access was dead, or UB, then the
867
+ /// result of this function is undefined.
868
+ LLVM_ABI std::optional<int64_t>
869
+ getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr,
870
+ const Loop *Lp,
871
+ const DenseMap<Value *, const SCEV *> &StridesMap =
872
+ DenseMap<Value *, const SCEV *>(),
873
+ bool Assume = false, bool ShouldCheckWrap = true);
874
+
875
+ /// Returns the distance between the pointers \p PtrA and \p PtrB iff they are
876
+ /// compatible and it is possible to calculate the distance between them. This
877
+ /// is a simple API that does not depend on the analysis pass.
878
+ /// \param StrictCheck Ensure that the calculated distance matches the
879
+ /// type-based one after all the bitcasts removal in the provided pointers.
880
+ LLVM_ABI std::optional<int64_t>
881
+ getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, Value *PtrB,
882
+ const DataLayout &DL, ScalarEvolution &SE,
883
+ bool StrictCheck = false, bool CheckType = true);
884
+
885
+ /// Attempt to sort the pointers in \p VL and return the sorted indices
886
+ /// in \p SortedIndices, if reordering is required.
887
+ ///
888
+ /// Returns 'true' if sorting is legal, otherwise returns 'false'.
889
+ ///
890
+ /// For example, for a given \p VL of memory accesses in program order, a[i+4],
891
+ /// a[i+0], a[i+1] and a[i+7], this function will sort the \p VL and save the
892
+ /// sorted indices in \p SortedIndices as a[i+0], a[i+1], a[i+4], a[i+7] and
893
+ /// saves the mask for actual memory accesses in program order in
894
+ /// \p SortedIndices as <1,2,0,3>
895
+ LLVM_ABI bool sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
896
+ const DataLayout &DL, ScalarEvolution &SE,
897
+ SmallVectorImpl<unsigned> &SortedIndices);
898
+
899
+ /// Returns true if the memory operations \p A and \p B are consecutive.
900
+ /// This is a simple API that does not depend on the analysis pass.
901
+ LLVM_ABI bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL,
902
+ ScalarEvolution &SE, bool CheckType = true);
903
+
904
+ /// Calculate Start and End points of memory access.
905
+ /// Let's assume A is the first access and B is a memory access on N-th loop
906
+ /// iteration. Then B is calculated as:
907
+ /// B = A + Step*N .
908
+ /// Step value may be positive or negative.
909
+ /// N is a calculated back-edge taken count:
910
+ /// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0
911
+ /// Start and End points are calculated in the following way:
912
+ /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt,
913
+ /// where SizeOfElt is the size of single memory access in bytes.
914
+ ///
915
+ /// There is no conflict when the intervals are disjoint:
916
+ /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End)
917
+ LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
918
+ const Loop *Lp, const SCEV *PtrExpr, Type *AccessTy, const SCEV *MaxBECount,
919
+ ScalarEvolution *SE,
920
+ DenseMap<std::pair<const SCEV *, Type *>,
921
+ std::pair<const SCEV *, const SCEV *>> *PointerBounds);
922
+
923
+ class LoopAccessInfoManager {
924
+ /// The cache.
925
+ DenseMap<Loop *, std::unique_ptr<LoopAccessInfo>> LoopAccessInfoMap;
926
+
927
+ // The used analysis passes.
928
+ ScalarEvolution &SE;
929
+ AAResults &AA;
930
+ DominatorTree &DT;
931
+ LoopInfo &LI;
932
+ TargetTransformInfo *TTI;
933
+ const TargetLibraryInfo *TLI = nullptr;
934
+
935
+ public:
936
+ LoopAccessInfoManager(ScalarEvolution &SE, AAResults &AA, DominatorTree &DT,
937
+ LoopInfo &LI, TargetTransformInfo *TTI,
938
+ const TargetLibraryInfo *TLI)
939
+ : SE(SE), AA(AA), DT(DT), LI(LI), TTI(TTI), TLI(TLI) {}
940
+
941
+ LLVM_ABI const LoopAccessInfo &getInfo(Loop &L, bool AllowPartial = false);
942
+
943
+ LLVM_ABI void clear();
944
+
945
+ LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
946
+ FunctionAnalysisManager::Invalidator &Inv);
947
+ };
948
+
949
+ /// This analysis provides dependence information for the memory
950
+ /// accesses of a loop.
951
+ ///
952
+ /// It runs the analysis for a loop on demand. This can be initiated by
953
+ /// querying the loop access info via AM.getResult<LoopAccessAnalysis>.
954
+ /// getResult return a LoopAccessInfo object. See this class for the
955
+ /// specifics of what information is provided.
956
+ class LoopAccessAnalysis
957
+ : public AnalysisInfoMixin<LoopAccessAnalysis> {
958
+ friend AnalysisInfoMixin<LoopAccessAnalysis>;
959
+ LLVM_ABI static AnalysisKey Key;
960
+
961
+ public:
962
+ typedef LoopAccessInfoManager Result;
963
+
964
+ LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM);
965
+ };
966
+
967
+ inline Instruction *MemoryDepChecker::Dependence::getSource(
968
+ const MemoryDepChecker &DepChecker) const {
969
+ return DepChecker.getMemoryInstructions()[Source];
970
+ }
971
+
972
+ inline Instruction *MemoryDepChecker::Dependence::getDestination(
973
+ const MemoryDepChecker &DepChecker) const {
974
+ return DepChecker.getMemoryInstructions()[Destination];
975
+ }
976
+
977
+ } // End llvm namespace
978
+
979
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/LoopAnalysisManager.h ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- LoopAnalysisManager.h - Loop analysis management ---------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ ///
10
+ /// This header provides classes for managing per-loop analyses. These are
11
+ /// typically used as part of a loop pass pipeline over the loop nests of
12
+ /// a function.
13
+ ///
14
+ /// Loop analyses are allowed to make some simplifying assumptions:
15
+ /// 1) Loops are, where possible, in simplified form.
16
+ /// 2) Loops are *always* in LCSSA form.
17
+ /// 3) A collection of analysis results are available:
18
+ /// - LoopInfo
19
+ /// - DominatorTree
20
+ /// - ScalarEvolution
21
+ /// - AAManager
22
+ ///
23
+ /// The primary mechanism to provide these invariants is the loop pass manager,
24
+ /// but they can also be manually provided in order to reason about a loop from
25
+ /// outside of a dedicated pass manager.
26
+ ///
27
+ //===----------------------------------------------------------------------===//
28
+
29
+ #ifndef LLVM_ANALYSIS_LOOPANALYSISMANAGER_H
30
+ #define LLVM_ANALYSIS_LOOPANALYSISMANAGER_H
31
+
32
+ #include "llvm/IR/PassManager.h"
33
+ #include "llvm/Support/Compiler.h"
34
+
35
+ namespace llvm {
36
+
37
+ class AAResults;
38
+ class AssumptionCache;
39
+ class BlockFrequencyInfo;
40
+ class BranchProbabilityInfo;
41
+ class DominatorTree;
42
+ class Function;
43
+ class Loop;
44
+ class LoopInfo;
45
+ class MemorySSA;
46
+ class ScalarEvolution;
47
+ class TargetLibraryInfo;
48
+ class TargetTransformInfo;
49
+
50
+ /// The adaptor from a function pass to a loop pass computes these analyses and
51
+ /// makes them available to the loop passes "for free". Each loop pass is
52
+ /// expected to update these analyses if necessary to ensure they're
53
+ /// valid after it runs.
54
+ struct LoopStandardAnalysisResults {
55
+ AAResults &AA;
56
+ AssumptionCache &AC;
57
+ DominatorTree &DT;
58
+ LoopInfo &LI;
59
+ ScalarEvolution &SE;
60
+ TargetLibraryInfo &TLI;
61
+ TargetTransformInfo &TTI;
62
+ BlockFrequencyInfo *BFI;
63
+ BranchProbabilityInfo *BPI;
64
+ MemorySSA *MSSA;
65
+ };
66
+
67
+ /// Extern template declaration for the analysis set for this IR unit.
68
+ extern template class LLVM_TEMPLATE_ABI AllAnalysesOn<Loop>;
69
+
70
+ extern template class LLVM_TEMPLATE_ABI
71
+ AnalysisManager<Loop, LoopStandardAnalysisResults &>;
72
+ /// The loop analysis manager.
73
+ ///
74
+ /// See the documentation for the AnalysisManager template for detail
75
+ /// documentation. This typedef serves as a convenient way to refer to this
76
+ /// construct in the adaptors and proxies used to integrate this into the larger
77
+ /// pass manager infrastructure.
78
+ typedef AnalysisManager<Loop, LoopStandardAnalysisResults &>
79
+ LoopAnalysisManager;
80
+
81
+ /// A proxy from a \c LoopAnalysisManager to a \c Function.
82
+ typedef InnerAnalysisManagerProxy<LoopAnalysisManager, Function>
83
+ LoopAnalysisManagerFunctionProxy;
84
+
85
+ /// A specialized result for the \c LoopAnalysisManagerFunctionProxy which
86
+ /// retains a \c LoopInfo reference.
87
+ ///
88
+ /// This allows it to collect loop objects for which analysis results may be
89
+ /// cached in the \c LoopAnalysisManager.
90
+ template <> class LoopAnalysisManagerFunctionProxy::Result {
91
+ public:
92
+ explicit Result(LoopAnalysisManager &InnerAM, LoopInfo &LI)
93
+ : InnerAM(&InnerAM), LI(&LI) {}
94
+ Result(Result &&Arg)
95
+ : InnerAM(std::move(Arg.InnerAM)), LI(Arg.LI), MSSAUsed(Arg.MSSAUsed) {
96
+ // We have to null out the analysis manager in the moved-from state
97
+ // because we are taking ownership of the responsibilty to clear the
98
+ // analysis state.
99
+ Arg.InnerAM = nullptr;
100
+ }
101
+ Result &operator=(Result &&RHS) {
102
+ InnerAM = RHS.InnerAM;
103
+ LI = RHS.LI;
104
+ MSSAUsed = RHS.MSSAUsed;
105
+ // We have to null out the analysis manager in the moved-from state
106
+ // because we are taking ownership of the responsibilty to clear the
107
+ // analysis state.
108
+ RHS.InnerAM = nullptr;
109
+ return *this;
110
+ }
111
+ ~Result() {
112
+ // InnerAM is cleared in a moved from state where there is nothing to do.
113
+ if (!InnerAM)
114
+ return;
115
+
116
+ // Clear out the analysis manager if we're being destroyed -- it means we
117
+ // didn't even see an invalidate call when we got invalidated.
118
+ InnerAM->clear();
119
+ }
120
+
121
+ /// Mark MemorySSA as used so we can invalidate self if MSSA is invalidated.
122
+ void markMSSAUsed() { MSSAUsed = true; }
123
+
124
+ /// Accessor for the analysis manager.
125
+ LoopAnalysisManager &getManager() { return *InnerAM; }
126
+
127
+ /// Handler for invalidation of the proxy for a particular function.
128
+ ///
129
+ /// If the proxy, \c LoopInfo, and associated analyses are preserved, this
130
+ /// will merely forward the invalidation event to any cached loop analysis
131
+ /// results for loops within this function.
132
+ ///
133
+ /// If the necessary loop infrastructure is not preserved, this will forcibly
134
+ /// clear all of the cached analysis results that are keyed on the \c
135
+ /// LoopInfo for this function.
136
+ LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
137
+ FunctionAnalysisManager::Invalidator &Inv);
138
+
139
+ private:
140
+ LoopAnalysisManager *InnerAM;
141
+ LoopInfo *LI;
142
+ bool MSSAUsed = false;
143
+ };
144
+
145
+ /// Provide a specialized run method for the \c LoopAnalysisManagerFunctionProxy
146
+ /// so it can pass the \c LoopInfo to the result.
147
+ template <>
148
+ LLVM_ABI LoopAnalysisManagerFunctionProxy::Result
149
+ LoopAnalysisManagerFunctionProxy::run(Function &F, FunctionAnalysisManager &AM);
150
+
151
+ // Ensure the \c LoopAnalysisManagerFunctionProxy is provided as an extern
152
+ // template.
153
+ extern template class InnerAnalysisManagerProxy<LoopAnalysisManager, Function>;
154
+
155
+ extern template class LLVM_TEMPLATE_ABI OuterAnalysisManagerProxy<
156
+ FunctionAnalysisManager, Loop, LoopStandardAnalysisResults &>;
157
+ /// A proxy from a \c FunctionAnalysisManager to a \c Loop.
158
+ typedef OuterAnalysisManagerProxy<FunctionAnalysisManager, Loop,
159
+ LoopStandardAnalysisResults &>
160
+ FunctionAnalysisManagerLoopProxy;
161
+
162
+ /// Returns the minimum set of Analyses that all loop passes must preserve.
163
+ LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses();
164
+ }
165
+
166
+ #endif // LLVM_ANALYSIS_LOOPANALYSISMANAGER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/LoopCacheAnalysis.h ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/LoopCacheAnalysis.h ------------------------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ ///
9
+ /// \file
10
+ /// This file defines the interface for the loop cache analysis.
11
+ ///
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
15
+ #define LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
16
+
17
+ #include "llvm/Analysis/LoopAnalysisManager.h"
18
+ #include "llvm/IR/PassManager.h"
19
+ #include "llvm/Support/InstructionCost.h"
20
+ #include <optional>
21
+
22
+ namespace llvm {
23
+
24
+ class AAResults;
25
+ class DependenceInfo;
26
+ class Instruction;
27
+ class LPMUpdater;
28
+ class raw_ostream;
29
+ class LoopInfo;
30
+ class Loop;
31
+ class ScalarEvolution;
32
+ class SCEV;
33
+ class TargetTransformInfo;
34
+
35
+ using CacheCostTy = InstructionCost;
36
+ using LoopVectorTy = SmallVector<Loop *, 8>;
37
+
38
+ /// Represents a memory reference as a base pointer and a set of indexing
39
+ /// operations. For example given the array reference A[i][2j+1][3k+2] in a
40
+ /// 3-dim loop nest:
41
+ /// for(i=0;i<n;++i)
42
+ /// for(j=0;j<m;++j)
43
+ /// for(k=0;k<o;++k)
44
+ /// ... A[i][2j+1][3k+2] ...
45
+ /// We expect:
46
+ /// BasePointer -> A
47
+ /// Subscripts -> [{0,+,1}<%for.i>][{1,+,2}<%for.j>][{2,+,3}<%for.k>]
48
+ /// Sizes -> [m][o][4]
49
+ class IndexedReference {
50
+ friend raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
51
+
52
+ public:
53
+ /// Construct an indexed reference given a \p StoreOrLoadInst instruction.
54
+ IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI,
55
+ ScalarEvolution &SE);
56
+
57
+ bool isValid() const { return IsValid; }
58
+ const SCEV *getBasePointer() const { return BasePointer; }
59
+ size_t getNumSubscripts() const { return Subscripts.size(); }
60
+ const SCEV *getSubscript(unsigned SubNum) const {
61
+ assert(SubNum < getNumSubscripts() && "Invalid subscript number");
62
+ return Subscripts[SubNum];
63
+ }
64
+ const SCEV *getFirstSubscript() const {
65
+ assert(!Subscripts.empty() && "Expecting non-empty container");
66
+ return Subscripts.front();
67
+ }
68
+ const SCEV *getLastSubscript() const {
69
+ assert(!Subscripts.empty() && "Expecting non-empty container");
70
+ return Subscripts.back();
71
+ }
72
+
73
+ /// Return true/false if the current object and the indexed reference \p Other
74
+ /// are/aren't in the same cache line of size \p CLS. Two references are in
75
+ /// the same chace line iff the distance between them in the innermost
76
+ /// dimension is less than the cache line size. Return std::nullopt if unsure.
77
+ std::optional<bool> hasSpacialReuse(const IndexedReference &Other,
78
+ unsigned CLS, AAResults &AA) const;
79
+
80
+ /// Return true if the current object and the indexed reference \p Other
81
+ /// have distance smaller than \p MaxDistance in the dimension associated with
82
+ /// the given loop \p L. Return false if the distance is not smaller than \p
83
+ /// MaxDistance and std::nullopt if unsure.
84
+ std::optional<bool> hasTemporalReuse(const IndexedReference &Other,
85
+ unsigned MaxDistance, const Loop &L,
86
+ DependenceInfo &DI, AAResults &AA) const;
87
+
88
+ /// Compute the cost of the reference w.r.t. the given loop \p L when it is
89
+ /// considered in the innermost position in the loop nest.
90
+ /// The cost is defined as:
91
+ /// - equal to one if the reference is loop invariant, or
92
+ /// - equal to '(TripCount * stride) / cache_line_size' if:
93
+ /// + the reference stride is less than the cache line size, and
94
+ /// + the coefficient of this loop's index variable used in all other
95
+ /// subscripts is zero
96
+ /// - or otherwise equal to 'TripCount'.
97
+ CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const;
98
+
99
+ private:
100
+ /// Attempt to delinearize the indexed reference.
101
+ bool delinearize(const LoopInfo &LI);
102
+
103
+ /// Attempt to delinearize \p AccessFn for fixed-size arrays.
104
+ bool tryDelinearizeFixedSize(const SCEV *AccessFn,
105
+ SmallVectorImpl<const SCEV *> &Subscripts);
106
+
107
+ /// Return true if the index reference is invariant with respect to loop \p L.
108
+ bool isLoopInvariant(const Loop &L) const;
109
+
110
+ /// Return true if the indexed reference is 'consecutive' in loop \p L.
111
+ /// An indexed reference is 'consecutive' if the only coefficient that uses
112
+ /// the loop induction variable is the rightmost one, and the access stride is
113
+ /// smaller than the cache line size \p CLS. Provide a valid \p Stride value
114
+ /// if the indexed reference is 'consecutive'.
115
+ bool isConsecutive(const Loop &L, const SCEV *&Stride, unsigned CLS) const;
116
+
117
+ /// Retrieve the index of the subscript corresponding to the given loop \p
118
+ /// L. Return a zero-based positive index if the subscript index is
119
+ /// succesfully located and a negative value otherwise. For example given the
120
+ /// indexed reference 'A[i][2j+1][3k+2]', the call
121
+ /// 'getSubscriptIndex(loop-k)' would return value 2.
122
+ int getSubscriptIndex(const Loop &L) const;
123
+
124
+ /// Return the coefficient used in the rightmost dimension.
125
+ const SCEV *getLastCoefficient() const;
126
+
127
+ /// Return true if the coefficient corresponding to induction variable of
128
+ /// loop \p L in the given \p Subscript is zero or is loop invariant in \p L.
129
+ bool isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
130
+ const Loop &L) const;
131
+
132
+ /// Verify that the given \p Subscript is 'well formed' (must be a simple add
133
+ /// recurrence).
134
+ bool isSimpleAddRecurrence(const SCEV &Subscript, const Loop &L) const;
135
+
136
+ /// Return true if the given reference \p Other is definetely aliased with
137
+ /// the indexed reference represented by this class.
138
+ bool isAliased(const IndexedReference &Other, AAResults &AA) const;
139
+
140
+ private:
141
+ /// True if the reference can be delinearized, false otherwise.
142
+ bool IsValid = false;
143
+
144
+ /// Represent the memory reference instruction.
145
+ Instruction &StoreOrLoadInst;
146
+
147
+ /// The base pointer of the memory reference.
148
+ const SCEV *BasePointer = nullptr;
149
+
150
+ /// The subscript (indexes) of the memory reference.
151
+ SmallVector<const SCEV *, 3> Subscripts;
152
+
153
+ /// The dimensions of the memory reference.
154
+ SmallVector<const SCEV *, 3> Sizes;
155
+
156
+ ScalarEvolution &SE;
157
+ };
158
+
159
+ /// A reference group represents a set of memory references that exhibit
160
+ /// temporal or spacial reuse. Two references belong to the same
161
+ /// reference group with respect to a inner loop L iff:
162
+ /// 1. they have a loop independent dependency, or
163
+ /// 2. they have a loop carried dependence with a small dependence distance
164
+ /// (e.g. less than 2) carried by the inner loop, or
165
+ /// 3. they refer to the same array, and the subscript in their innermost
166
+ /// dimension is less than or equal to 'd' (where 'd' is less than the cache
167
+ /// line size)
168
+ ///
169
+ /// Intuitively a reference group represents memory references that access
170
+ /// the same cache line. Conditions 1,2 above account for temporal reuse, while
171
+ /// contition 3 accounts for spacial reuse.
172
+ using ReferenceGroupTy = SmallVector<std::unique_ptr<IndexedReference>, 8>;
173
+ using ReferenceGroupsTy = SmallVector<ReferenceGroupTy, 8>;
174
+
175
+ /// \c CacheCost represents the estimated cost of a inner loop as the number of
176
+ /// cache lines used by the memory references it contains.
177
+ /// The 'cache cost' of a loop 'L' in a loop nest 'LN' is computed as the sum of
178
+ /// the cache costs of all of its reference groups when the loop is considered
179
+ /// to be in the innermost position in the nest.
180
+ /// A reference group represents memory references that fall into the same cache
181
+ /// line. Each reference group is analysed with respect to the innermost loop in
182
+ /// a loop nest. The cost of a reference is defined as follow:
183
+ /// - one if it is loop invariant w.r.t the innermost loop,
184
+ /// - equal to the loop trip count divided by the cache line times the
185
+ /// reference stride if the reference stride is less than the cache line
186
+ /// size (CLS), and the coefficient of this loop's index variable used in all
187
+ /// other subscripts is zero (e.g. RefCost = TripCount/(CLS/RefStride))
188
+ /// - equal to the innermost loop trip count if the reference stride is greater
189
+ /// or equal to the cache line size CLS.
190
+ class CacheCost {
191
+ friend raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
192
+ using LoopTripCountTy = std::pair<const Loop *, unsigned>;
193
+ using LoopCacheCostTy = std::pair<const Loop *, CacheCostTy>;
194
+
195
+ public:
196
+ /// Construct a CacheCost object for the loop nest described by \p Loops.
197
+ /// The optional parameter \p TRT can be used to specify the max. distance
198
+ /// between array elements accessed in a loop so that the elements are
199
+ /// classified to have temporal reuse.
200
+ CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE,
201
+ TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI,
202
+ std::optional<unsigned> TRT = std::nullopt);
203
+
204
+ /// Create a CacheCost for the loop nest rooted by \p Root.
205
+ /// The optional parameter \p TRT can be used to specify the max. distance
206
+ /// between array elements accessed in a loop so that the elements are
207
+ /// classified to have temporal reuse.
208
+ static std::unique_ptr<CacheCost>
209
+ getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI,
210
+ std::optional<unsigned> TRT = std::nullopt);
211
+
212
+ /// Return the estimated cost of loop \p L if the given loop is part of the
213
+ /// loop nest associated with this object. Return -1 otherwise.
214
+ CacheCostTy getLoopCost(const Loop &L) const {
215
+ auto IT = llvm::find_if(LoopCosts, [&L](const LoopCacheCostTy &LCC) {
216
+ return LCC.first == &L;
217
+ });
218
+ return (IT != LoopCosts.end()) ? (*IT).second : -1;
219
+ }
220
+
221
+ /// Return the estimated ordered loop costs.
222
+ ArrayRef<LoopCacheCostTy> getLoopCosts() const { return LoopCosts; }
223
+
224
+ private:
225
+ /// Calculate the cache footprint of each loop in the nest (when it is
226
+ /// considered to be in the innermost position).
227
+ void calculateCacheFootprint();
228
+
229
+ /// Partition store/load instructions in the loop nest into reference groups.
230
+ /// Two or more memory accesses belong in the same reference group if they
231
+ /// share the same cache line.
232
+ bool populateReferenceGroups(ReferenceGroupsTy &RefGroups) const;
233
+
234
+ /// Calculate the cost of the given loop \p L assuming it is the innermost
235
+ /// loop in nest.
236
+ CacheCostTy computeLoopCacheCost(const Loop &L,
237
+ const ReferenceGroupsTy &RefGroups) const;
238
+
239
+ /// Compute the cost of a representative reference in reference group \p RG
240
+ /// when the given loop \p L is considered as the innermost loop in the nest.
241
+ /// The computed cost is an estimate for the number of cache lines used by the
242
+ /// reference group. The representative reference cost is defined as:
243
+ /// - equal to one if the reference is loop invariant, or
244
+ /// - equal to '(TripCount * stride) / cache_line_size' if (a) loop \p L's
245
+ /// induction variable is used only in the reference subscript associated
246
+ /// with loop \p L, and (b) the reference stride is less than the cache
247
+ /// line size, or
248
+ /// - TripCount otherwise
249
+ CacheCostTy computeRefGroupCacheCost(const ReferenceGroupTy &RG,
250
+ const Loop &L) const;
251
+
252
+ /// Sort the LoopCosts vector by decreasing cache cost.
253
+ void sortLoopCosts() {
254
+ stable_sort(LoopCosts,
255
+ [](const LoopCacheCostTy &A, const LoopCacheCostTy &B) {
256
+ return A.second > B.second;
257
+ });
258
+ }
259
+
260
+ private:
261
+ /// Loops in the loop nest associated with this object.
262
+ LoopVectorTy Loops;
263
+
264
+ /// Trip counts for the loops in the loop nest associated with this object.
265
+ SmallVector<LoopTripCountTy, 3> TripCounts;
266
+
267
+ /// Cache costs for the loops in the loop nest associated with this object.
268
+ SmallVector<LoopCacheCostTy, 3> LoopCosts;
269
+
270
+ /// The max. distance between array elements accessed in a loop so that the
271
+ /// elements are classified to have temporal reuse.
272
+ std::optional<unsigned> TRT;
273
+
274
+ const LoopInfo &LI;
275
+ ScalarEvolution &SE;
276
+ TargetTransformInfo &TTI;
277
+ AAResults &AA;
278
+ DependenceInfo &DI;
279
+ };
280
+
281
+ raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
282
+ raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
283
+
284
+ /// Printer pass for the \c CacheCost results.
285
+ class LoopCachePrinterPass : public PassInfoMixin<LoopCachePrinterPass> {
286
+ raw_ostream &OS;
287
+
288
+ public:
289
+ explicit LoopCachePrinterPass(raw_ostream &OS) : OS(OS) {}
290
+
291
+ PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
292
+ LoopStandardAnalysisResults &AR, LPMUpdater &U);
293
+
294
+ static bool isRequired() { return true; }
295
+ };
296
+
297
+ } // namespace llvm
298
+
299
+ #endif // LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/MemDerefPrinter.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- MemDerefPrinter.h - Printer for isDereferenceablePointer -----------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ #ifndef LLVM_ANALYSIS_MEMDEREFPRINTER_H
10
+ #define LLVM_ANALYSIS_MEMDEREFPRINTER_H
11
+
12
+ #include "llvm/IR/PassManager.h"
13
+
14
+ namespace llvm {
15
+ class MemDerefPrinterPass : public PassInfoMixin<MemDerefPrinterPass> {
16
+ raw_ostream &OS;
17
+
18
+ public:
19
+ MemDerefPrinterPass(raw_ostream &OS) : OS(OS) {}
20
+ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
21
+ static bool isRequired() { return true; }
22
+ };
23
+ } // namespace llvm
24
+
25
+ #endif // LLVM_ANALYSIS_MEMDEREFPRINTER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/MemoryDependenceAnalysis.h ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps ---*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the MemoryDependenceAnalysis analysis pass.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
14
+ #define LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
15
+
16
+ #include "llvm/ADT/DenseMap.h"
17
+ #include "llvm/ADT/PointerEmbeddedInt.h"
18
+ #include "llvm/ADT/PointerIntPair.h"
19
+ #include "llvm/ADT/PointerSumType.h"
20
+ #include "llvm/ADT/SmallPtrSet.h"
21
+ #include "llvm/Analysis/AliasAnalysis.h"
22
+ #include "llvm/Analysis/MemoryLocation.h"
23
+ #include "llvm/IR/PassManager.h"
24
+ #include "llvm/IR/PredIteratorCache.h"
25
+ #include "llvm/IR/ValueHandle.h"
26
+ #include "llvm/Pass.h"
27
+ #include <optional>
28
+
29
+ namespace llvm {
30
+
31
+ class AssumptionCache;
32
+ class DominatorTree;
33
+ class PHITransAddr;
34
+
35
+ /// A memory dependence query can return one of three different answers.
36
+ class MemDepResult {
37
+ enum DepType {
38
+ /// Clients of MemDep never see this.
39
+ ///
40
+ /// Entries with this marker occur in a LocalDeps map or NonLocalDeps map
41
+ /// when the instruction they previously referenced was removed from
42
+ /// MemDep. In either case, the entry may include an instruction pointer.
43
+ /// If so, the pointer is an instruction in the block where scanning can
44
+ /// start from, saving some work.
45
+ ///
46
+ /// In a default-constructed MemDepResult object, the type will be Invalid
47
+ /// and the instruction pointer will be null.
48
+ Invalid = 0,
49
+
50
+ /// This is a dependence on the specified instruction which clobbers the
51
+ /// desired value. The pointer member of the MemDepResult pair holds the
52
+ /// instruction that clobbers the memory. For example, this occurs when we
53
+ /// see a may-aliased store to the memory location we care about.
54
+ ///
55
+ /// There are several cases that may be interesting here:
56
+ /// 1. Loads are clobbered by may-alias stores.
57
+ /// 2. Loads are considered clobbered by partially-aliased loads. The
58
+ /// client may choose to analyze deeper into these cases.
59
+ Clobber,
60
+
61
+ /// This is a dependence on the specified instruction which defines or
62
+ /// produces the desired memory location. The pointer member of the
63
+ /// MemDepResult pair holds the instruction that defines the memory.
64
+ ///
65
+ /// Cases of interest:
66
+ /// 1. This could be a load or store for dependence queries on
67
+ /// load/store. The value loaded or stored is the produced value.
68
+ /// Note that the pointer operand may be different than that of the
69
+ /// queried pointer due to must aliases and phi translation. Note
70
+ /// that the def may not be the same type as the query, the pointers
71
+ /// may just be must aliases.
72
+ /// 2. For loads and stores, this could be an allocation instruction. In
73
+ /// this case, the load is loading an undef value or a store is the
74
+ /// first store to (that part of) the allocation.
75
+ /// 3. Dependence queries on calls return Def only when they are readonly
76
+ /// calls or memory use intrinsics with identical callees and no
77
+ /// intervening clobbers. No validation is done that the operands to
78
+ /// the calls are the same.
79
+ /// 4. For loads and stores, this could be a select instruction that
80
+ /// defines pointer to this memory location. In this case, users can
81
+ /// find non-clobbered Defs for both select values that are reaching
82
+ // the desired memory location (there is still a guarantee that there
83
+ // are no clobbers between analyzed memory location and select).
84
+ Def,
85
+
86
+ /// This marker indicates that the query has no known dependency in the
87
+ /// specified block.
88
+ ///
89
+ /// More detailed state info is encoded in the upper part of the pair (i.e.
90
+ /// the Instruction*)
91
+ Other
92
+ };
93
+
94
+ /// If DepType is "Other", the upper part of the sum type is an encoding of
95
+ /// the following more detailed type information.
96
+ enum OtherType {
97
+ /// This marker indicates that the query has no dependency in the specified
98
+ /// block.
99
+ ///
100
+ /// To find out more, the client should query other predecessor blocks.
101
+ NonLocal = 1,
102
+ /// This marker indicates that the query has no dependency in the specified
103
+ /// function.
104
+ NonFuncLocal,
105
+ /// This marker indicates that the query dependency is unknown.
106
+ Unknown
107
+ };
108
+
109
+ using ValueTy = PointerSumType<
110
+ DepType, PointerSumTypeMember<Invalid, Instruction *>,
111
+ PointerSumTypeMember<Clobber, Instruction *>,
112
+ PointerSumTypeMember<Def, Instruction *>,
113
+ PointerSumTypeMember<Other, PointerEmbeddedInt<OtherType, 3>>>;
114
+ ValueTy Value;
115
+
116
+ explicit MemDepResult(ValueTy V) : Value(V) {}
117
+
118
+ public:
119
+ MemDepResult() = default;
120
+
121
+ /// get methods: These are static ctor methods for creating various
122
+ /// MemDepResult kinds.
123
+ static MemDepResult getDef(Instruction *Inst) {
124
+ assert(Inst && "Def requires inst");
125
+ return MemDepResult(ValueTy::create<Def>(Inst));
126
+ }
127
+ static MemDepResult getClobber(Instruction *Inst) {
128
+ assert(Inst && "Clobber requires inst");
129
+ return MemDepResult(ValueTy::create<Clobber>(Inst));
130
+ }
131
+ static MemDepResult getNonLocal() {
132
+ return MemDepResult(ValueTy::create<Other>(NonLocal));
133
+ }
134
+ static MemDepResult getNonFuncLocal() {
135
+ return MemDepResult(ValueTy::create<Other>(NonFuncLocal));
136
+ }
137
+ static MemDepResult getUnknown() {
138
+ return MemDepResult(ValueTy::create<Other>(Unknown));
139
+ }
140
+
141
+ /// Tests if this MemDepResult represents a query that is an instruction
142
+ /// clobber dependency.
143
+ bool isClobber() const { return Value.is<Clobber>(); }
144
+
145
+ /// Tests if this MemDepResult represents a query that is an instruction
146
+ /// definition dependency.
147
+ bool isDef() const { return Value.is<Def>(); }
148
+
149
+ /// Tests if this MemDepResult represents a valid local query (Clobber/Def).
150
+ bool isLocal() const { return isClobber() || isDef(); }
151
+
152
+ /// Tests if this MemDepResult represents a query that is transparent to the
153
+ /// start of the block, but where a non-local hasn't been done.
154
+ bool isNonLocal() const {
155
+ return Value.is<Other>() && Value.cast<Other>() == NonLocal;
156
+ }
157
+
158
+ /// Tests if this MemDepResult represents a query that is transparent to the
159
+ /// start of the function.
160
+ bool isNonFuncLocal() const {
161
+ return Value.is<Other>() && Value.cast<Other>() == NonFuncLocal;
162
+ }
163
+
164
+ /// Tests if this MemDepResult represents a query which cannot and/or will
165
+ /// not be computed.
166
+ bool isUnknown() const {
167
+ return Value.is<Other>() && Value.cast<Other>() == Unknown;
168
+ }
169
+
170
+ /// If this is a normal dependency, returns the instruction that is depended
171
+ /// on. Otherwise, returns null.
172
+ Instruction *getInst() const {
173
+ switch (Value.getTag()) {
174
+ case Invalid:
175
+ return Value.cast<Invalid>();
176
+ case Clobber:
177
+ return Value.cast<Clobber>();
178
+ case Def:
179
+ return Value.cast<Def>();
180
+ case Other:
181
+ return nullptr;
182
+ }
183
+ llvm_unreachable("Unknown discriminant!");
184
+ }
185
+
186
+ bool operator==(const MemDepResult &M) const { return Value == M.Value; }
187
+ bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
188
+ bool operator<(const MemDepResult &M) const { return Value < M.Value; }
189
+ bool operator>(const MemDepResult &M) const { return Value > M.Value; }
190
+
191
+ private:
192
+ friend class MemoryDependenceResults;
193
+
194
+ /// Tests if this is a MemDepResult in its dirty/invalid. state.
195
+ bool isDirty() const { return Value.is<Invalid>(); }
196
+
197
+ static MemDepResult getDirty(Instruction *Inst) {
198
+ return MemDepResult(ValueTy::create<Invalid>(Inst));
199
+ }
200
+ };
201
+
202
+ /// This is an entry in the NonLocalDepInfo cache.
203
+ ///
204
+ /// For each BasicBlock (the BB entry) it keeps a MemDepResult.
205
+ class NonLocalDepEntry {
206
+ BasicBlock *BB;
207
+ MemDepResult Result;
208
+
209
+ public:
210
+ NonLocalDepEntry(BasicBlock *BB, MemDepResult Result)
211
+ : BB(BB), Result(Result) {}
212
+
213
+ // This is used for searches.
214
+ NonLocalDepEntry(BasicBlock *BB) : BB(BB) {}
215
+
216
+ // BB is the sort key, it can't be changed.
217
+ BasicBlock *getBB() const { return BB; }
218
+
219
+ void setResult(const MemDepResult &R) { Result = R; }
220
+
221
+ const MemDepResult &getResult() const { return Result; }
222
+
223
+ bool operator<(const NonLocalDepEntry &RHS) const { return BB < RHS.BB; }
224
+ };
225
+
226
+ /// This is a result from a NonLocal dependence query.
227
+ ///
228
+ /// For each BasicBlock (the BB entry) it keeps a MemDepResult and the
229
+ /// (potentially phi translated) address that was live in the block.
230
+ class NonLocalDepResult {
231
+ NonLocalDepEntry Entry;
232
+ Value *Address;
233
+
234
+ public:
235
+ NonLocalDepResult(BasicBlock *BB, MemDepResult Result, Value *Address)
236
+ : Entry(BB, Result), Address(Address) {}
237
+
238
+ // BB is the sort key, it can't be changed.
239
+ BasicBlock *getBB() const { return Entry.getBB(); }
240
+
241
+ void setResult(const MemDepResult &R, Value *Addr) {
242
+ Entry.setResult(R);
243
+ Address = Addr;
244
+ }
245
+
246
+ const MemDepResult &getResult() const { return Entry.getResult(); }
247
+
248
+ /// Returns the address of this pointer in this block.
249
+ ///
250
+ /// This can be different than the address queried for the non-local result
251
+ /// because of phi translation. This returns null if the address was not
252
+ /// available in a block (i.e. because phi translation failed) or if this is
253
+ /// a cached result and that address was deleted.
254
+ ///
255
+ /// The address is always null for a non-local 'call' dependence.
256
+ Value *getAddress() const { return Address; }
257
+ };
258
+
259
+ /// Provides a lazy, caching interface for making common memory aliasing
260
+ /// information queries, backed by LLVM's alias analysis passes.
261
+ ///
262
+ /// The dependency information returned is somewhat unusual, but is pragmatic.
263
+ /// If queried about a store or call that might modify memory, the analysis
264
+ /// will return the instruction[s] that may either load from that memory or
265
+ /// store to it. If queried with a load or call that can never modify memory,
266
+ /// the analysis will return calls and stores that might modify the pointer,
267
+ /// but generally does not return loads unless a) they are volatile, or
268
+ /// b) they load from *must-aliased* pointers. Returning a dependence on
269
+ /// must-alias'd pointers instead of all pointers interacts well with the
270
+ /// internal caching mechanism.
271
+ class MemoryDependenceResults {
272
+ // A map from instructions to their dependency.
273
+ using LocalDepMapType = DenseMap<Instruction *, MemDepResult>;
274
+ LocalDepMapType LocalDeps;
275
+
276
+ public:
277
+ using NonLocalDepInfo = std::vector<NonLocalDepEntry>;
278
+
279
+ private:
280
+ /// A pair<Value*, bool> where the bool is true if the dependence is a read
281
+ /// only dependence, false if read/write.
282
+ using ValueIsLoadPair = PointerIntPair<const Value *, 1, bool>;
283
+
284
+ /// This pair is used when caching information for a block.
285
+ ///
286
+ /// If the pointer is null, the cache value is not a full query that starts
287
+ /// at the specified block. If non-null, the bool indicates whether or not
288
+ /// the contents of the block was skipped.
289
+ using BBSkipFirstBlockPair = PointerIntPair<BasicBlock *, 1, bool>;
290
+
291
+ /// This record is the information kept for each (value, is load) pair.
292
+ struct NonLocalPointerInfo {
293
+ /// The pair of the block and the skip-first-block flag.
294
+ BBSkipFirstBlockPair Pair;
295
+ /// The results of the query for each relevant block.
296
+ NonLocalDepInfo NonLocalDeps;
297
+ /// The maximum size of the dereferences of the pointer.
298
+ ///
299
+ /// May be UnknownSize if the sizes are unknown.
300
+ LocationSize Size = LocationSize::afterPointer();
301
+ /// The AA tags associated with dereferences of the pointer.
302
+ ///
303
+ /// The members may be null if there are no tags or conflicting tags.
304
+ AAMDNodes AATags;
305
+
306
+ NonLocalPointerInfo() = default;
307
+ };
308
+
309
+ /// Cache storing single nonlocal def for the instruction.
310
+ /// It is set when nonlocal def would be found in function returning only
311
+ /// local dependencies.
312
+ DenseMap<AssertingVH<const Value>, NonLocalDepResult> NonLocalDefsCache;
313
+ using ReverseNonLocalDefsCacheTy =
314
+ DenseMap<Instruction *, SmallPtrSet<const Value*, 4>>;
315
+ ReverseNonLocalDefsCacheTy ReverseNonLocalDefsCache;
316
+
317
+ /// This map stores the cached results of doing a pointer lookup at the
318
+ /// bottom of a block.
319
+ ///
320
+ /// The key of this map is the pointer+isload bit, the value is a list of
321
+ /// <bb->result> mappings.
322
+ using CachedNonLocalPointerInfo =
323
+ DenseMap<ValueIsLoadPair, NonLocalPointerInfo>;
324
+ CachedNonLocalPointerInfo NonLocalPointerDeps;
325
+
326
+ // A map from instructions to their non-local pointer dependencies.
327
+ using ReverseNonLocalPtrDepTy =
328
+ DenseMap<Instruction *, SmallPtrSet<ValueIsLoadPair, 4>>;
329
+ ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
330
+
331
+ /// This is the instruction we keep for each cached access that we have for
332
+ /// an instruction.
333
+ ///
334
+ /// The pointer is an owning pointer and the bool indicates whether we have
335
+ /// any dirty bits in the set.
336
+ using PerInstNLInfo = std::pair<NonLocalDepInfo, bool>;
337
+
338
+ // A map from instructions to their non-local dependencies.
339
+ using NonLocalDepMapType = DenseMap<Instruction *, PerInstNLInfo>;
340
+
341
+ NonLocalDepMapType NonLocalDepsMap;
342
+
343
+ // A reverse mapping from dependencies to the dependees. This is
344
+ // used when removing instructions to keep the cache coherent.
345
+ using ReverseDepMapType =
346
+ DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>>;
347
+ ReverseDepMapType ReverseLocalDeps;
348
+
349
+ // A reverse mapping from dependencies to the non-local dependees.
350
+ ReverseDepMapType ReverseNonLocalDeps;
351
+
352
+ /// Current AA implementation, just a cache.
353
+ AAResults &AA;
354
+ AssumptionCache &AC;
355
+ const TargetLibraryInfo &TLI;
356
+ DominatorTree &DT;
357
+ PredIteratorCache PredCache;
358
+ EarliestEscapeAnalysis EEA;
359
+
360
+ unsigned DefaultBlockScanLimit;
361
+
362
+ /// Offsets to dependant clobber loads.
363
+ using ClobberOffsetsMapType = DenseMap<LoadInst *, int32_t>;
364
+ ClobberOffsetsMapType ClobberOffsets;
365
+
366
+ public:
367
+ MemoryDependenceResults(AAResults &AA, AssumptionCache &AC,
368
+ const TargetLibraryInfo &TLI, DominatorTree &DT,
369
+ unsigned DefaultBlockScanLimit)
370
+ : AA(AA), AC(AC), TLI(TLI), DT(DT), EEA(DT),
371
+ DefaultBlockScanLimit(DefaultBlockScanLimit) {}
372
+
373
+ /// Handle invalidation in the new PM.
374
+ bool invalidate(Function &F, const PreservedAnalyses &PA,
375
+ FunctionAnalysisManager::Invalidator &Inv);
376
+
377
+ /// Some methods limit the number of instructions they will examine.
378
+ /// The return value of this method is the default limit that will be
379
+ /// used if no limit is explicitly passed in.
380
+ unsigned getDefaultBlockScanLimit() const;
381
+
382
+ /// Returns the instruction on which a memory operation depends.
383
+ ///
384
+ /// See the class comment for more details. It is illegal to call this on
385
+ /// non-memory instructions.
386
+ MemDepResult getDependency(Instruction *QueryInst);
387
+
388
+ /// Perform a full dependency query for the specified call, returning the set
389
+ /// of blocks that the value is potentially live across.
390
+ ///
391
+ /// The returned set of results will include a "NonLocal" result for all
392
+ /// blocks where the value is live across.
393
+ ///
394
+ /// This method assumes the instruction returns a "NonLocal" dependency
395
+ /// within its own block.
396
+ ///
397
+ /// This returns a reference to an internal data structure that may be
398
+ /// invalidated on the next non-local query or when an instruction is
399
+ /// removed. Clients must copy this data if they want it around longer than
400
+ /// that.
401
+ const NonLocalDepInfo &getNonLocalCallDependency(CallBase *QueryCall);
402
+
403
+ /// Perform a full dependency query for an access to the QueryInst's
404
+ /// specified memory location, returning the set of instructions that either
405
+ /// define or clobber the value.
406
+ ///
407
+ /// Warning: For a volatile query instruction, the dependencies will be
408
+ /// accurate, and thus usable for reordering, but it is never legal to
409
+ /// remove the query instruction.
410
+ ///
411
+ /// This method assumes the pointer has a "NonLocal" dependency within
412
+ /// QueryInst's parent basic block.
413
+ void getNonLocalPointerDependency(Instruction *QueryInst,
414
+ SmallVectorImpl<NonLocalDepResult> &Result);
415
+
416
+ /// Removes an instruction from the dependence analysis, updating the
417
+ /// dependence of instructions that previously depended on it.
418
+ void removeInstruction(Instruction *InstToRemove);
419
+
420
+ /// Invalidates cached information about the specified pointer, because it
421
+ /// may be too conservative in memdep.
422
+ ///
423
+ /// This is an optional call that can be used when the client detects an
424
+ /// equivalence between the pointer and some other value and replaces the
425
+ /// other value with ptr. This can make Ptr available in more places that
426
+ /// cached info does not necessarily keep.
427
+ void invalidateCachedPointerInfo(Value *Ptr);
428
+
429
+ /// Clears the PredIteratorCache info.
430
+ ///
431
+ /// This needs to be done when the CFG changes, e.g., due to splitting
432
+ /// critical edges.
433
+ void invalidateCachedPredecessors();
434
+
435
+ /// Returns the instruction on which a memory location depends.
436
+ ///
437
+ /// If isLoad is true, this routine ignores may-aliases with read-only
438
+ /// operations. If isLoad is false, this routine ignores may-aliases
439
+ /// with reads from read-only locations. If possible, pass the query
440
+ /// instruction as well; this function may take advantage of the metadata
441
+ /// annotated to the query instruction to refine the result. \p Limit
442
+ /// can be used to set the maximum number of instructions that will be
443
+ /// examined to find the pointer dependency. On return, it will be set to
444
+ /// the number of instructions left to examine. If a null pointer is passed
445
+ /// in, the limit will default to the value of -memdep-block-scan-limit.
446
+ ///
447
+ /// Note that this is an uncached query, and thus may be inefficient.
448
+ MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc, bool isLoad,
449
+ BasicBlock::iterator ScanIt,
450
+ BasicBlock *BB,
451
+ Instruction *QueryInst = nullptr,
452
+ unsigned *Limit = nullptr);
453
+
454
+ MemDepResult getPointerDependencyFrom(const MemoryLocation &Loc, bool isLoad,
455
+ BasicBlock::iterator ScanIt,
456
+ BasicBlock *BB,
457
+ Instruction *QueryInst,
458
+ unsigned *Limit,
459
+ BatchAAResults &BatchAA);
460
+
461
+ MemDepResult
462
+ getSimplePointerDependencyFrom(const MemoryLocation &MemLoc, bool isLoad,
463
+ BasicBlock::iterator ScanIt, BasicBlock *BB,
464
+ Instruction *QueryInst, unsigned *Limit,
465
+ BatchAAResults &BatchAA);
466
+
467
+ /// This analysis looks for other loads and stores with invariant.group
468
+ /// metadata and the same pointer operand. Returns Unknown if it does not
469
+ /// find anything, and Def if it can be assumed that 2 instructions load or
470
+ /// store the same value and NonLocal which indicate that non-local Def was
471
+ /// found, which can be retrieved by calling getNonLocalPointerDependency
472
+ /// with the same queried instruction.
473
+ MemDepResult getInvariantGroupPointerDependency(LoadInst *LI, BasicBlock *BB);
474
+
475
+ /// Release memory in caches.
476
+ void releaseMemory();
477
+
478
+ /// Return the clobber offset to dependent instruction.
479
+ std::optional<int32_t> getClobberOffset(LoadInst *DepInst) const {
480
+ const auto Off = ClobberOffsets.find(DepInst);
481
+ if (Off != ClobberOffsets.end())
482
+ return Off->getSecond();
483
+ return std::nullopt;
484
+ }
485
+
486
+ private:
487
+ MemDepResult getCallDependencyFrom(CallBase *Call, bool isReadOnlyCall,
488
+ BasicBlock::iterator ScanIt,
489
+ BasicBlock *BB);
490
+ bool getNonLocalPointerDepFromBB(Instruction *QueryInst,
491
+ const PHITransAddr &Pointer,
492
+ const MemoryLocation &Loc, bool isLoad,
493
+ BasicBlock *BB,
494
+ SmallVectorImpl<NonLocalDepResult> &Result,
495
+ SmallDenseMap<BasicBlock *, Value *, 16> &Visited,
496
+ bool SkipFirstBlock = false,
497
+ bool IsIncomplete = false);
498
+ MemDepResult getNonLocalInfoForBlock(Instruction *QueryInst,
499
+ const MemoryLocation &Loc, bool isLoad,
500
+ BasicBlock *BB, NonLocalDepInfo *Cache,
501
+ unsigned NumSortedEntries,
502
+ BatchAAResults &BatchAA);
503
+
504
+ void removeCachedNonLocalPointerDependencies(ValueIsLoadPair P);
505
+
506
+ void verifyRemoved(Instruction *Inst) const;
507
+ };
508
+
509
+ /// An analysis that produces \c MemoryDependenceResults for a function.
510
+ ///
511
+ /// This is essentially a no-op because the results are computed entirely
512
+ /// lazily.
513
+ class MemoryDependenceAnalysis
514
+ : public AnalysisInfoMixin<MemoryDependenceAnalysis> {
515
+ friend AnalysisInfoMixin<MemoryDependenceAnalysis>;
516
+
517
+ static AnalysisKey Key;
518
+
519
+ unsigned DefaultBlockScanLimit;
520
+
521
+ public:
522
+ using Result = MemoryDependenceResults;
523
+
524
+ MemoryDependenceAnalysis();
525
+ MemoryDependenceAnalysis(unsigned DefaultBlockScanLimit) : DefaultBlockScanLimit(DefaultBlockScanLimit) { }
526
+
527
+ MemoryDependenceResults run(Function &F, FunctionAnalysisManager &AM);
528
+ };
529
+
530
+ /// A wrapper analysis pass for the legacy pass manager that exposes a \c
531
+ /// MemoryDepnedenceResults instance.
532
+ class MemoryDependenceWrapperPass : public FunctionPass {
533
+ std::optional<MemoryDependenceResults> MemDep;
534
+
535
+ public:
536
+ static char ID;
537
+
538
+ MemoryDependenceWrapperPass();
539
+ ~MemoryDependenceWrapperPass() override;
540
+
541
+ /// Pass Implementation stuff. This doesn't do any analysis eagerly.
542
+ bool runOnFunction(Function &) override;
543
+
544
+ /// Clean up memory in between runs
545
+ void releaseMemory() override;
546
+
547
+ /// Does not modify anything. It uses Value Numbering and Alias Analysis.
548
+ void getAnalysisUsage(AnalysisUsage &AU) const override;
549
+
550
+ MemoryDependenceResults &getMemDep() { return *MemDep; }
551
+ };
552
+
553
+ } // end namespace llvm
554
+
555
+ #endif // LLVM_ANALYSIS_MEMORYDEPENDENCEANALYSIS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/ModuleDebugInfoPrinter.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- ModuleDebugInfoPrinter.h - -----------------------------------------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ #ifndef LLVM_ANALYSIS_MODULEDEBUGINFOPRINTER_H
10
+ #define LLVM_ANALYSIS_MODULEDEBUGINFOPRINTER_H
11
+
12
+ #include "llvm/IR/DebugInfo.h"
13
+ #include "llvm/IR/PassManager.h"
14
+
15
+ namespace llvm {
16
+ class raw_ostream;
17
+
18
+ class ModuleDebugInfoPrinterPass
19
+ : public PassInfoMixin<ModuleDebugInfoPrinterPass> {
20
+ DebugInfoFinder Finder;
21
+ raw_ostream &OS;
22
+
23
+ public:
24
+ explicit ModuleDebugInfoPrinterPass(raw_ostream &OS);
25
+ PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
26
+ static bool isRequired() { return true; }
27
+ };
28
+ } // end namespace llvm
29
+
30
+ #endif // LLVM_ANALYSIS_MODULEDEBUGINFOPRINTER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/NoInferenceModelRunner.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- NoInferenceModelRunner.h ---- noop ML model runner ------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+
10
+ #ifndef LLVM_ANALYSIS_NOINFERENCEMODELRUNNER_H
11
+ #define LLVM_ANALYSIS_NOINFERENCEMODELRUNNER_H
12
+
13
+ #include "llvm/Analysis/MLModelRunner.h"
14
+ #include "llvm/Support/Compiler.h"
15
+ namespace llvm {
16
+ class TensorSpec;
17
+
18
+ /// A pseudo model runner. We use it to store feature values when collecting
19
+ /// logs for the default policy, in 'development' mode, but never ask it to
20
+ /// 'run'.
21
+ class NoInferenceModelRunner : public MLModelRunner {
22
+ public:
23
+ LLVM_ABI NoInferenceModelRunner(LLVMContext &Ctx,
24
+ const std::vector<TensorSpec> &Inputs);
25
+
26
+ static bool classof(const MLModelRunner *R) {
27
+ return R->getKind() == MLModelRunner::Kind::NoOp;
28
+ }
29
+
30
+ private:
31
+ void *evaluateUntyped() override {
32
+ llvm_unreachable("We shouldn't call run on this model runner.");
33
+ }
34
+ };
35
+ } // namespace llvm
36
+ #endif // LLVM_ANALYSIS_NOINFERENCEMODELRUNNER_H
deps/exla/cache/xla_extension/include/llvm/Analysis/ObjCARCAliasAnalysis.h ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- ObjCARCAliasAnalysis.h - ObjC ARC Alias Analysis ---------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ /// This file declares a simple ARC-aware AliasAnalysis using special knowledge
10
+ /// of Objective C to enhance other optimization passes which rely on the Alias
11
+ /// Analysis infrastructure.
12
+ ///
13
+ /// WARNING: This file knows about certain library functions. It recognizes them
14
+ /// by name, and hardwires knowledge of their semantics.
15
+ ///
16
+ /// WARNING: This file knows about how certain Objective-C library functions are
17
+ /// used. Naive LLVM IR transformations which would otherwise be
18
+ /// behavior-preserving may break these assumptions.
19
+ ///
20
+ //===----------------------------------------------------------------------===//
21
+
22
+ #ifndef LLVM_ANALYSIS_OBJCARCALIASANALYSIS_H
23
+ #define LLVM_ANALYSIS_OBJCARCALIASANALYSIS_H
24
+
25
+ #include "llvm/Analysis/AliasAnalysis.h"
26
+
27
+ namespace llvm {
28
+ namespace objcarc {
29
+
30
+ /// This is a simple alias analysis implementation that uses knowledge
31
+ /// of ARC constructs to answer queries.
32
+ ///
33
+ /// TODO: This class could be generalized to know about other ObjC-specific
34
+ /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
35
+ /// even though their offsets are dynamic.
36
+ class ObjCARCAAResult : public AAResultBase {
37
+ const DataLayout &DL;
38
+
39
+ public:
40
+ explicit ObjCARCAAResult(const DataLayout &DL) : DL(DL) {}
41
+ ObjCARCAAResult(ObjCARCAAResult &&Arg)
42
+ : AAResultBase(std::move(Arg)), DL(Arg.DL) {}
43
+
44
+ /// Handle invalidation events from the new pass manager.
45
+ ///
46
+ /// By definition, this result is stateless and so remains valid.
47
+ bool invalidate(Function &, const PreservedAnalyses &,
48
+ FunctionAnalysisManager::Invalidator &) {
49
+ return false;
50
+ }
51
+
52
+ AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
53
+ AAQueryInfo &AAQI, const Instruction *CtxI);
54
+ ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI,
55
+ bool IgnoreLocals);
56
+
57
+ using AAResultBase::getMemoryEffects;
58
+ MemoryEffects getMemoryEffects(const Function *F);
59
+
60
+ using AAResultBase::getModRefInfo;
61
+ ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
62
+ AAQueryInfo &AAQI);
63
+ };
64
+
65
+ /// Analysis pass providing a never-invalidated alias analysis result.
66
+ class ObjCARCAA : public AnalysisInfoMixin<ObjCARCAA> {
67
+ friend AnalysisInfoMixin<ObjCARCAA>;
68
+ static AnalysisKey Key;
69
+
70
+ public:
71
+ typedef ObjCARCAAResult Result;
72
+
73
+ ObjCARCAAResult run(Function &F, FunctionAnalysisManager &AM);
74
+ };
75
+
76
+ } // namespace objcarc
77
+ } // namespace llvm
78
+
79
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/ObjCARCAnalysisUtils.h ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- ObjCARCAnalysisUtils.h - ObjC ARC Analysis Utilities -----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ /// \file
9
+ /// This file defines common analysis utilities used by the ObjC ARC Optimizer.
10
+ /// ARC stands for Automatic Reference Counting and is a system for managing
11
+ /// reference counts for objects in Objective C.
12
+ ///
13
+ /// WARNING: This file knows about certain library functions. It recognizes them
14
+ /// by name, and hardwires knowledge of their semantics.
15
+ ///
16
+ /// WARNING: This file knows about how certain Objective-C library functions are
17
+ /// used. Naive LLVM IR transformations which would otherwise be
18
+ /// behavior-preserving may break these assumptions.
19
+ ///
20
+ //===----------------------------------------------------------------------===//
21
+
22
+ #ifndef LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
23
+ #define LLVM_ANALYSIS_OBJCARCANALYSISUTILS_H
24
+
25
+ #include "llvm/Analysis/ObjCARCInstKind.h"
26
+ #include "llvm/Analysis/ValueTracking.h"
27
+ #include "llvm/IR/Constants.h"
28
+ #include "llvm/IR/Module.h"
29
+ #include "llvm/IR/ValueHandle.h"
30
+ #include <optional>
31
+
32
+ namespace llvm {
33
+
34
+ class AAResults;
35
+
36
+ namespace objcarc {
37
+
38
+ /// A handy option to enable/disable all ARC Optimizations.
39
+ extern bool EnableARCOpts;
40
+
41
+ /// Test if the given module looks interesting to run ARC optimization
42
+ /// on.
43
+ inline bool ModuleHasARC(const Module &M) {
44
+ return M.getNamedValue("llvm.objc.retain") ||
45
+ M.getNamedValue("llvm.objc.release") ||
46
+ M.getNamedValue("llvm.objc.autorelease") ||
47
+ M.getNamedValue("llvm.objc.retainAutoreleasedReturnValue") ||
48
+ M.getNamedValue("llvm.objc.unsafeClaimAutoreleasedReturnValue") ||
49
+ M.getNamedValue("llvm.objc.retainBlock") ||
50
+ M.getNamedValue("llvm.objc.autoreleaseReturnValue") ||
51
+ M.getNamedValue("llvm.objc.autoreleasePoolPush") ||
52
+ M.getNamedValue("llvm.objc.loadWeakRetained") ||
53
+ M.getNamedValue("llvm.objc.loadWeak") ||
54
+ M.getNamedValue("llvm.objc.destroyWeak") ||
55
+ M.getNamedValue("llvm.objc.storeWeak") ||
56
+ M.getNamedValue("llvm.objc.initWeak") ||
57
+ M.getNamedValue("llvm.objc.moveWeak") ||
58
+ M.getNamedValue("llvm.objc.copyWeak") ||
59
+ M.getNamedValue("llvm.objc.retainedObject") ||
60
+ M.getNamedValue("llvm.objc.unretainedObject") ||
61
+ M.getNamedValue("llvm.objc.unretainedPointer") ||
62
+ M.getNamedValue("llvm.objc.clang.arc.noop.use") ||
63
+ M.getNamedValue("llvm.objc.clang.arc.use");
64
+ }
65
+
66
+ /// This is a wrapper around getUnderlyingObject which also knows how to
67
+ /// look through objc_retain and objc_autorelease calls, which we know to return
68
+ /// their argument verbatim.
69
+ inline const Value *GetUnderlyingObjCPtr(const Value *V) {
70
+ for (;;) {
71
+ V = getUnderlyingObject(V);
72
+ if (!IsForwarding(GetBasicARCInstKind(V)))
73
+ break;
74
+ V = cast<CallInst>(V)->getArgOperand(0);
75
+ }
76
+
77
+ return V;
78
+ }
79
+
80
+ /// A wrapper for GetUnderlyingObjCPtr used for results memoization.
81
+ inline const Value *GetUnderlyingObjCPtrCached(
82
+ const Value *V,
83
+ DenseMap<const Value *, std::pair<WeakVH, WeakTrackingVH>> &Cache) {
84
+ // The entry is invalid if either value handle is null.
85
+ auto InCache = Cache.lookup(V);
86
+ if (InCache.first && InCache.second)
87
+ return InCache.second;
88
+
89
+ const Value *Computed = GetUnderlyingObjCPtr(V);
90
+ Cache[V] =
91
+ std::make_pair(const_cast<Value *>(V), const_cast<Value *>(Computed));
92
+ return Computed;
93
+ }
94
+
95
+ /// The RCIdentity root of a value \p V is a dominating value U for which
96
+ /// retaining or releasing U is equivalent to retaining or releasing V. In other
97
+ /// words, ARC operations on \p V are equivalent to ARC operations on \p U.
98
+ ///
99
+ /// We use this in the ARC optimizer to make it easier to match up ARC
100
+ /// operations by always mapping ARC operations to RCIdentityRoots instead of
101
+ /// pointers themselves.
102
+ ///
103
+ /// The two ways that we see RCIdentical values in ObjC are via:
104
+ ///
105
+ /// 1. PointerCasts
106
+ /// 2. Forwarding Calls that return their argument verbatim.
107
+ ///
108
+ /// Thus this function strips off pointer casts and forwarding calls. *NOTE*
109
+ /// This implies that two RCIdentical values must alias.
110
+ inline const Value *GetRCIdentityRoot(const Value *V) {
111
+ for (;;) {
112
+ V = V->stripPointerCasts();
113
+ if (!IsForwarding(GetBasicARCInstKind(V)))
114
+ break;
115
+ V = cast<CallInst>(V)->getArgOperand(0);
116
+ }
117
+ return V;
118
+ }
119
+
120
+ /// Helper which calls const Value *GetRCIdentityRoot(const Value *V) and just
121
+ /// casts away the const of the result. For documentation about what an
122
+ /// RCIdentityRoot (and by extension GetRCIdentityRoot is) look at that
123
+ /// function.
124
+ inline Value *GetRCIdentityRoot(Value *V) {
125
+ return const_cast<Value *>(GetRCIdentityRoot((const Value *)V));
126
+ }
127
+
128
+ /// Assuming the given instruction is one of the special calls such as
129
+ /// objc_retain or objc_release, return the RCIdentity root of the argument of
130
+ /// the call.
131
+ inline Value *GetArgRCIdentityRoot(Value *Inst) {
132
+ return GetRCIdentityRoot(cast<CallInst>(Inst)->getArgOperand(0));
133
+ }
134
+
135
+ inline bool IsNullOrUndef(const Value *V) {
136
+ return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
137
+ }
138
+
139
+ inline bool IsNoopInstruction(const Instruction *I) {
140
+ return isa<BitCastInst>(I) ||
141
+ (isa<GetElementPtrInst>(I) &&
142
+ cast<GetElementPtrInst>(I)->hasAllZeroIndices());
143
+ }
144
+
145
+ /// Test whether the given value is possible a retainable object pointer.
146
+ inline bool IsPotentialRetainableObjPtr(const Value *Op) {
147
+ // Pointers to static or stack storage are not valid retainable object
148
+ // pointers.
149
+ if (isa<Constant>(Op) || isa<AllocaInst>(Op))
150
+ return false;
151
+ // Special arguments can not be a valid retainable object pointer.
152
+ if (const Argument *Arg = dyn_cast<Argument>(Op))
153
+ if (Arg->hasPassPointeeByValueCopyAttr() || Arg->hasNestAttr() ||
154
+ Arg->hasStructRetAttr())
155
+ return false;
156
+ // Only consider values with pointer types.
157
+ //
158
+ // It seemes intuitive to exclude function pointer types as well, since
159
+ // functions are never retainable object pointers, however clang occasionally
160
+ // bitcasts retainable object pointers to function-pointer type temporarily.
161
+ PointerType *Ty = dyn_cast<PointerType>(Op->getType());
162
+ if (!Ty)
163
+ return false;
164
+ // Conservatively assume anything else is a potential retainable object
165
+ // pointer.
166
+ return true;
167
+ }
168
+
169
+ bool IsPotentialRetainableObjPtr(const Value *Op, AAResults &AA);
170
+
171
+ /// Helper for GetARCInstKind. Determines what kind of construct CS
172
+ /// is.
173
+ inline ARCInstKind GetCallSiteClass(const CallBase &CB) {
174
+ for (const Use &U : CB.args())
175
+ if (IsPotentialRetainableObjPtr(U))
176
+ return CB.onlyReadsMemory() ? ARCInstKind::User : ARCInstKind::CallOrUser;
177
+
178
+ return CB.onlyReadsMemory() ? ARCInstKind::None : ARCInstKind::Call;
179
+ }
180
+
181
+ /// Return true if this value refers to a distinct and identifiable
182
+ /// object.
183
+ ///
184
+ /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
185
+ /// special knowledge of ObjC conventions.
186
+ inline bool IsObjCIdentifiedObject(const Value *V) {
187
+ // Assume that call results and arguments have their own "provenance".
188
+ // Constants (including GlobalVariables) and Allocas are never
189
+ // reference-counted.
190
+ if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
191
+ isa<Argument>(V) || isa<Constant>(V) ||
192
+ isa<AllocaInst>(V))
193
+ return true;
194
+
195
+ if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
196
+ const Value *Pointer =
197
+ GetRCIdentityRoot(LI->getPointerOperand());
198
+ if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
199
+ // A constant pointer can't be pointing to an object on the heap. It may
200
+ // be reference-counted, but it won't be deleted.
201
+ if (GV->isConstant())
202
+ return true;
203
+ StringRef Name = GV->getName();
204
+ // These special variables are known to hold values which are not
205
+ // reference-counted pointers.
206
+ if (Name.starts_with("\01l_objc_msgSend_fixup_"))
207
+ return true;
208
+
209
+ StringRef Section = GV->getSection();
210
+ if (Section.contains("__message_refs") ||
211
+ Section.contains("__objc_classrefs") ||
212
+ Section.contains("__objc_superrefs") ||
213
+ Section.contains("__objc_methname") || Section.contains("__cstring"))
214
+ return true;
215
+ }
216
+ }
217
+
218
+ return false;
219
+ }
220
+
221
+ enum class ARCMDKindID {
222
+ ImpreciseRelease,
223
+ CopyOnEscape,
224
+ NoObjCARCExceptions,
225
+ };
226
+
227
+ /// A cache of MDKinds used by various ARC optimizations.
228
+ class ARCMDKindCache {
229
+ Module *M;
230
+
231
+ /// The Metadata Kind for clang.imprecise_release metadata.
232
+ std::optional<unsigned> ImpreciseReleaseMDKind;
233
+
234
+ /// The Metadata Kind for clang.arc.copy_on_escape metadata.
235
+ std::optional<unsigned> CopyOnEscapeMDKind;
236
+
237
+ /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
238
+ std::optional<unsigned> NoObjCARCExceptionsMDKind;
239
+
240
+ public:
241
+ void init(Module *Mod) {
242
+ M = Mod;
243
+ ImpreciseReleaseMDKind = std::nullopt;
244
+ CopyOnEscapeMDKind = std::nullopt;
245
+ NoObjCARCExceptionsMDKind = std::nullopt;
246
+ }
247
+
248
+ unsigned get(ARCMDKindID ID) {
249
+ switch (ID) {
250
+ case ARCMDKindID::ImpreciseRelease:
251
+ if (!ImpreciseReleaseMDKind)
252
+ ImpreciseReleaseMDKind =
253
+ M->getContext().getMDKindID("clang.imprecise_release");
254
+ return *ImpreciseReleaseMDKind;
255
+ case ARCMDKindID::CopyOnEscape:
256
+ if (!CopyOnEscapeMDKind)
257
+ CopyOnEscapeMDKind =
258
+ M->getContext().getMDKindID("clang.arc.copy_on_escape");
259
+ return *CopyOnEscapeMDKind;
260
+ case ARCMDKindID::NoObjCARCExceptions:
261
+ if (!NoObjCARCExceptionsMDKind)
262
+ NoObjCARCExceptionsMDKind =
263
+ M->getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
264
+ return *NoObjCARCExceptionsMDKind;
265
+ }
266
+ llvm_unreachable("Covered switch isn't covered?!");
267
+ }
268
+ };
269
+
270
+ } // end namespace objcarc
271
+ } // end namespace llvm
272
+
273
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/PHITransAddr.h ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- PHITransAddr.h - PHI Translation for Addresses -----------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file declares the PHITransAddr class.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_PHITRANSADDR_H
14
+ #define LLVM_ANALYSIS_PHITRANSADDR_H
15
+
16
+ #include "llvm/ADT/SmallVector.h"
17
+ #include "llvm/IR/Instruction.h"
18
+ #include "llvm/Support/Compiler.h"
19
+
20
+ namespace llvm {
21
+ class AssumptionCache;
22
+ class DominatorTree;
23
+ class DataLayout;
24
+ class TargetLibraryInfo;
25
+
26
+ /// PHITransAddr - An address value which tracks and handles phi translation.
27
+ /// As we walk "up" the CFG through predecessors, we need to ensure that the
28
+ /// address we're tracking is kept up to date. For example, if we're analyzing
29
+ /// an address of "&A[i]" and walk through the definition of 'i' which is a PHI
30
+ /// node, we *must* phi translate i to get "&A[j]" or else we will analyze an
31
+ /// incorrect pointer in the predecessor block.
32
+ ///
33
+ /// This is designed to be a relatively small object that lives on the stack and
34
+ /// is copyable.
35
+ ///
36
+ class PHITransAddr {
37
+ /// Addr - The actual address we're analyzing.
38
+ Value *Addr;
39
+
40
+ /// The DataLayout we are playing with.
41
+ const DataLayout &DL;
42
+
43
+ /// TLI - The target library info if known, otherwise null.
44
+ const TargetLibraryInfo *TLI = nullptr;
45
+
46
+ /// A cache of \@llvm.assume calls used by SimplifyInstruction.
47
+ AssumptionCache *AC;
48
+
49
+ /// InstInputs - The inputs for our symbolic address.
50
+ SmallVector<Instruction*, 4> InstInputs;
51
+
52
+ public:
53
+ PHITransAddr(Value *Addr, const DataLayout &DL, AssumptionCache *AC)
54
+ : Addr(Addr), DL(DL), AC(AC) {
55
+ // If the address is an instruction, the whole thing is considered an input.
56
+ addAsInput(Addr);
57
+ }
58
+
59
+ Value *getAddr() const { return Addr; }
60
+
61
+ /// needsPHITranslationFromBlock - Return true if moving from the specified
62
+ /// BasicBlock to its predecessors requires PHI translation.
63
+ bool needsPHITranslationFromBlock(BasicBlock *BB) const {
64
+ // We do need translation if one of our input instructions is defined in
65
+ // this block.
66
+ return any_of(InstInputs, [BB](const auto &InstInput) {
67
+ return InstInput->getParent() == BB;
68
+ });
69
+ }
70
+
71
+ /// isPotentiallyPHITranslatable - If this needs PHI translation, return true
72
+ /// if we have some hope of doing it. This should be used as a filter to
73
+ /// avoid calling PHITranslateValue in hopeless situations.
74
+ LLVM_ABI bool isPotentiallyPHITranslatable() const;
75
+
76
+ /// translateValue - PHI translate the current address up the CFG from
77
+ /// CurBB to Pred, updating our state to reflect any needed changes. If
78
+ /// 'MustDominate' is true, the translated value must dominate PredBB.
79
+ LLVM_ABI Value *translateValue(BasicBlock *CurBB, BasicBlock *PredBB,
80
+ const DominatorTree *DT, bool MustDominate);
81
+
82
+ /// translateWithInsertion - PHI translate this value into the specified
83
+ /// predecessor block, inserting a computation of the value if it is
84
+ /// unavailable.
85
+ ///
86
+ /// All newly created instructions are added to the NewInsts list. This
87
+ /// returns null on failure.
88
+ ///
89
+ LLVM_ABI Value *
90
+ translateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB,
91
+ const DominatorTree &DT,
92
+ SmallVectorImpl<Instruction *> &NewInsts);
93
+
94
+ LLVM_ABI void dump() const;
95
+
96
+ /// verify - Check internal consistency of this data structure. If the
97
+ /// structure is valid, it returns true. If invalid, it prints errors and
98
+ /// returns false.
99
+ LLVM_ABI bool verify() const;
100
+
101
+ private:
102
+ Value *translateSubExpr(Value *V, BasicBlock *CurBB, BasicBlock *PredBB,
103
+ const DominatorTree *DT);
104
+
105
+ /// insertTranslatedSubExpr - Insert a computation of the PHI translated
106
+ /// version of 'V' for the edge PredBB->CurBB into the end of the PredBB
107
+ /// block. All newly created instructions are added to the NewInsts list.
108
+ /// This returns null on failure.
109
+ ///
110
+ Value *insertTranslatedSubExpr(Value *InVal, BasicBlock *CurBB,
111
+ BasicBlock *PredBB, const DominatorTree &DT,
112
+ SmallVectorImpl<Instruction *> &NewInsts);
113
+
114
+ /// addAsInput - If the specified value is an instruction, add it as an input.
115
+ Value *addAsInput(Value *V) {
116
+ // If V is an instruction, it is now an input.
117
+ if (Instruction *VI = dyn_cast<Instruction>(V))
118
+ InstInputs.push_back(VI);
119
+ return V;
120
+ }
121
+ };
122
+
123
+ } // end namespace llvm
124
+
125
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/PostDominators.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //=- llvm/Analysis/PostDominators.h - Post Dominator Calculation --*- C++ -*-=//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file exposes interfaces to post dominance information.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_POSTDOMINATORS_H
14
+ #define LLVM_ANALYSIS_POSTDOMINATORS_H
15
+
16
+ #include "llvm/ADT/DepthFirstIterator.h"
17
+ #include "llvm/IR/Dominators.h"
18
+ #include "llvm/IR/PassManager.h"
19
+ #include "llvm/Pass.h"
20
+ #include "llvm/Support/Compiler.h"
21
+
22
+ namespace llvm {
23
+
24
+ class Function;
25
+ class raw_ostream;
26
+
27
+ /// PostDominatorTree Class - Concrete subclass of DominatorTree that is used to
28
+ /// compute the post-dominator tree.
29
+ class PostDominatorTree : public PostDomTreeBase<BasicBlock> {
30
+ public:
31
+ using Base = PostDomTreeBase<BasicBlock>;
32
+
33
+ PostDominatorTree() = default;
34
+ explicit PostDominatorTree(Function &F) { recalculate(F); }
35
+ /// Handle invalidation explicitly.
36
+ LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
37
+ FunctionAnalysisManager::Invalidator &);
38
+
39
+ // Ensure base-class overloads are visible.
40
+ using Base::dominates;
41
+
42
+ /// Return true if \p I1 dominates \p I2. This checks if \p I2 comes before
43
+ /// \p I1 if they belongs to the same basic block.
44
+ LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const;
45
+ };
46
+
47
+ /// Analysis pass which computes a \c PostDominatorTree.
48
+ class PostDominatorTreeAnalysis
49
+ : public AnalysisInfoMixin<PostDominatorTreeAnalysis> {
50
+ friend AnalysisInfoMixin<PostDominatorTreeAnalysis>;
51
+
52
+ LLVM_ABI static AnalysisKey Key;
53
+
54
+ public:
55
+ /// Provide the result type for this analysis pass.
56
+ using Result = PostDominatorTree;
57
+
58
+ /// Run the analysis pass over a function and produce a post dominator
59
+ /// tree.
60
+ LLVM_ABI PostDominatorTree run(Function &F, FunctionAnalysisManager &);
61
+ };
62
+
63
+ /// Printer pass for the \c PostDominatorTree.
64
+ class PostDominatorTreePrinterPass
65
+ : public PassInfoMixin<PostDominatorTreePrinterPass> {
66
+ raw_ostream &OS;
67
+
68
+ public:
69
+ LLVM_ABI explicit PostDominatorTreePrinterPass(raw_ostream &OS);
70
+
71
+ LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
72
+
73
+ static bool isRequired() { return true; }
74
+ };
75
+
76
+ struct LLVM_ABI PostDominatorTreeWrapperPass : public FunctionPass {
77
+ static char ID; // Pass identification, replacement for typeid
78
+
79
+ PostDominatorTree DT;
80
+
81
+ PostDominatorTreeWrapperPass();
82
+
83
+ PostDominatorTree &getPostDomTree() { return DT; }
84
+ const PostDominatorTree &getPostDomTree() const { return DT; }
85
+
86
+ bool runOnFunction(Function &F) override;
87
+
88
+ void verifyAnalysis() const override;
89
+
90
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
91
+ AU.setPreservesAll();
92
+ }
93
+
94
+ void releaseMemory() override { DT.reset(); }
95
+
96
+ void print(raw_ostream &OS, const Module*) const override;
97
+ };
98
+
99
+ LLVM_ABI FunctionPass *createPostDomTree();
100
+
101
+ template <> struct GraphTraits<PostDominatorTree*>
102
+ : public GraphTraits<DomTreeNode*> {
103
+ static NodeRef getEntryNode(PostDominatorTree *DT) {
104
+ return DT->getRootNode();
105
+ }
106
+
107
+ static nodes_iterator nodes_begin(PostDominatorTree *N) {
108
+ return df_begin(getEntryNode(N));
109
+ }
110
+
111
+ static nodes_iterator nodes_end(PostDominatorTree *N) {
112
+ return df_end(getEntryNode(N));
113
+ }
114
+ };
115
+
116
+ } // end namespace llvm
117
+
118
+ #endif // LLVM_ANALYSIS_POSTDOMINATORS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/PtrUseVisitor.h ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- PtrUseVisitor.h - InstVisitors over a pointers uses ------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ /// \file
10
+ /// This file provides a collection of visitors which walk the (instruction)
11
+ /// uses of a pointer. These visitors all provide the same essential behavior
12
+ /// as an InstVisitor with similar template-based flexibility and
13
+ /// implementation strategies.
14
+ ///
15
+ /// These can be used, for example, to quickly analyze the uses of an alloca,
16
+ /// global variable, or function argument.
17
+ ///
18
+ /// FIXME: Provide a variant which doesn't track offsets and is cheaper.
19
+ //
20
+ //===----------------------------------------------------------------------===//
21
+
22
+ #ifndef LLVM_ANALYSIS_PTRUSEVISITOR_H
23
+ #define LLVM_ANALYSIS_PTRUSEVISITOR_H
24
+
25
+ #include "llvm/ADT/APInt.h"
26
+ #include "llvm/ADT/PointerIntPair.h"
27
+ #include "llvm/ADT/SmallPtrSet.h"
28
+ #include "llvm/ADT/SmallVector.h"
29
+ #include "llvm/IR/DerivedTypes.h"
30
+ #include "llvm/IR/InstVisitor.h"
31
+ #include "llvm/IR/IntrinsicInst.h"
32
+ #include <cassert>
33
+ #include <type_traits>
34
+
35
+ namespace llvm {
36
+ class DataLayout;
37
+
38
+ namespace detail {
39
+
40
+ /// Implementation of non-dependent functionality for \c PtrUseVisitor.
41
+ ///
42
+ /// See \c PtrUseVisitor for the public interface and detailed comments about
43
+ /// usage. This class is just a helper base class which is not templated and
44
+ /// contains all common code to be shared between different instantiations of
45
+ /// PtrUseVisitor.
46
+ class PtrUseVisitorBase {
47
+ public:
48
+ /// This class provides information about the result of a visit.
49
+ ///
50
+ /// After walking all the users (recursively) of a pointer, the basic
51
+ /// infrastructure records some commonly useful information such as escape
52
+ /// analysis and whether the visit completed or aborted early.
53
+ class PtrInfo {
54
+ public:
55
+ /// Reset the pointer info, clearing all state.
56
+ void reset() {
57
+ AbortedInfo = nullptr;
58
+ EscapedInfo = nullptr;
59
+ }
60
+
61
+ /// Did we abort the visit early?
62
+ bool isAborted() const { return AbortedInfo != nullptr; }
63
+
64
+ /// Is the pointer escaped at some point?
65
+ bool isEscaped() const { return EscapedInfo != nullptr; }
66
+
67
+ /// Is the pointer escaped into a read-only nocapture call at some point?
68
+ bool isEscapedReadOnly() const { return EscapedReadOnly != nullptr; }
69
+
70
+ /// Get the instruction causing the visit to abort.
71
+ /// \returns a pointer to the instruction causing the abort if one is
72
+ /// available; otherwise returns null.
73
+ Instruction *getAbortingInst() const { return AbortedInfo; }
74
+
75
+ /// Get the instruction causing the pointer to escape.
76
+ /// \returns a pointer to the instruction which escapes the pointer if one
77
+ /// is available; otherwise returns null.
78
+ Instruction *getEscapingInst() const { return EscapedInfo; }
79
+
80
+ /// Get the instruction causing the pointer to escape which is a read-only
81
+ /// nocapture call.
82
+ Instruction *getEscapedReadOnlyInst() const { return EscapedReadOnly; }
83
+
84
+ /// Mark the visit as aborted. Intended for use in a void return.
85
+ /// \param I The instruction which caused the visit to abort, if available.
86
+ void setAborted(Instruction *I) {
87
+ assert(I && "Expected a valid pointer in setAborted");
88
+ AbortedInfo = I;
89
+ }
90
+
91
+ /// Mark the pointer as escaped. Intended for use in a void return.
92
+ /// \param I The instruction which escapes the pointer, if available.
93
+ void setEscaped(Instruction *I) {
94
+ assert(I && "Expected a valid pointer in setEscaped");
95
+ EscapedInfo = I;
96
+ }
97
+
98
+ /// Mark the pointer as escaped into a readonly-nocapture call.
99
+ void setEscapedReadOnly(Instruction *I) {
100
+ assert(I && "Expected a valid pointer in setEscapedReadOnly");
101
+ EscapedReadOnly = I;
102
+ }
103
+
104
+ /// Mark the pointer as escaped, and the visit as aborted. Intended
105
+ /// for use in a void return.
106
+ /// \param I The instruction which both escapes the pointer and aborts the
107
+ /// visit, if available.
108
+ void setEscapedAndAborted(Instruction *I) {
109
+ setEscaped(I);
110
+ setAborted(I);
111
+ }
112
+
113
+ private:
114
+ Instruction *AbortedInfo = nullptr;
115
+ Instruction *EscapedInfo = nullptr;
116
+ Instruction *EscapedReadOnly = nullptr;
117
+ };
118
+
119
+ protected:
120
+ const DataLayout &DL;
121
+
122
+ /// \name Visitation infrastructure
123
+ /// @{
124
+
125
+ /// The info collected about the pointer being visited thus far.
126
+ PtrInfo PI;
127
+
128
+ /// A struct of the data needed to visit a particular use.
129
+ ///
130
+ /// This is used to maintain a worklist fo to-visit uses. This is used to
131
+ /// make the visit be iterative rather than recursive.
132
+ struct UseToVisit {
133
+ using UseAndIsOffsetKnownPair = PointerIntPair<Use *, 1, bool>;
134
+
135
+ UseAndIsOffsetKnownPair UseAndIsOffsetKnown;
136
+ APInt Offset;
137
+ };
138
+
139
+ /// The worklist of to-visit uses.
140
+ SmallVector<UseToVisit, 8> Worklist;
141
+
142
+ /// A set of visited uses to break cycles in unreachable code.
143
+ SmallPtrSet<Use *, 8> VisitedUses;
144
+
145
+ /// @}
146
+
147
+ /// \name Per-visit state
148
+ /// This state is reset for each instruction visited.
149
+ /// @{
150
+
151
+ /// The use currently being visited.
152
+ Use *U;
153
+
154
+ /// True if we have a known constant offset for the use currently
155
+ /// being visited.
156
+ bool IsOffsetKnown;
157
+
158
+ /// The constant offset of the use if that is known.
159
+ APInt Offset;
160
+
161
+ /// @}
162
+
163
+ /// Note that the constructor is protected because this class must be a base
164
+ /// class, we can't create instances directly of this class.
165
+ PtrUseVisitorBase(const DataLayout &DL) : DL(DL) {}
166
+
167
+ /// Enqueue the users of this instruction in the visit worklist.
168
+ ///
169
+ /// This will visit the users with the same offset of the current visit
170
+ /// (including an unknown offset if that is the current state).
171
+ void enqueueUsers(Value &I);
172
+
173
+ /// Walk the operands of a GEP and adjust the offset as appropriate.
174
+ ///
175
+ /// This routine does the heavy lifting of the pointer walk by computing
176
+ /// offsets and looking through GEPs.
177
+ bool adjustOffsetForGEP(GetElementPtrInst &GEPI);
178
+ };
179
+
180
+ } // end namespace detail
181
+
182
+ /// A base class for visitors over the uses of a pointer value.
183
+ ///
184
+ /// Once constructed, a user can call \c visit on a pointer value, and this
185
+ /// will walk its uses and visit each instruction using an InstVisitor. It also
186
+ /// provides visit methods which will recurse through any pointer-to-pointer
187
+ /// transformations such as GEPs and bitcasts.
188
+ ///
189
+ /// During the visit, the current Use* being visited is available to the
190
+ /// subclass, as well as the current offset from the original base pointer if
191
+ /// known.
192
+ ///
193
+ /// The recursive visit of uses is accomplished with a worklist, so the only
194
+ /// ordering guarantee is that an instruction is visited before any uses of it
195
+ /// are visited. Note that this does *not* mean before any of its users are
196
+ /// visited! This is because users can be visited multiple times due to
197
+ /// multiple, different uses of pointers derived from the same base.
198
+ ///
199
+ /// A particular Use will only be visited once, but a User may be visited
200
+ /// multiple times, once per Use. This visits may notably have different
201
+ /// offsets.
202
+ ///
203
+ /// All visit methods on the underlying InstVisitor return a boolean. This
204
+ /// return short-circuits the visit, stopping it immediately.
205
+ ///
206
+ /// FIXME: Generalize this for all values rather than just instructions.
207
+ template <typename DerivedT>
208
+ class PtrUseVisitor : protected InstVisitor<DerivedT>,
209
+ public detail::PtrUseVisitorBase {
210
+ friend class InstVisitor<DerivedT>;
211
+
212
+ using Base = InstVisitor<DerivedT>;
213
+
214
+ public:
215
+ PtrUseVisitor(const DataLayout &DL) : PtrUseVisitorBase(DL) {
216
+ static_assert(std::is_base_of<PtrUseVisitor, DerivedT>::value,
217
+ "Must pass the derived type to this template!");
218
+ }
219
+
220
+ /// Recursively visit the uses of the given pointer.
221
+ /// \returns An info struct about the pointer. See \c PtrInfo for details.
222
+ /// We may also need to process Argument pointers, so the input uses is
223
+ /// a common Value type.
224
+ PtrInfo visitPtr(Value &I) {
225
+ // This must be a pointer type. Get an integer type suitable to hold
226
+ // offsets on this pointer.
227
+ // FIXME: Support a vector of pointers.
228
+ assert(I.getType()->isPointerTy());
229
+ assert(isa<Instruction>(I) || isa<Argument>(I));
230
+ IntegerType *IntIdxTy = cast<IntegerType>(DL.getIndexType(I.getType()));
231
+ IsOffsetKnown = true;
232
+ Offset = APInt(IntIdxTy->getBitWidth(), 0);
233
+ PI.reset();
234
+
235
+ // Enqueue the uses of this pointer.
236
+ enqueueUsers(I);
237
+
238
+ // Visit all the uses off the worklist until it is empty.
239
+ while (!Worklist.empty()) {
240
+ UseToVisit ToVisit = Worklist.pop_back_val();
241
+ U = ToVisit.UseAndIsOffsetKnown.getPointer();
242
+ IsOffsetKnown = ToVisit.UseAndIsOffsetKnown.getInt();
243
+ if (IsOffsetKnown)
244
+ Offset = std::move(ToVisit.Offset);
245
+
246
+ Instruction *I = cast<Instruction>(U->getUser());
247
+ static_cast<DerivedT*>(this)->visit(I);
248
+ if (PI.isAborted())
249
+ break;
250
+ }
251
+ return PI;
252
+ }
253
+
254
+ protected:
255
+ void visitStoreInst(StoreInst &SI) {
256
+ if (SI.getValueOperand() == U->get())
257
+ PI.setEscaped(&SI);
258
+ }
259
+
260
+ void visitBitCastInst(BitCastInst &BC) {
261
+ enqueueUsers(BC);
262
+ }
263
+
264
+ void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
265
+ enqueueUsers(ASC);
266
+ }
267
+
268
+ void visitPtrToIntInst(PtrToIntInst &I) {
269
+ PI.setEscaped(&I);
270
+ }
271
+
272
+ void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
273
+ if (GEPI.use_empty())
274
+ return;
275
+
276
+ // If we can't walk the GEP, clear the offset.
277
+ if (!adjustOffsetForGEP(GEPI)) {
278
+ IsOffsetKnown = false;
279
+ Offset = APInt();
280
+ }
281
+
282
+ // Enqueue the users now that the offset has been adjusted.
283
+ enqueueUsers(GEPI);
284
+ }
285
+
286
+ // No-op intrinsics which we know don't escape the pointer to logic in
287
+ // some other function.
288
+ void visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) {}
289
+ void visitMemIntrinsic(MemIntrinsic &I) {}
290
+ void visitIntrinsicInst(IntrinsicInst &II) {
291
+ switch (II.getIntrinsicID()) {
292
+ default:
293
+ return Base::visitIntrinsicInst(II);
294
+
295
+ // We escape pointers used by a fake_use to prevent SROA from transforming
296
+ // them.
297
+ case Intrinsic::fake_use:
298
+ PI.setEscaped(&II);
299
+ return;
300
+
301
+ case Intrinsic::lifetime_start:
302
+ case Intrinsic::lifetime_end:
303
+ return; // No-op intrinsics.
304
+ }
305
+ }
306
+
307
+ // Generically, arguments to calls and invokes escape the pointer to some
308
+ // other function. Mark that.
309
+ void visitCallBase(CallBase &CB) {
310
+ PI.setEscaped(&CB);
311
+ Base::visitCallBase(CB);
312
+ }
313
+ };
314
+
315
+ } // end namespace llvm
316
+
317
+ #endif // LLVM_ANALYSIS_PTRUSEVISITOR_H
deps/exla/cache/xla_extension/include/llvm/Analysis/RegionIterator.h ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- RegionIterator.h - Iterators to iteratate over Regions ---*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ // This file defines the iterators to iterate over the elements of a Region.
9
+ //===----------------------------------------------------------------------===//
10
+
11
+ #ifndef LLVM_ANALYSIS_REGIONITERATOR_H
12
+ #define LLVM_ANALYSIS_REGIONITERATOR_H
13
+
14
+ #include "llvm/ADT/DepthFirstIterator.h"
15
+ #include "llvm/ADT/GraphTraits.h"
16
+ #include "llvm/ADT/PointerIntPair.h"
17
+ #include "llvm/Analysis/RegionInfo.h"
18
+ #include <cassert>
19
+ #include <iterator>
20
+ #include <type_traits>
21
+
22
+ namespace llvm {
23
+
24
+ class BasicBlock;
25
+ class RegionInfo;
26
+
27
+ //===----------------------------------------------------------------------===//
28
+ /// Hierarchical RegionNode successor iterator.
29
+ ///
30
+ /// This iterator iterates over all successors of a RegionNode.
31
+ ///
32
+ /// For a BasicBlock RegionNode it skips all BasicBlocks that are not part of
33
+ /// the parent Region. Furthermore for BasicBlocks that start a subregion, a
34
+ /// RegionNode representing the subregion is returned.
35
+ ///
36
+ /// For a subregion RegionNode there is just one successor. The RegionNode
37
+ /// representing the exit of the subregion.
38
+ template <class NodeRef, class BlockT, class RegionT> class RNSuccIterator {
39
+ public:
40
+ using iterator_category = std::forward_iterator_tag;
41
+ using value_type = NodeRef;
42
+ using difference_type = std::ptrdiff_t;
43
+ using pointer = value_type *;
44
+ using reference = value_type &;
45
+
46
+ private:
47
+ using BlockTraits = GraphTraits<BlockT *>;
48
+ using SuccIterTy = typename BlockTraits::ChildIteratorType;
49
+
50
+ // The iterator works in two modes, bb mode or region mode.
51
+ enum ItMode {
52
+ // In BB mode it returns all successors of this BasicBlock as its
53
+ // successors.
54
+ ItBB,
55
+ // In region mode there is only one successor, thats the regionnode mapping
56
+ // to the exit block of the regionnode
57
+ ItRgBegin, // At the beginning of the regionnode successor.
58
+ ItRgEnd // At the end of the regionnode successor.
59
+ };
60
+
61
+ static_assert(std::is_pointer<NodeRef>::value,
62
+ "FIXME: Currently RNSuccIterator only supports NodeRef as "
63
+ "pointers due to the use of pointer-specific data structures "
64
+ "(e.g. PointerIntPair and SmallPtrSet) internally. Generalize "
65
+ "it to support non-pointer types");
66
+
67
+ // Use two bit to represent the mode iterator.
68
+ PointerIntPair<NodeRef, 2, ItMode> Node;
69
+
70
+ // The block successor iterator.
71
+ SuccIterTy BItor;
72
+
73
+ // advanceRegionSucc - A region node has only one successor. It reaches end
74
+ // once we advance it.
75
+ void advanceRegionSucc() {
76
+ assert(Node.getInt() == ItRgBegin && "Cannot advance region successor!");
77
+ Node.setInt(ItRgEnd);
78
+ }
79
+
80
+ NodeRef getNode() const { return Node.getPointer(); }
81
+
82
+ // isRegionMode - Is the current iterator in region mode?
83
+ bool isRegionMode() const { return Node.getInt() != ItBB; }
84
+
85
+ // Get the immediate successor. This function may return a Basic Block
86
+ // RegionNode or a subregion RegionNode.
87
+ NodeRef getISucc(BlockT *BB) const {
88
+ NodeRef succ;
89
+ succ = getNode()->getParent()->getNode(BB);
90
+ assert(succ && "BB not in Region or entered subregion!");
91
+ return succ;
92
+ }
93
+
94
+ // getRegionSucc - Return the successor basic block of a SubRegion RegionNode.
95
+ inline BlockT* getRegionSucc() const {
96
+ assert(Node.getInt() == ItRgBegin && "Cannot get the region successor!");
97
+ return getNode()->template getNodeAs<RegionT>()->getExit();
98
+ }
99
+
100
+ // isExit - Is this the exit BB of the Region?
101
+ inline bool isExit(BlockT* BB) const {
102
+ return getNode()->getParent()->getExit() == BB;
103
+ }
104
+
105
+ public:
106
+ using Self = RNSuccIterator<NodeRef, BlockT, RegionT>;
107
+
108
+ /// Create begin iterator of a RegionNode.
109
+ inline RNSuccIterator(NodeRef node)
110
+ : Node(node, node->isSubRegion() ? ItRgBegin : ItBB),
111
+ BItor(BlockTraits::child_begin(node->getEntry())) {
112
+ // Skip the exit block
113
+ if (!isRegionMode())
114
+ while (BlockTraits::child_end(node->getEntry()) != BItor && isExit(*BItor))
115
+ ++BItor;
116
+
117
+ if (isRegionMode() && isExit(getRegionSucc()))
118
+ advanceRegionSucc();
119
+ }
120
+
121
+ /// Create an end iterator.
122
+ inline RNSuccIterator(NodeRef node, bool)
123
+ : Node(node, node->isSubRegion() ? ItRgEnd : ItBB),
124
+ BItor(BlockTraits::child_end(node->getEntry())) {}
125
+
126
+ inline bool operator==(const Self& x) const {
127
+ assert(isRegionMode() == x.isRegionMode() && "Broken iterator!");
128
+ if (isRegionMode())
129
+ return Node.getInt() == x.Node.getInt();
130
+ else
131
+ return BItor == x.BItor;
132
+ }
133
+
134
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
135
+
136
+ inline value_type operator*() const {
137
+ BlockT *BB = isRegionMode() ? getRegionSucc() : *BItor;
138
+ assert(!isExit(BB) && "Iterator out of range!");
139
+ return getISucc(BB);
140
+ }
141
+
142
+ inline Self& operator++() {
143
+ if(isRegionMode()) {
144
+ // The Region only has 1 successor.
145
+ advanceRegionSucc();
146
+ } else {
147
+ // Skip the exit.
148
+ do
149
+ ++BItor;
150
+ while (BItor != BlockTraits::child_end(getNode()->getEntry())
151
+ && isExit(*BItor));
152
+ }
153
+ return *this;
154
+ }
155
+
156
+ inline Self operator++(int) {
157
+ Self tmp = *this;
158
+ ++*this;
159
+ return tmp;
160
+ }
161
+ };
162
+
163
+ //===----------------------------------------------------------------------===//
164
+ /// Flat RegionNode iterator.
165
+ ///
166
+ /// The Flat Region iterator will iterate over all BasicBlock RegionNodes that
167
+ /// are contained in the Region and its subregions. This is close to a virtual
168
+ /// control flow graph of the Region.
169
+ template <class NodeRef, class BlockT, class RegionT>
170
+ class RNSuccIterator<FlatIt<NodeRef>, BlockT, RegionT> {
171
+ using BlockTraits = GraphTraits<BlockT *>;
172
+ using SuccIterTy = typename BlockTraits::ChildIteratorType;
173
+
174
+ NodeRef Node;
175
+ SuccIterTy Itor;
176
+
177
+ public:
178
+ using iterator_category = std::forward_iterator_tag;
179
+ using value_type = NodeRef;
180
+ using difference_type = std::ptrdiff_t;
181
+ using pointer = value_type *;
182
+ using reference = value_type &;
183
+
184
+ using Self = RNSuccIterator<FlatIt<NodeRef>, BlockT, RegionT>;
185
+
186
+ /// Create the iterator from a RegionNode.
187
+ ///
188
+ /// Note that the incoming node must be a bb node, otherwise it will trigger
189
+ /// an assertion when we try to get a BasicBlock.
190
+ inline RNSuccIterator(NodeRef node)
191
+ : Node(node), Itor(BlockTraits::child_begin(node->getEntry())) {
192
+ assert(!Node->isSubRegion() &&
193
+ "Subregion node not allowed in flat iterating mode!");
194
+ assert(Node->getParent() && "A BB node must have a parent!");
195
+
196
+ // Skip the exit block of the iterating region.
197
+ while (BlockTraits::child_end(Node->getEntry()) != Itor &&
198
+ Node->getParent()->getExit() == *Itor)
199
+ ++Itor;
200
+ }
201
+
202
+ /// Create an end iterator
203
+ inline RNSuccIterator(NodeRef node, bool)
204
+ : Node(node), Itor(BlockTraits::child_end(node->getEntry())) {
205
+ assert(!Node->isSubRegion() &&
206
+ "Subregion node not allowed in flat iterating mode!");
207
+ }
208
+
209
+ inline bool operator==(const Self& x) const {
210
+ assert(Node->getParent() == x.Node->getParent()
211
+ && "Cannot compare iterators of different regions!");
212
+
213
+ return Itor == x.Itor && Node == x.Node;
214
+ }
215
+
216
+ inline bool operator!=(const Self& x) const { return !operator==(x); }
217
+
218
+ inline value_type operator*() const {
219
+ BlockT *BB = *Itor;
220
+
221
+ // Get the iterating region.
222
+ RegionT *Parent = Node->getParent();
223
+
224
+ // The only case that the successor reaches out of the region is it reaches
225
+ // the exit of the region.
226
+ assert(Parent->getExit() != BB && "iterator out of range!");
227
+
228
+ return Parent->getBBNode(BB);
229
+ }
230
+
231
+ inline Self& operator++() {
232
+ // Skip the exit block of the iterating region.
233
+ do
234
+ ++Itor;
235
+ while (Itor != succ_end(Node->getEntry())
236
+ && Node->getParent()->getExit() == *Itor);
237
+
238
+ return *this;
239
+ }
240
+
241
+ inline Self operator++(int) {
242
+ Self tmp = *this;
243
+ ++*this;
244
+ return tmp;
245
+ }
246
+ };
247
+
248
+ template <class NodeRef, class BlockT, class RegionT>
249
+ inline RNSuccIterator<NodeRef, BlockT, RegionT> succ_begin(NodeRef Node) {
250
+ return RNSuccIterator<NodeRef, BlockT, RegionT>(Node);
251
+ }
252
+
253
+ template <class NodeRef, class BlockT, class RegionT>
254
+ inline RNSuccIterator<NodeRef, BlockT, RegionT> succ_end(NodeRef Node) {
255
+ return RNSuccIterator<NodeRef, BlockT, RegionT>(Node, true);
256
+ }
257
+
258
+ //===--------------------------------------------------------------------===//
259
+ // RegionNode GraphTraits specialization so the bbs in the region can be
260
+ // iterate by generic graph iterators.
261
+ //
262
+ // NodeT can either be region node or const region node, otherwise child_begin
263
+ // and child_end fail.
264
+
265
+ #define RegionNodeGraphTraits(NodeT, BlockT, RegionT) \
266
+ template <> struct GraphTraits<NodeT *> { \
267
+ using NodeRef = NodeT *; \
268
+ using ChildIteratorType = RNSuccIterator<NodeRef, BlockT, RegionT>; \
269
+ static NodeRef getEntryNode(NodeRef N) { return N; } \
270
+ static inline ChildIteratorType child_begin(NodeRef N) { \
271
+ return RNSuccIterator<NodeRef, BlockT, RegionT>(N); \
272
+ } \
273
+ static inline ChildIteratorType child_end(NodeRef N) { \
274
+ return RNSuccIterator<NodeRef, BlockT, RegionT>(N, true); \
275
+ } \
276
+ }; \
277
+ template <> struct GraphTraits<FlatIt<NodeT *>> { \
278
+ using NodeRef = NodeT *; \
279
+ using ChildIteratorType = \
280
+ RNSuccIterator<FlatIt<NodeRef>, BlockT, RegionT>; \
281
+ static NodeRef getEntryNode(NodeRef N) { return N; } \
282
+ static inline ChildIteratorType child_begin(NodeRef N) { \
283
+ return RNSuccIterator<FlatIt<NodeRef>, BlockT, RegionT>(N); \
284
+ } \
285
+ static inline ChildIteratorType child_end(NodeRef N) { \
286
+ return RNSuccIterator<FlatIt<NodeRef>, BlockT, RegionT>(N, true); \
287
+ } \
288
+ }
289
+
290
+ #define RegionGraphTraits(RegionT, NodeT) \
291
+ template <> struct GraphTraits<RegionT *> : public GraphTraits<NodeT *> { \
292
+ using nodes_iterator = df_iterator<NodeRef>; \
293
+ static NodeRef getEntryNode(RegionT *R) { \
294
+ return R->getNode(R->getEntry()); \
295
+ } \
296
+ static nodes_iterator nodes_begin(RegionT *R) { \
297
+ return nodes_iterator::begin(getEntryNode(R)); \
298
+ } \
299
+ static nodes_iterator nodes_end(RegionT *R) { \
300
+ return nodes_iterator::end(getEntryNode(R)); \
301
+ } \
302
+ }; \
303
+ template <> \
304
+ struct GraphTraits<FlatIt<RegionT *>> \
305
+ : public GraphTraits<FlatIt<NodeT *>> { \
306
+ using nodes_iterator = \
307
+ df_iterator<NodeRef, df_iterator_default_set<NodeRef>, false, \
308
+ GraphTraits<FlatIt<NodeRef>>>; \
309
+ static NodeRef getEntryNode(RegionT *R) { \
310
+ return R->getBBNode(R->getEntry()); \
311
+ } \
312
+ static nodes_iterator nodes_begin(RegionT *R) { \
313
+ return nodes_iterator::begin(getEntryNode(R)); \
314
+ } \
315
+ static nodes_iterator nodes_end(RegionT *R) { \
316
+ return nodes_iterator::end(getEntryNode(R)); \
317
+ } \
318
+ }
319
+
320
+ RegionNodeGraphTraits(RegionNode, BasicBlock, Region);
321
+ RegionNodeGraphTraits(const RegionNode, BasicBlock, Region);
322
+
323
+ RegionGraphTraits(Region, RegionNode);
324
+ RegionGraphTraits(const Region, const RegionNode);
325
+
326
+ template <> struct GraphTraits<RegionInfo*>
327
+ : public GraphTraits<FlatIt<RegionNode*>> {
328
+ using nodes_iterator =
329
+ df_iterator<NodeRef, df_iterator_default_set<NodeRef>, false,
330
+ GraphTraits<FlatIt<NodeRef>>>;
331
+
332
+ static NodeRef getEntryNode(RegionInfo *RI) {
333
+ return GraphTraits<FlatIt<Region*>>::getEntryNode(RI->getTopLevelRegion());
334
+ }
335
+
336
+ static nodes_iterator nodes_begin(RegionInfo* RI) {
337
+ return nodes_iterator::begin(getEntryNode(RI));
338
+ }
339
+
340
+ static nodes_iterator nodes_end(RegionInfo *RI) {
341
+ return nodes_iterator::end(getEntryNode(RI));
342
+ }
343
+ };
344
+
345
+ template <> struct GraphTraits<RegionInfoPass*>
346
+ : public GraphTraits<RegionInfo *> {
347
+ using nodes_iterator =
348
+ df_iterator<NodeRef, df_iterator_default_set<NodeRef>, false,
349
+ GraphTraits<FlatIt<NodeRef>>>;
350
+
351
+ static NodeRef getEntryNode(RegionInfoPass *RI) {
352
+ return GraphTraits<RegionInfo*>::getEntryNode(&RI->getRegionInfo());
353
+ }
354
+
355
+ static nodes_iterator nodes_begin(RegionInfoPass* RI) {
356
+ return GraphTraits<RegionInfo*>::nodes_begin(&RI->getRegionInfo());
357
+ }
358
+
359
+ static nodes_iterator nodes_end(RegionInfoPass *RI) {
360
+ return GraphTraits<RegionInfo*>::nodes_end(&RI->getRegionInfo());
361
+ }
362
+ };
363
+
364
+ } // end namespace llvm
365
+
366
+ #endif // LLVM_ANALYSIS_REGIONITERATOR_H
deps/exla/cache/xla_extension/include/llvm/Analysis/RegionPrinter.h ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- RegionPrinter.h - Region printer external interface -----*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines external functions that can be called to explicitly
10
+ // instantiate the region printer.
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ #ifndef LLVM_ANALYSIS_REGIONPRINTER_H
15
+ #define LLVM_ANALYSIS_REGIONPRINTER_H
16
+
17
+ #include "llvm/Support/Compiler.h"
18
+ #include "llvm/Support/DOTGraphTraits.h"
19
+
20
+ namespace llvm {
21
+ class FunctionPass;
22
+ class Function;
23
+ class RegionInfo;
24
+ class RegionNode;
25
+
26
+ LLVM_ABI FunctionPass *createRegionViewerPass();
27
+ LLVM_ABI FunctionPass *createRegionOnlyViewerPass();
28
+ LLVM_ABI FunctionPass *createRegionPrinterPass();
29
+ LLVM_ABI FunctionPass *createRegionOnlyPrinterPass();
30
+
31
+ template <>
32
+ struct DOTGraphTraits<RegionNode *> : public DefaultDOTGraphTraits {
33
+ DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
34
+
35
+ LLVM_ABI std::string getNodeLabel(RegionNode *Node, RegionNode *Graph);
36
+ };
37
+
38
+ #ifndef NDEBUG
39
+ /// Open a viewer to display the GraphViz vizualization of the analysis
40
+ /// result.
41
+ ///
42
+ /// Practical to call in the debugger.
43
+ /// Includes the instructions in each BasicBlock.
44
+ ///
45
+ /// @param RI The analysis to display.
46
+ void viewRegion(llvm::RegionInfo *RI);
47
+
48
+ /// Analyze the regions of a function and open its GraphViz
49
+ /// visualization in a viewer.
50
+ ///
51
+ /// Useful to call in the debugger.
52
+ /// Includes the instructions in each BasicBlock.
53
+ /// The result of a new analysis may differ from the RegionInfo the pass
54
+ /// manager currently holds.
55
+ ///
56
+ /// @param F Function to analyze.
57
+ void viewRegion(const llvm::Function *F);
58
+
59
+ /// Open a viewer to display the GraphViz vizualization of the analysis
60
+ /// result.
61
+ ///
62
+ /// Useful to call in the debugger.
63
+ /// Shows only the BasicBlock names without their instructions.
64
+ ///
65
+ /// @param RI The analysis to display.
66
+ void viewRegionOnly(llvm::RegionInfo *RI);
67
+
68
+ /// Analyze the regions of a function and open its GraphViz
69
+ /// visualization in a viewer.
70
+ ///
71
+ /// Useful to call in the debugger.
72
+ /// Shows only the BasicBlock names without their instructions.
73
+ /// The result of a new analysis may differ from the RegionInfo the pass
74
+ /// manager currently holds.
75
+ ///
76
+ /// @param F Function to analyze.
77
+ void viewRegionOnly(const llvm::Function *F);
78
+ #endif
79
+ } // End llvm namespace
80
+
81
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionDivision.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/ScalarEvolutionDivision.h - See below ------*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the class that knows how to divide SCEV's.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONDIVISION_H
14
+ #define LLVM_ANALYSIS_SCALAREVOLUTIONDIVISION_H
15
+
16
+ #include "llvm/Analysis/ScalarEvolutionExpressions.h"
17
+
18
+ namespace llvm {
19
+
20
+ class SCEV;
21
+
22
+ class ScalarEvolution;
23
+
24
+ struct SCEVCouldNotCompute;
25
+
26
+ struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
27
+ public:
28
+ // Computes the Quotient and Remainder of the division of Numerator by
29
+ // Denominator.
30
+ static void divide(ScalarEvolution &SE, const SCEV *Numerator,
31
+ const SCEV *Denominator, const SCEV **Quotient,
32
+ const SCEV **Remainder);
33
+
34
+ // Except in the trivial case described above, we do not know how to divide
35
+ // Expr by Denominator for the following functions with empty implementation.
36
+ void visitPtrToIntExpr(const SCEVPtrToIntExpr *Numerator) {}
37
+ void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
38
+ void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
39
+ void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
40
+ void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
41
+ void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
42
+ void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
43
+ void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
44
+ void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
45
+ void visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Numerator) {}
46
+ void visitUnknown(const SCEVUnknown *Numerator) {}
47
+ void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
48
+
49
+ void visitConstant(const SCEVConstant *Numerator);
50
+
51
+ void visitVScale(const SCEVVScale *Numerator);
52
+
53
+ void visitAddRecExpr(const SCEVAddRecExpr *Numerator);
54
+
55
+ void visitAddExpr(const SCEVAddExpr *Numerator);
56
+
57
+ void visitMulExpr(const SCEVMulExpr *Numerator);
58
+
59
+ private:
60
+ SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
61
+ const SCEV *Denominator);
62
+
63
+ // Convenience function for giving up on the division. We set the quotient to
64
+ // be equal to zero and the remainder to be equal to the numerator.
65
+ void cannotDivide(const SCEV *Numerator);
66
+
67
+ ScalarEvolution &SE;
68
+ const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
69
+ };
70
+
71
+ } // end namespace llvm
72
+
73
+ #endif // LLVM_ANALYSIS_SCALAREVOLUTIONDIVISION_H
deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionExpressions.h ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/ScalarEvolutionExpressions.h - SCEV Exprs --*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines the classes used to represent and build scalar expressions.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
14
+ #define LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
15
+
16
+ #include "llvm/ADT/DenseMap.h"
17
+ #include "llvm/ADT/SmallPtrSet.h"
18
+ #include "llvm/ADT/SmallVector.h"
19
+ #include "llvm/Analysis/ScalarEvolution.h"
20
+ #include "llvm/IR/Constants.h"
21
+ #include "llvm/IR/ValueHandle.h"
22
+ #include "llvm/Support/Casting.h"
23
+ #include "llvm/Support/Compiler.h"
24
+ #include "llvm/Support/ErrorHandling.h"
25
+ #include <cassert>
26
+ #include <cstddef>
27
+
28
+ namespace llvm {
29
+
30
+ class APInt;
31
+ class Constant;
32
+ class ConstantInt;
33
+ class ConstantRange;
34
+ class Loop;
35
+ class Type;
36
+ class Value;
37
+
38
+ enum SCEVTypes : unsigned short {
39
+ // These should be ordered in terms of increasing complexity to make the
40
+ // folders simpler.
41
+ scConstant,
42
+ scVScale,
43
+ scTruncate,
44
+ scZeroExtend,
45
+ scSignExtend,
46
+ scAddExpr,
47
+ scMulExpr,
48
+ scUDivExpr,
49
+ scAddRecExpr,
50
+ scUMaxExpr,
51
+ scSMaxExpr,
52
+ scUMinExpr,
53
+ scSMinExpr,
54
+ scSequentialUMinExpr,
55
+ scPtrToInt,
56
+ scUnknown,
57
+ scCouldNotCompute
58
+ };
59
+
60
+ /// This class represents a constant integer value.
61
+ class SCEVConstant : public SCEV {
62
+ friend class ScalarEvolution;
63
+
64
+ ConstantInt *V;
65
+
66
+ SCEVConstant(const FoldingSetNodeIDRef ID, ConstantInt *v)
67
+ : SCEV(ID, scConstant, 1), V(v) {}
68
+
69
+ public:
70
+ ConstantInt *getValue() const { return V; }
71
+ const APInt &getAPInt() const { return getValue()->getValue(); }
72
+
73
+ Type *getType() const { return V->getType(); }
74
+
75
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
76
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scConstant; }
77
+ };
78
+
79
+ /// This class represents the value of vscale, as used when defining the length
80
+ /// of a scalable vector or returned by the llvm.vscale() intrinsic.
81
+ class SCEVVScale : public SCEV {
82
+ friend class ScalarEvolution;
83
+
84
+ SCEVVScale(const FoldingSetNodeIDRef ID, Type *ty)
85
+ : SCEV(ID, scVScale, 0), Ty(ty) {}
86
+
87
+ Type *Ty;
88
+
89
+ public:
90
+ Type *getType() const { return Ty; }
91
+
92
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
93
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scVScale; }
94
+ };
95
+
96
+ inline unsigned short computeExpressionSize(ArrayRef<const SCEV *> Args) {
97
+ APInt Size(16, 1);
98
+ for (const auto *Arg : Args)
99
+ Size = Size.uadd_sat(APInt(16, Arg->getExpressionSize()));
100
+ return (unsigned short)Size.getZExtValue();
101
+ }
102
+
103
+ /// This is the base class for unary cast operator classes.
104
+ class SCEVCastExpr : public SCEV {
105
+ protected:
106
+ const SCEV *Op;
107
+ Type *Ty;
108
+
109
+ LLVM_ABI SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
110
+ const SCEV *op, Type *ty);
111
+
112
+ public:
113
+ const SCEV *getOperand() const { return Op; }
114
+ const SCEV *getOperand(unsigned i) const {
115
+ assert(i == 0 && "Operand index out of range!");
116
+ return Op;
117
+ }
118
+ ArrayRef<const SCEV *> operands() const { return Op; }
119
+ size_t getNumOperands() const { return 1; }
120
+ Type *getType() const { return Ty; }
121
+
122
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
123
+ static bool classof(const SCEV *S) {
124
+ return S->getSCEVType() == scPtrToInt || S->getSCEVType() == scTruncate ||
125
+ S->getSCEVType() == scZeroExtend || S->getSCEVType() == scSignExtend;
126
+ }
127
+ };
128
+
129
+ /// This class represents a cast from a pointer to a pointer-sized integer
130
+ /// value.
131
+ class SCEVPtrToIntExpr : public SCEVCastExpr {
132
+ friend class ScalarEvolution;
133
+
134
+ SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, Type *ITy);
135
+
136
+ public:
137
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
138
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scPtrToInt; }
139
+ };
140
+
141
+ /// This is the base class for unary integral cast operator classes.
142
+ class SCEVIntegralCastExpr : public SCEVCastExpr {
143
+ protected:
144
+ LLVM_ABI SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
145
+ const SCEV *op, Type *ty);
146
+
147
+ public:
148
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
149
+ static bool classof(const SCEV *S) {
150
+ return S->getSCEVType() == scTruncate || S->getSCEVType() == scZeroExtend ||
151
+ S->getSCEVType() == scSignExtend;
152
+ }
153
+ };
154
+
155
+ /// This class represents a truncation of an integer value to a
156
+ /// smaller integer value.
157
+ class SCEVTruncateExpr : public SCEVIntegralCastExpr {
158
+ friend class ScalarEvolution;
159
+
160
+ SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
161
+
162
+ public:
163
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
164
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scTruncate; }
165
+ };
166
+
167
+ /// This class represents a zero extension of a small integer value
168
+ /// to a larger integer value.
169
+ class SCEVZeroExtendExpr : public SCEVIntegralCastExpr {
170
+ friend class ScalarEvolution;
171
+
172
+ SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
173
+
174
+ public:
175
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
176
+ static bool classof(const SCEV *S) {
177
+ return S->getSCEVType() == scZeroExtend;
178
+ }
179
+ };
180
+
181
+ /// This class represents a sign extension of a small integer value
182
+ /// to a larger integer value.
183
+ class SCEVSignExtendExpr : public SCEVIntegralCastExpr {
184
+ friend class ScalarEvolution;
185
+
186
+ SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, const SCEV *op, Type *ty);
187
+
188
+ public:
189
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
190
+ static bool classof(const SCEV *S) {
191
+ return S->getSCEVType() == scSignExtend;
192
+ }
193
+ };
194
+
195
+ /// This node is a base class providing common functionality for
196
+ /// n'ary operators.
197
+ class SCEVNAryExpr : public SCEV {
198
+ protected:
199
+ // Since SCEVs are immutable, ScalarEvolution allocates operand
200
+ // arrays with its SCEVAllocator, so this class just needs a simple
201
+ // pointer rather than a more elaborate vector-like data structure.
202
+ // This also avoids the need for a non-trivial destructor.
203
+ const SCEV *const *Operands;
204
+ size_t NumOperands;
205
+
206
+ SCEVNAryExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
207
+ const SCEV *const *O, size_t N)
208
+ : SCEV(ID, T, computeExpressionSize(ArrayRef(O, N))), Operands(O),
209
+ NumOperands(N) {}
210
+
211
+ public:
212
+ size_t getNumOperands() const { return NumOperands; }
213
+
214
+ const SCEV *getOperand(unsigned i) const {
215
+ assert(i < NumOperands && "Operand index out of range!");
216
+ return Operands[i];
217
+ }
218
+
219
+ ArrayRef<const SCEV *> operands() const {
220
+ return ArrayRef(Operands, NumOperands);
221
+ }
222
+
223
+ NoWrapFlags getNoWrapFlags(NoWrapFlags Mask = NoWrapMask) const {
224
+ return (NoWrapFlags)(SubclassData & Mask);
225
+ }
226
+
227
+ bool hasNoUnsignedWrap() const {
228
+ return getNoWrapFlags(FlagNUW) != FlagAnyWrap;
229
+ }
230
+
231
+ bool hasNoSignedWrap() const {
232
+ return getNoWrapFlags(FlagNSW) != FlagAnyWrap;
233
+ }
234
+
235
+ bool hasNoSelfWrap() const { return getNoWrapFlags(FlagNW) != FlagAnyWrap; }
236
+
237
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
238
+ static bool classof(const SCEV *S) {
239
+ return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
240
+ S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
241
+ S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr ||
242
+ S->getSCEVType() == scSequentialUMinExpr ||
243
+ S->getSCEVType() == scAddRecExpr;
244
+ }
245
+ };
246
+
247
+ /// This node is the base class for n'ary commutative operators.
248
+ class SCEVCommutativeExpr : public SCEVNAryExpr {
249
+ protected:
250
+ SCEVCommutativeExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
251
+ const SCEV *const *O, size_t N)
252
+ : SCEVNAryExpr(ID, T, O, N) {}
253
+
254
+ public:
255
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
256
+ static bool classof(const SCEV *S) {
257
+ return S->getSCEVType() == scAddExpr || S->getSCEVType() == scMulExpr ||
258
+ S->getSCEVType() == scSMaxExpr || S->getSCEVType() == scUMaxExpr ||
259
+ S->getSCEVType() == scSMinExpr || S->getSCEVType() == scUMinExpr;
260
+ }
261
+
262
+ /// Set flags for a non-recurrence without clearing previously set flags.
263
+ void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
264
+ };
265
+
266
+ /// This node represents an addition of some number of SCEVs.
267
+ class SCEVAddExpr : public SCEVCommutativeExpr {
268
+ friend class ScalarEvolution;
269
+
270
+ Type *Ty;
271
+
272
+ SCEVAddExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
273
+ : SCEVCommutativeExpr(ID, scAddExpr, O, N) {
274
+ auto *FirstPointerTypedOp = find_if(operands(), [](const SCEV *Op) {
275
+ return Op->getType()->isPointerTy();
276
+ });
277
+ if (FirstPointerTypedOp != operands().end())
278
+ Ty = (*FirstPointerTypedOp)->getType();
279
+ else
280
+ Ty = getOperand(0)->getType();
281
+ }
282
+
283
+ public:
284
+ Type *getType() const { return Ty; }
285
+
286
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
287
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scAddExpr; }
288
+ };
289
+
290
+ /// This node represents multiplication of some number of SCEVs.
291
+ class SCEVMulExpr : public SCEVCommutativeExpr {
292
+ friend class ScalarEvolution;
293
+
294
+ SCEVMulExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
295
+ : SCEVCommutativeExpr(ID, scMulExpr, O, N) {}
296
+
297
+ public:
298
+ Type *getType() const { return getOperand(0)->getType(); }
299
+
300
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
301
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scMulExpr; }
302
+ };
303
+
304
+ /// This class represents a binary unsigned division operation.
305
+ class SCEVUDivExpr : public SCEV {
306
+ friend class ScalarEvolution;
307
+
308
+ std::array<const SCEV *, 2> Operands;
309
+
310
+ SCEVUDivExpr(const FoldingSetNodeIDRef ID, const SCEV *lhs, const SCEV *rhs)
311
+ : SCEV(ID, scUDivExpr, computeExpressionSize({lhs, rhs})) {
312
+ Operands[0] = lhs;
313
+ Operands[1] = rhs;
314
+ }
315
+
316
+ public:
317
+ const SCEV *getLHS() const { return Operands[0]; }
318
+ const SCEV *getRHS() const { return Operands[1]; }
319
+ size_t getNumOperands() const { return 2; }
320
+ const SCEV *getOperand(unsigned i) const {
321
+ assert((i == 0 || i == 1) && "Operand index out of range!");
322
+ return i == 0 ? getLHS() : getRHS();
323
+ }
324
+
325
+ ArrayRef<const SCEV *> operands() const { return Operands; }
326
+
327
+ Type *getType() const {
328
+ // In most cases the types of LHS and RHS will be the same, but in some
329
+ // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
330
+ // depend on the type for correctness, but handling types carefully can
331
+ // avoid extra casts in the SCEVExpander. The LHS is more likely to be
332
+ // a pointer type than the RHS, so use the RHS' type here.
333
+ return getRHS()->getType();
334
+ }
335
+
336
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
337
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scUDivExpr; }
338
+ };
339
+
340
+ /// This node represents a polynomial recurrence on the trip count
341
+ /// of the specified loop. This is the primary focus of the
342
+ /// ScalarEvolution framework; all the other SCEV subclasses are
343
+ /// mostly just supporting infrastructure to allow SCEVAddRecExpr
344
+ /// expressions to be created and analyzed.
345
+ ///
346
+ /// All operands of an AddRec are required to be loop invariant.
347
+ ///
348
+ class SCEVAddRecExpr : public SCEVNAryExpr {
349
+ friend class ScalarEvolution;
350
+
351
+ const Loop *L;
352
+
353
+ SCEVAddRecExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N,
354
+ const Loop *l)
355
+ : SCEVNAryExpr(ID, scAddRecExpr, O, N), L(l) {}
356
+
357
+ public:
358
+ Type *getType() const { return getStart()->getType(); }
359
+ const SCEV *getStart() const { return Operands[0]; }
360
+ const Loop *getLoop() const { return L; }
361
+
362
+ /// Constructs and returns the recurrence indicating how much this
363
+ /// expression steps by. If this is a polynomial of degree N, it
364
+ /// returns a chrec of degree N-1. We cannot determine whether
365
+ /// the step recurrence has self-wraparound.
366
+ const SCEV *getStepRecurrence(ScalarEvolution &SE) const {
367
+ if (isAffine())
368
+ return getOperand(1);
369
+ return SE.getAddRecExpr(
370
+ SmallVector<const SCEV *, 3>(operands().drop_front()), getLoop(),
371
+ FlagAnyWrap);
372
+ }
373
+
374
+ /// Return true if this represents an expression A + B*x where A
375
+ /// and B are loop invariant values.
376
+ bool isAffine() const {
377
+ // We know that the start value is invariant. This expression is thus
378
+ // affine iff the step is also invariant.
379
+ return getNumOperands() == 2;
380
+ }
381
+
382
+ /// Return true if this represents an expression A + B*x + C*x^2
383
+ /// where A, B and C are loop invariant values. This corresponds
384
+ /// to an addrec of the form {L,+,M,+,N}
385
+ bool isQuadratic() const { return getNumOperands() == 3; }
386
+
387
+ /// Set flags for a recurrence without clearing any previously set flags.
388
+ /// For AddRec, either NUW or NSW implies NW. Keep track of this fact here
389
+ /// to make it easier to propagate flags.
390
+ void setNoWrapFlags(NoWrapFlags Flags) {
391
+ if (Flags & (FlagNUW | FlagNSW))
392
+ Flags = ScalarEvolution::setFlags(Flags, FlagNW);
393
+ SubclassData |= Flags;
394
+ }
395
+
396
+ /// Return the value of this chain of recurrences at the specified
397
+ /// iteration number.
398
+ LLVM_ABI const SCEV *evaluateAtIteration(const SCEV *It,
399
+ ScalarEvolution &SE) const;
400
+
401
+ /// Return the value of this chain of recurrences at the specified iteration
402
+ /// number. Takes an explicit list of operands to represent an AddRec.
403
+ LLVM_ABI static const SCEV *
404
+ evaluateAtIteration(ArrayRef<const SCEV *> Operands, const SCEV *It,
405
+ ScalarEvolution &SE);
406
+
407
+ /// Return the number of iterations of this loop that produce
408
+ /// values in the specified constant range. Another way of
409
+ /// looking at this is that it returns the first iteration number
410
+ /// where the value is not in the condition, thus computing the
411
+ /// exit count. If the iteration count can't be computed, an
412
+ /// instance of SCEVCouldNotCompute is returned.
413
+ LLVM_ABI const SCEV *getNumIterationsInRange(const ConstantRange &Range,
414
+ ScalarEvolution &SE) const;
415
+
416
+ /// Return an expression representing the value of this expression
417
+ /// one iteration of the loop ahead.
418
+ LLVM_ABI const SCEVAddRecExpr *getPostIncExpr(ScalarEvolution &SE) const;
419
+
420
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
421
+ static bool classof(const SCEV *S) {
422
+ return S->getSCEVType() == scAddRecExpr;
423
+ }
424
+ };
425
+
426
+ /// This node is the base class min/max selections.
427
+ class SCEVMinMaxExpr : public SCEVCommutativeExpr {
428
+ friend class ScalarEvolution;
429
+
430
+ static bool isMinMaxType(enum SCEVTypes T) {
431
+ return T == scSMaxExpr || T == scUMaxExpr || T == scSMinExpr ||
432
+ T == scUMinExpr;
433
+ }
434
+
435
+ protected:
436
+ /// Note: Constructing subclasses via this constructor is allowed
437
+ SCEVMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
438
+ const SCEV *const *O, size_t N)
439
+ : SCEVCommutativeExpr(ID, T, O, N) {
440
+ assert(isMinMaxType(T));
441
+ // Min and max never overflow
442
+ setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
443
+ }
444
+
445
+ public:
446
+ Type *getType() const { return getOperand(0)->getType(); }
447
+
448
+ static bool classof(const SCEV *S) { return isMinMaxType(S->getSCEVType()); }
449
+
450
+ static enum SCEVTypes negate(enum SCEVTypes T) {
451
+ switch (T) {
452
+ case scSMaxExpr:
453
+ return scSMinExpr;
454
+ case scSMinExpr:
455
+ return scSMaxExpr;
456
+ case scUMaxExpr:
457
+ return scUMinExpr;
458
+ case scUMinExpr:
459
+ return scUMaxExpr;
460
+ default:
461
+ llvm_unreachable("Not a min or max SCEV type!");
462
+ }
463
+ }
464
+ };
465
+
466
+ /// This class represents a signed maximum selection.
467
+ class SCEVSMaxExpr : public SCEVMinMaxExpr {
468
+ friend class ScalarEvolution;
469
+
470
+ SCEVSMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
471
+ : SCEVMinMaxExpr(ID, scSMaxExpr, O, N) {}
472
+
473
+ public:
474
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
475
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scSMaxExpr; }
476
+ };
477
+
478
+ /// This class represents an unsigned maximum selection.
479
+ class SCEVUMaxExpr : public SCEVMinMaxExpr {
480
+ friend class ScalarEvolution;
481
+
482
+ SCEVUMaxExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
483
+ : SCEVMinMaxExpr(ID, scUMaxExpr, O, N) {}
484
+
485
+ public:
486
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
487
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scUMaxExpr; }
488
+ };
489
+
490
+ /// This class represents a signed minimum selection.
491
+ class SCEVSMinExpr : public SCEVMinMaxExpr {
492
+ friend class ScalarEvolution;
493
+
494
+ SCEVSMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
495
+ : SCEVMinMaxExpr(ID, scSMinExpr, O, N) {}
496
+
497
+ public:
498
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
499
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scSMinExpr; }
500
+ };
501
+
502
+ /// This class represents an unsigned minimum selection.
503
+ class SCEVUMinExpr : public SCEVMinMaxExpr {
504
+ friend class ScalarEvolution;
505
+
506
+ SCEVUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O, size_t N)
507
+ : SCEVMinMaxExpr(ID, scUMinExpr, O, N) {}
508
+
509
+ public:
510
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
511
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scUMinExpr; }
512
+ };
513
+
514
+ /// This node is the base class for sequential/in-order min/max selections.
515
+ /// Note that their fundamental difference from SCEVMinMaxExpr's is that they
516
+ /// are early-returning upon reaching saturation point.
517
+ /// I.e. given `0 umin_seq poison`, the result will be `0`, while the result of
518
+ /// `0 umin poison` is `poison`. When returning early, later expressions are not
519
+ /// executed, so `0 umin_seq (%x u/ 0)` does not result in undefined behavior.
520
+ class SCEVSequentialMinMaxExpr : public SCEVNAryExpr {
521
+ friend class ScalarEvolution;
522
+
523
+ static bool isSequentialMinMaxType(enum SCEVTypes T) {
524
+ return T == scSequentialUMinExpr;
525
+ }
526
+
527
+ /// Set flags for a non-recurrence without clearing previously set flags.
528
+ void setNoWrapFlags(NoWrapFlags Flags) { SubclassData |= Flags; }
529
+
530
+ protected:
531
+ /// Note: Constructing subclasses via this constructor is allowed
532
+ SCEVSequentialMinMaxExpr(const FoldingSetNodeIDRef ID, enum SCEVTypes T,
533
+ const SCEV *const *O, size_t N)
534
+ : SCEVNAryExpr(ID, T, O, N) {
535
+ assert(isSequentialMinMaxType(T));
536
+ // Min and max never overflow
537
+ setNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW));
538
+ }
539
+
540
+ public:
541
+ Type *getType() const { return getOperand(0)->getType(); }
542
+
543
+ static SCEVTypes getEquivalentNonSequentialSCEVType(SCEVTypes Ty) {
544
+ assert(isSequentialMinMaxType(Ty));
545
+ switch (Ty) {
546
+ case scSequentialUMinExpr:
547
+ return scUMinExpr;
548
+ default:
549
+ llvm_unreachable("Not a sequential min/max type.");
550
+ }
551
+ }
552
+
553
+ SCEVTypes getEquivalentNonSequentialSCEVType() const {
554
+ return getEquivalentNonSequentialSCEVType(getSCEVType());
555
+ }
556
+
557
+ static bool classof(const SCEV *S) {
558
+ return isSequentialMinMaxType(S->getSCEVType());
559
+ }
560
+ };
561
+
562
+ /// This class represents a sequential/in-order unsigned minimum selection.
563
+ class SCEVSequentialUMinExpr : public SCEVSequentialMinMaxExpr {
564
+ friend class ScalarEvolution;
565
+
566
+ SCEVSequentialUMinExpr(const FoldingSetNodeIDRef ID, const SCEV *const *O,
567
+ size_t N)
568
+ : SCEVSequentialMinMaxExpr(ID, scSequentialUMinExpr, O, N) {}
569
+
570
+ public:
571
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
572
+ static bool classof(const SCEV *S) {
573
+ return S->getSCEVType() == scSequentialUMinExpr;
574
+ }
575
+ };
576
+
577
+ /// This means that we are dealing with an entirely unknown SCEV
578
+ /// value, and only represent it as its LLVM Value. This is the
579
+ /// "bottom" value for the analysis.
580
+ class LLVM_ABI SCEVUnknown final : public SCEV, private CallbackVH {
581
+ friend class ScalarEvolution;
582
+
583
+ /// The parent ScalarEvolution value. This is used to update the
584
+ /// parent's maps when the value associated with a SCEVUnknown is
585
+ /// deleted or RAUW'd.
586
+ ScalarEvolution *SE;
587
+
588
+ /// The next pointer in the linked list of all SCEVUnknown
589
+ /// instances owned by a ScalarEvolution.
590
+ SCEVUnknown *Next;
591
+
592
+ SCEVUnknown(const FoldingSetNodeIDRef ID, Value *V, ScalarEvolution *se,
593
+ SCEVUnknown *next)
594
+ : SCEV(ID, scUnknown, 1), CallbackVH(V), SE(se), Next(next) {}
595
+
596
+ // Implement CallbackVH.
597
+ void deleted() override;
598
+ void allUsesReplacedWith(Value *New) override;
599
+
600
+ public:
601
+ Value *getValue() const { return getValPtr(); }
602
+
603
+ Type *getType() const { return getValPtr()->getType(); }
604
+
605
+ /// Methods for support type inquiry through isa, cast, and dyn_cast:
606
+ static bool classof(const SCEV *S) { return S->getSCEVType() == scUnknown; }
607
+ };
608
+
609
+ /// This class defines a simple visitor class that may be used for
610
+ /// various SCEV analysis purposes.
611
+ template <typename SC, typename RetVal = void> struct SCEVVisitor {
612
+ RetVal visit(const SCEV *S) {
613
+ switch (S->getSCEVType()) {
614
+ case scConstant:
615
+ return ((SC *)this)->visitConstant((const SCEVConstant *)S);
616
+ case scVScale:
617
+ return ((SC *)this)->visitVScale((const SCEVVScale *)S);
618
+ case scPtrToInt:
619
+ return ((SC *)this)->visitPtrToIntExpr((const SCEVPtrToIntExpr *)S);
620
+ case scTruncate:
621
+ return ((SC *)this)->visitTruncateExpr((const SCEVTruncateExpr *)S);
622
+ case scZeroExtend:
623
+ return ((SC *)this)->visitZeroExtendExpr((const SCEVZeroExtendExpr *)S);
624
+ case scSignExtend:
625
+ return ((SC *)this)->visitSignExtendExpr((const SCEVSignExtendExpr *)S);
626
+ case scAddExpr:
627
+ return ((SC *)this)->visitAddExpr((const SCEVAddExpr *)S);
628
+ case scMulExpr:
629
+ return ((SC *)this)->visitMulExpr((const SCEVMulExpr *)S);
630
+ case scUDivExpr:
631
+ return ((SC *)this)->visitUDivExpr((const SCEVUDivExpr *)S);
632
+ case scAddRecExpr:
633
+ return ((SC *)this)->visitAddRecExpr((const SCEVAddRecExpr *)S);
634
+ case scSMaxExpr:
635
+ return ((SC *)this)->visitSMaxExpr((const SCEVSMaxExpr *)S);
636
+ case scUMaxExpr:
637
+ return ((SC *)this)->visitUMaxExpr((const SCEVUMaxExpr *)S);
638
+ case scSMinExpr:
639
+ return ((SC *)this)->visitSMinExpr((const SCEVSMinExpr *)S);
640
+ case scUMinExpr:
641
+ return ((SC *)this)->visitUMinExpr((const SCEVUMinExpr *)S);
642
+ case scSequentialUMinExpr:
643
+ return ((SC *)this)
644
+ ->visitSequentialUMinExpr((const SCEVSequentialUMinExpr *)S);
645
+ case scUnknown:
646
+ return ((SC *)this)->visitUnknown((const SCEVUnknown *)S);
647
+ case scCouldNotCompute:
648
+ return ((SC *)this)->visitCouldNotCompute((const SCEVCouldNotCompute *)S);
649
+ }
650
+ llvm_unreachable("Unknown SCEV kind!");
651
+ }
652
+
653
+ RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S) {
654
+ llvm_unreachable("Invalid use of SCEVCouldNotCompute!");
655
+ }
656
+ };
657
+
658
+ /// Visit all nodes in the expression tree using worklist traversal.
659
+ ///
660
+ /// Visitor implements:
661
+ /// // return true to follow this node.
662
+ /// bool follow(const SCEV *S);
663
+ /// // return true to terminate the search.
664
+ /// bool isDone();
665
+ template <typename SV> class SCEVTraversal {
666
+ SV &Visitor;
667
+ SmallVector<const SCEV *, 8> Worklist;
668
+ SmallPtrSet<const SCEV *, 8> Visited;
669
+
670
+ void push(const SCEV *S) {
671
+ if (Visited.insert(S).second && Visitor.follow(S))
672
+ Worklist.push_back(S);
673
+ }
674
+
675
+ public:
676
+ SCEVTraversal(SV &V) : Visitor(V) {}
677
+
678
+ void visitAll(const SCEV *Root) {
679
+ push(Root);
680
+ while (!Worklist.empty() && !Visitor.isDone()) {
681
+ const SCEV *S = Worklist.pop_back_val();
682
+
683
+ switch (S->getSCEVType()) {
684
+ case scConstant:
685
+ case scVScale:
686
+ case scUnknown:
687
+ continue;
688
+ case scPtrToInt:
689
+ case scTruncate:
690
+ case scZeroExtend:
691
+ case scSignExtend:
692
+ case scAddExpr:
693
+ case scMulExpr:
694
+ case scUDivExpr:
695
+ case scSMaxExpr:
696
+ case scUMaxExpr:
697
+ case scSMinExpr:
698
+ case scUMinExpr:
699
+ case scSequentialUMinExpr:
700
+ case scAddRecExpr:
701
+ for (const auto *Op : S->operands()) {
702
+ push(Op);
703
+ if (Visitor.isDone())
704
+ break;
705
+ }
706
+ continue;
707
+ case scCouldNotCompute:
708
+ llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
709
+ }
710
+ llvm_unreachable("Unknown SCEV kind!");
711
+ }
712
+ }
713
+ };
714
+
715
+ /// Use SCEVTraversal to visit all nodes in the given expression tree.
716
+ template <typename SV> void visitAll(const SCEV *Root, SV &Visitor) {
717
+ SCEVTraversal<SV> T(Visitor);
718
+ T.visitAll(Root);
719
+ }
720
+
721
+ /// Return true if any node in \p Root satisfies the predicate \p Pred.
722
+ template <typename PredTy>
723
+ bool SCEVExprContains(const SCEV *Root, PredTy Pred) {
724
+ struct FindClosure {
725
+ bool Found = false;
726
+ PredTy Pred;
727
+
728
+ FindClosure(PredTy Pred) : Pred(Pred) {}
729
+
730
+ bool follow(const SCEV *S) {
731
+ if (!Pred(S))
732
+ return true;
733
+
734
+ Found = true;
735
+ return false;
736
+ }
737
+
738
+ bool isDone() const { return Found; }
739
+ };
740
+
741
+ FindClosure FC(Pred);
742
+ visitAll(Root, FC);
743
+ return FC.Found;
744
+ }
745
+
746
+ /// This visitor recursively visits a SCEV expression and re-writes it.
747
+ /// The result from each visit is cached, so it will return the same
748
+ /// SCEV for the same input.
749
+ template <typename SC>
750
+ class SCEVRewriteVisitor : public SCEVVisitor<SC, const SCEV *> {
751
+ protected:
752
+ ScalarEvolution &SE;
753
+ // Memoize the result of each visit so that we only compute once for
754
+ // the same input SCEV. This is to avoid redundant computations when
755
+ // a SCEV is referenced by multiple SCEVs. Without memoization, this
756
+ // visit algorithm would have exponential time complexity in the worst
757
+ // case, causing the compiler to hang on certain tests.
758
+ SmallDenseMap<const SCEV *, const SCEV *> RewriteResults;
759
+
760
+ public:
761
+ SCEVRewriteVisitor(ScalarEvolution &SE) : SE(SE) {}
762
+
763
+ const SCEV *visit(const SCEV *S) {
764
+ auto It = RewriteResults.find(S);
765
+ if (It != RewriteResults.end())
766
+ return It->second;
767
+ auto *Visited = SCEVVisitor<SC, const SCEV *>::visit(S);
768
+ auto Result = RewriteResults.try_emplace(S, Visited);
769
+ assert(Result.second && "Should insert a new entry");
770
+ return Result.first->second;
771
+ }
772
+
773
+ const SCEV *visitConstant(const SCEVConstant *Constant) { return Constant; }
774
+
775
+ const SCEV *visitVScale(const SCEVVScale *VScale) { return VScale; }
776
+
777
+ const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) {
778
+ const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
779
+ return Operand == Expr->getOperand()
780
+ ? Expr
781
+ : SE.getPtrToIntExpr(Operand, Expr->getType());
782
+ }
783
+
784
+ const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) {
785
+ const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
786
+ return Operand == Expr->getOperand()
787
+ ? Expr
788
+ : SE.getTruncateExpr(Operand, Expr->getType());
789
+ }
790
+
791
+ const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
792
+ const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
793
+ return Operand == Expr->getOperand()
794
+ ? Expr
795
+ : SE.getZeroExtendExpr(Operand, Expr->getType());
796
+ }
797
+
798
+ const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
799
+ const SCEV *Operand = ((SC *)this)->visit(Expr->getOperand());
800
+ return Operand == Expr->getOperand()
801
+ ? Expr
802
+ : SE.getSignExtendExpr(Operand, Expr->getType());
803
+ }
804
+
805
+ const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
806
+ SmallVector<const SCEV *, 2> Operands;
807
+ bool Changed = false;
808
+ for (const auto *Op : Expr->operands()) {
809
+ Operands.push_back(((SC *)this)->visit(Op));
810
+ Changed |= Op != Operands.back();
811
+ }
812
+ return !Changed ? Expr : SE.getAddExpr(Operands);
813
+ }
814
+
815
+ const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
816
+ SmallVector<const SCEV *, 2> Operands;
817
+ bool Changed = false;
818
+ for (const auto *Op : Expr->operands()) {
819
+ Operands.push_back(((SC *)this)->visit(Op));
820
+ Changed |= Op != Operands.back();
821
+ }
822
+ return !Changed ? Expr : SE.getMulExpr(Operands);
823
+ }
824
+
825
+ const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) {
826
+ auto *LHS = ((SC *)this)->visit(Expr->getLHS());
827
+ auto *RHS = ((SC *)this)->visit(Expr->getRHS());
828
+ bool Changed = LHS != Expr->getLHS() || RHS != Expr->getRHS();
829
+ return !Changed ? Expr : SE.getUDivExpr(LHS, RHS);
830
+ }
831
+
832
+ const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
833
+ SmallVector<const SCEV *, 2> Operands;
834
+ bool Changed = false;
835
+ for (const auto *Op : Expr->operands()) {
836
+ Operands.push_back(((SC *)this)->visit(Op));
837
+ Changed |= Op != Operands.back();
838
+ }
839
+ return !Changed ? Expr
840
+ : SE.getAddRecExpr(Operands, Expr->getLoop(),
841
+ Expr->getNoWrapFlags());
842
+ }
843
+
844
+ const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
845
+ SmallVector<const SCEV *, 2> Operands;
846
+ bool Changed = false;
847
+ for (const auto *Op : Expr->operands()) {
848
+ Operands.push_back(((SC *)this)->visit(Op));
849
+ Changed |= Op != Operands.back();
850
+ }
851
+ return !Changed ? Expr : SE.getSMaxExpr(Operands);
852
+ }
853
+
854
+ const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) {
855
+ SmallVector<const SCEV *, 2> Operands;
856
+ bool Changed = false;
857
+ for (const auto *Op : Expr->operands()) {
858
+ Operands.push_back(((SC *)this)->visit(Op));
859
+ Changed |= Op != Operands.back();
860
+ }
861
+ return !Changed ? Expr : SE.getUMaxExpr(Operands);
862
+ }
863
+
864
+ const SCEV *visitSMinExpr(const SCEVSMinExpr *Expr) {
865
+ SmallVector<const SCEV *, 2> Operands;
866
+ bool Changed = false;
867
+ for (const auto *Op : Expr->operands()) {
868
+ Operands.push_back(((SC *)this)->visit(Op));
869
+ Changed |= Op != Operands.back();
870
+ }
871
+ return !Changed ? Expr : SE.getSMinExpr(Operands);
872
+ }
873
+
874
+ const SCEV *visitUMinExpr(const SCEVUMinExpr *Expr) {
875
+ SmallVector<const SCEV *, 2> Operands;
876
+ bool Changed = false;
877
+ for (const auto *Op : Expr->operands()) {
878
+ Operands.push_back(((SC *)this)->visit(Op));
879
+ Changed |= Op != Operands.back();
880
+ }
881
+ return !Changed ? Expr : SE.getUMinExpr(Operands);
882
+ }
883
+
884
+ const SCEV *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
885
+ SmallVector<const SCEV *, 2> Operands;
886
+ bool Changed = false;
887
+ for (const auto *Op : Expr->operands()) {
888
+ Operands.push_back(((SC *)this)->visit(Op));
889
+ Changed |= Op != Operands.back();
890
+ }
891
+ return !Changed ? Expr : SE.getUMinExpr(Operands, /*Sequential=*/true);
892
+ }
893
+
894
+ const SCEV *visitUnknown(const SCEVUnknown *Expr) { return Expr; }
895
+
896
+ const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
897
+ return Expr;
898
+ }
899
+ };
900
+
901
+ using ValueToValueMap = DenseMap<const Value *, Value *>;
902
+ using ValueToSCEVMapTy = DenseMap<const Value *, const SCEV *>;
903
+
904
+ /// The SCEVParameterRewriter takes a scalar evolution expression and updates
905
+ /// the SCEVUnknown components following the Map (Value -> SCEV).
906
+ class SCEVParameterRewriter : public SCEVRewriteVisitor<SCEVParameterRewriter> {
907
+ public:
908
+ static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE,
909
+ ValueToSCEVMapTy &Map) {
910
+ SCEVParameterRewriter Rewriter(SE, Map);
911
+ return Rewriter.visit(Scev);
912
+ }
913
+
914
+ SCEVParameterRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M)
915
+ : SCEVRewriteVisitor(SE), Map(M) {}
916
+
917
+ const SCEV *visitUnknown(const SCEVUnknown *Expr) {
918
+ auto I = Map.find(Expr->getValue());
919
+ if (I == Map.end())
920
+ return Expr;
921
+ return I->second;
922
+ }
923
+
924
+ private:
925
+ ValueToSCEVMapTy &Map;
926
+ };
927
+
928
+ using LoopToScevMapT = DenseMap<const Loop *, const SCEV *>;
929
+
930
+ /// The SCEVLoopAddRecRewriter takes a scalar evolution expression and applies
931
+ /// the Map (Loop -> SCEV) to all AddRecExprs.
932
+ class SCEVLoopAddRecRewriter
933
+ : public SCEVRewriteVisitor<SCEVLoopAddRecRewriter> {
934
+ public:
935
+ SCEVLoopAddRecRewriter(ScalarEvolution &SE, LoopToScevMapT &M)
936
+ : SCEVRewriteVisitor(SE), Map(M) {}
937
+
938
+ static const SCEV *rewrite(const SCEV *Scev, LoopToScevMapT &Map,
939
+ ScalarEvolution &SE) {
940
+ SCEVLoopAddRecRewriter Rewriter(SE, Map);
941
+ return Rewriter.visit(Scev);
942
+ }
943
+
944
+ const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
945
+ SmallVector<const SCEV *, 2> Operands;
946
+ for (const SCEV *Op : Expr->operands())
947
+ Operands.push_back(visit(Op));
948
+
949
+ const Loop *L = Expr->getLoop();
950
+ auto It = Map.find(L);
951
+ if (It == Map.end())
952
+ return SE.getAddRecExpr(Operands, L, Expr->getNoWrapFlags());
953
+
954
+ return SCEVAddRecExpr::evaluateAtIteration(Operands, It->second, SE);
955
+ }
956
+
957
+ private:
958
+ LoopToScevMapT &Map;
959
+ };
960
+
961
+ } // end namespace llvm
962
+
963
+ #endif // LLVM_ANALYSIS_SCALAREVOLUTIONEXPRESSIONS_H
deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionNormalization.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===- llvm/Analysis/ScalarEvolutionNormalization.h - See below -*- C++ -*-===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+ //
9
+ // This file defines utilities for working with "normalized" ScalarEvolution
10
+ // expressions.
11
+ //
12
+ // The following example illustrates post-increment uses and how normalized
13
+ // expressions help.
14
+ //
15
+ // for (i=0; i!=n; ++i) {
16
+ // ...
17
+ // }
18
+ // use(i);
19
+ //
20
+ // While the expression for most uses of i inside the loop is {0,+,1}<%L>, the
21
+ // expression for the use of i outside the loop is {1,+,1}<%L>, since i is
22
+ // incremented at the end of the loop body. This is inconveient, since it
23
+ // suggests that we need two different induction variables, one that starts
24
+ // at 0 and one that starts at 1. We'd prefer to be able to think of these as
25
+ // the same induction variable, with uses inside the loop using the
26
+ // "pre-incremented" value, and uses after the loop using the
27
+ // "post-incremented" value.
28
+ //
29
+ // Expressions for post-incremented uses are represented as an expression
30
+ // paired with a set of loops for which the expression is in "post-increment"
31
+ // mode (there may be multiple loops).
32
+ //
33
+ //===----------------------------------------------------------------------===//
34
+
35
+ #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONNORMALIZATION_H
36
+ #define LLVM_ANALYSIS_SCALAREVOLUTIONNORMALIZATION_H
37
+
38
+ #include "llvm/ADT/STLFunctionalExtras.h"
39
+ #include "llvm/ADT/SmallPtrSet.h"
40
+ #include "llvm/Support/Compiler.h"
41
+
42
+ namespace llvm {
43
+
44
+ class Loop;
45
+ class ScalarEvolution;
46
+ class SCEV;
47
+ class SCEVAddRecExpr;
48
+
49
+ typedef SmallPtrSet<const Loop *, 2> PostIncLoopSet;
50
+
51
+ typedef function_ref<bool(const SCEVAddRecExpr *)> NormalizePredTy;
52
+
53
+ /// Normalize \p S to be post-increment for all loops present in \p
54
+ /// Loops. Returns nullptr if the result is not invertible and \p
55
+ /// CheckInvertible is true.
56
+ LLVM_ABI const SCEV *normalizeForPostIncUse(const SCEV *S,
57
+ const PostIncLoopSet &Loops,
58
+ ScalarEvolution &SE,
59
+ bool CheckInvertible = true);
60
+
61
+ /// Normalize \p S for all add recurrence sub-expressions for which \p
62
+ /// Pred returns true.
63
+ LLVM_ABI const SCEV *normalizeForPostIncUseIf(const SCEV *S,
64
+ NormalizePredTy Pred,
65
+ ScalarEvolution &SE);
66
+
67
+ /// Denormalize \p S to be post-increment for all loops present in \p
68
+ /// Loops.
69
+ LLVM_ABI const SCEV *denormalizeForPostIncUse(const SCEV *S,
70
+ const PostIncLoopSet &Loops,
71
+ ScalarEvolution &SE);
72
+ } // namespace llvm
73
+
74
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarEvolutionPatternMatch.h ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===----------------------------------------------------------------------===//
2
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3
+ // See https://llvm.org/LICENSE.txt for license information.
4
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5
+ //
6
+ //===----------------------------------------------------------------------===//
7
+ //
8
+ // This file provides a simple and efficient mechanism for performing general
9
+ // tree-based pattern matches on SCEVs, based on LLVM's IR pattern matchers.
10
+ //
11
+ //===----------------------------------------------------------------------===//
12
+
13
+ #ifndef LLVM_ANALYSIS_SCALAREVOLUTIONPATTERNMATCH_H
14
+ #define LLVM_ANALYSIS_SCALAREVOLUTIONPATTERNMATCH_H
15
+
16
+ #include "llvm/Analysis/ScalarEvolutionExpressions.h"
17
+
18
+ namespace llvm {
19
+ namespace SCEVPatternMatch {
20
+
21
+ template <typename Pattern> bool match(const SCEV *S, const Pattern &P) {
22
+ return P.match(S);
23
+ }
24
+
25
+ template <typename Predicate> struct cst_pred_ty : public Predicate {
26
+ cst_pred_ty() = default;
27
+ cst_pred_ty(uint64_t V) : Predicate(V) {}
28
+ bool match(const SCEV *S) const {
29
+ assert((isa<SCEVCouldNotCompute>(S) || !S->getType()->isVectorTy()) &&
30
+ "no vector types expected from SCEVs");
31
+ auto *C = dyn_cast<SCEVConstant>(S);
32
+ return C && this->isValue(C->getAPInt());
33
+ }
34
+ };
35
+
36
+ struct is_zero {
37
+ bool isValue(const APInt &C) const { return C.isZero(); }
38
+ };
39
+
40
+ /// Match an integer 0.
41
+ inline cst_pred_ty<is_zero> m_scev_Zero() { return cst_pred_ty<is_zero>(); }
42
+
43
+ struct is_one {
44
+ bool isValue(const APInt &C) const { return C.isOne(); }
45
+ };
46
+
47
+ /// Match an integer 1.
48
+ inline cst_pred_ty<is_one> m_scev_One() { return cst_pred_ty<is_one>(); }
49
+
50
+ struct is_all_ones {
51
+ bool isValue(const APInt &C) const { return C.isAllOnes(); }
52
+ };
53
+
54
+ /// Match an integer with all bits set.
55
+ inline cst_pred_ty<is_all_ones> m_scev_AllOnes() {
56
+ return cst_pred_ty<is_all_ones>();
57
+ }
58
+
59
+ template <typename Class> struct class_match {
60
+ template <typename ITy> bool match(ITy *V) const { return isa<Class>(V); }
61
+ };
62
+
63
+ inline class_match<const SCEV> m_SCEV() { return class_match<const SCEV>(); }
64
+ inline class_match<const SCEVConstant> m_SCEVConstant() {
65
+ return class_match<const SCEVConstant>();
66
+ }
67
+
68
+ template <typename Class> struct bind_ty {
69
+ Class *&VR;
70
+
71
+ bind_ty(Class *&V) : VR(V) {}
72
+
73
+ template <typename ITy> bool match(ITy *V) const {
74
+ if (auto *CV = dyn_cast<Class>(V)) {
75
+ VR = CV;
76
+ return true;
77
+ }
78
+ return false;
79
+ }
80
+ };
81
+
82
+ /// Match a SCEV, capturing it if we match.
83
+ inline bind_ty<const SCEV> m_SCEV(const SCEV *&V) { return V; }
84
+ inline bind_ty<const SCEVConstant> m_SCEVConstant(const SCEVConstant *&V) {
85
+ return V;
86
+ }
87
+ inline bind_ty<const SCEVUnknown> m_SCEVUnknown(const SCEVUnknown *&V) {
88
+ return V;
89
+ }
90
+
91
+ /// Match a specified const SCEV *.
92
+ struct specificscev_ty {
93
+ const SCEV *Expr;
94
+
95
+ specificscev_ty(const SCEV *Expr) : Expr(Expr) {}
96
+
97
+ template <typename ITy> bool match(ITy *S) const { return S == Expr; }
98
+ };
99
+
100
+ /// Match if we have a specific specified SCEV.
101
+ inline specificscev_ty m_scev_Specific(const SCEV *S) { return S; }
102
+
103
+ struct is_specific_cst {
104
+ uint64_t CV;
105
+ is_specific_cst(uint64_t C) : CV(C) {}
106
+ bool isValue(const APInt &C) const { return C == CV; }
107
+ };
108
+
109
+ /// Match an SCEV constant with a plain unsigned integer.
110
+ inline cst_pred_ty<is_specific_cst> m_scev_SpecificInt(uint64_t V) { return V; }
111
+
112
+ struct bind_cst_ty {
113
+ const APInt *&CR;
114
+
115
+ bind_cst_ty(const APInt *&Op0) : CR(Op0) {}
116
+
117
+ bool match(const SCEV *S) const {
118
+ assert((isa<SCEVCouldNotCompute>(S) || !S->getType()->isVectorTy()) &&
119
+ "no vector types expected from SCEVs");
120
+ auto *C = dyn_cast<SCEVConstant>(S);
121
+ if (!C)
122
+ return false;
123
+ CR = &C->getAPInt();
124
+ return true;
125
+ }
126
+ };
127
+
128
+ /// Match an SCEV constant and bind it to an APInt.
129
+ inline bind_cst_ty m_scev_APInt(const APInt *&C) { return C; }
130
+
131
+ /// Match a unary SCEV.
132
+ template <typename SCEVTy, typename Op0_t> struct SCEVUnaryExpr_match {
133
+ Op0_t Op0;
134
+
135
+ SCEVUnaryExpr_match(Op0_t Op0) : Op0(Op0) {}
136
+
137
+ bool match(const SCEV *S) const {
138
+ auto *E = dyn_cast<SCEVTy>(S);
139
+ return E && E->getNumOperands() == 1 && Op0.match(E->getOperand(0));
140
+ }
141
+ };
142
+
143
+ template <typename SCEVTy, typename Op0_t>
144
+ inline SCEVUnaryExpr_match<SCEVTy, Op0_t> m_scev_Unary(const Op0_t &Op0) {
145
+ return SCEVUnaryExpr_match<SCEVTy, Op0_t>(Op0);
146
+ }
147
+
148
+ template <typename Op0_t>
149
+ inline SCEVUnaryExpr_match<SCEVSignExtendExpr, Op0_t>
150
+ m_scev_SExt(const Op0_t &Op0) {
151
+ return m_scev_Unary<SCEVSignExtendExpr>(Op0);
152
+ }
153
+
154
+ template <typename Op0_t>
155
+ inline SCEVUnaryExpr_match<SCEVZeroExtendExpr, Op0_t>
156
+ m_scev_ZExt(const Op0_t &Op0) {
157
+ return m_scev_Unary<SCEVZeroExtendExpr>(Op0);
158
+ }
159
+
160
+ /// Match a binary SCEV.
161
+ template <typename SCEVTy, typename Op0_t, typename Op1_t>
162
+ struct SCEVBinaryExpr_match {
163
+ Op0_t Op0;
164
+ Op1_t Op1;
165
+
166
+ SCEVBinaryExpr_match(Op0_t Op0, Op1_t Op1) : Op0(Op0), Op1(Op1) {}
167
+
168
+ bool match(const SCEV *S) const {
169
+ auto *E = dyn_cast<SCEVTy>(S);
170
+ return E && E->getNumOperands() == 2 && Op0.match(E->getOperand(0)) &&
171
+ Op1.match(E->getOperand(1));
172
+ }
173
+ };
174
+
175
+ template <typename SCEVTy, typename Op0_t, typename Op1_t>
176
+ inline SCEVBinaryExpr_match<SCEVTy, Op0_t, Op1_t>
177
+ m_scev_Binary(const Op0_t &Op0, const Op1_t &Op1) {
178
+ return SCEVBinaryExpr_match<SCEVTy, Op0_t, Op1_t>(Op0, Op1);
179
+ }
180
+
181
+ template <typename Op0_t, typename Op1_t>
182
+ inline SCEVBinaryExpr_match<SCEVAddExpr, Op0_t, Op1_t>
183
+ m_scev_Add(const Op0_t &Op0, const Op1_t &Op1) {
184
+ return m_scev_Binary<SCEVAddExpr>(Op0, Op1);
185
+ }
186
+
187
+ template <typename Op0_t, typename Op1_t>
188
+ inline SCEVBinaryExpr_match<SCEVMulExpr, Op0_t, Op1_t>
189
+ m_scev_Mul(const Op0_t &Op0, const Op1_t &Op1) {
190
+ return m_scev_Binary<SCEVMulExpr>(Op0, Op1);
191
+ }
192
+
193
+ template <typename Op0_t, typename Op1_t>
194
+ inline SCEVBinaryExpr_match<SCEVUDivExpr, Op0_t, Op1_t>
195
+ m_scev_UDiv(const Op0_t &Op0, const Op1_t &Op1) {
196
+ return m_scev_Binary<SCEVUDivExpr>(Op0, Op1);
197
+ }
198
+
199
+ inline class_match<const Loop> m_Loop() { return class_match<const Loop>(); }
200
+
201
+ /// Match an affine SCEVAddRecExpr.
202
+ template <typename Op0_t, typename Op1_t, typename Loop_t>
203
+ struct SCEVAffineAddRec_match {
204
+ SCEVBinaryExpr_match<SCEVAddRecExpr, Op0_t, Op1_t> Ops;
205
+ Loop_t Loop;
206
+
207
+ SCEVAffineAddRec_match(Op0_t Op0, Op1_t Op1, Loop_t Loop)
208
+ : Ops(Op0, Op1), Loop(Loop) {}
209
+
210
+ bool match(const SCEV *S) const {
211
+ return Ops.match(S) && Loop.match(cast<SCEVAddRecExpr>(S)->getLoop());
212
+ }
213
+ };
214
+
215
+ /// Match a specified const Loop*.
216
+ struct specificloop_ty {
217
+ const Loop *L;
218
+
219
+ specificloop_ty(const Loop *L) : L(L) {}
220
+
221
+ bool match(const Loop *L) const { return L == this->L; }
222
+ };
223
+
224
+ inline specificloop_ty m_SpecificLoop(const Loop *L) { return L; }
225
+
226
+ inline bind_ty<const Loop> m_Loop(const Loop *&L) { return L; }
227
+
228
+ template <typename Op0_t, typename Op1_t>
229
+ inline SCEVAffineAddRec_match<Op0_t, Op1_t, class_match<const Loop>>
230
+ m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1) {
231
+ return SCEVAffineAddRec_match<Op0_t, Op1_t, class_match<const Loop>>(
232
+ Op0, Op1, m_Loop());
233
+ }
234
+
235
+ template <typename Op0_t, typename Op1_t, typename Loop_t>
236
+ inline SCEVAffineAddRec_match<Op0_t, Op1_t, Loop_t>
237
+ m_scev_AffineAddRec(const Op0_t &Op0, const Op1_t &Op1, const Loop_t &L) {
238
+ return SCEVAffineAddRec_match<Op0_t, Op1_t, Loop_t>(Op0, Op1, L);
239
+ }
240
+
241
+ } // namespace SCEVPatternMatch
242
+ } // namespace llvm
243
+
244
+ #endif
deps/exla/cache/xla_extension/include/llvm/Analysis/ScalarFuncs.def ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //===-- ScalarFuncs.def - Library information ----------*- C++ -*----------===//
2
+ //
3
+ // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
+ // See https://llvm.org/LICENSE.txt for license information.
5
+ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
+ //
7
+ //===----------------------------------------------------------------------===//
8
+
9
+ // This .def file creates mapping from standard IEEE math functions
10
+ // their corresponding entries in the IBM MASS (scalar) library.
11
+ // LLVM intrinsic math functions will be handled in PPCISelLowing to
12
+ // allow existing optimizations like pow(x,0.5) --> sqrt(x).
13
+
14
+ #if defined(TLI_DEFINE_SCALAR_MASS_FUNCS)
15
+ #define TLI_DEFINE_SCALAR_MASS_FUNC(SCAL, MASSENTRY) {SCAL, MASSENTRY},
16
+ #endif
17
+
18
+ TLI_DEFINE_SCALAR_MASS_FUNC("acosf", "__xl_acosf")
19
+ TLI_DEFINE_SCALAR_MASS_FUNC("__acosf_finite", "__xl_acosf")
20
+ TLI_DEFINE_SCALAR_MASS_FUNC("acos", "__xl_acos")
21
+ TLI_DEFINE_SCALAR_MASS_FUNC("__acos_finite", "__xl_acos")
22
+
23
+ TLI_DEFINE_SCALAR_MASS_FUNC("acoshf", "__xl_acoshf")
24
+ TLI_DEFINE_SCALAR_MASS_FUNC("__acoshf_finite", "__xl_acoshf")
25
+ TLI_DEFINE_SCALAR_MASS_FUNC("acosh", "__xl_acosh")
26
+ TLI_DEFINE_SCALAR_MASS_FUNC("__acosh_finite", "__xl_acosh")
27
+
28
+ TLI_DEFINE_SCALAR_MASS_FUNC("asinf", "__xl_asinf")
29
+ TLI_DEFINE_SCALAR_MASS_FUNC("__asinf_finite", "__xl_asinf")
30
+ TLI_DEFINE_SCALAR_MASS_FUNC("asin", "__xl_asin")
31
+ TLI_DEFINE_SCALAR_MASS_FUNC("__asin_finite", "__xl_asin")
32
+
33
+ TLI_DEFINE_SCALAR_MASS_FUNC("asinhf", "__xl_asinhf")
34
+ TLI_DEFINE_SCALAR_MASS_FUNC("asinh", "__xl_asinh")
35
+
36
+ TLI_DEFINE_SCALAR_MASS_FUNC("atanf", "__xl_atanf")
37
+ TLI_DEFINE_SCALAR_MASS_FUNC("atan", "__xl_atan")
38
+
39
+ TLI_DEFINE_SCALAR_MASS_FUNC("atan2f", "__xl_atan2f")
40
+ TLI_DEFINE_SCALAR_MASS_FUNC("__atan2f_finite", "__xl_atan2f")
41
+ TLI_DEFINE_SCALAR_MASS_FUNC("atan2", "__xl_atan2")
42
+ TLI_DEFINE_SCALAR_MASS_FUNC("__atan2_finite", "__xl_atan2")
43
+
44
+ TLI_DEFINE_SCALAR_MASS_FUNC("atanhf", "__xl_atanhf")
45
+ TLI_DEFINE_SCALAR_MASS_FUNC("__atanhf_finite", "__xl_atanhf")
46
+ TLI_DEFINE_SCALAR_MASS_FUNC("atanh", "__xl_atanh")
47
+ TLI_DEFINE_SCALAR_MASS_FUNC("__atanh_finite", "__xl_atanh")
48
+
49
+ TLI_DEFINE_SCALAR_MASS_FUNC("cbrtf", "__xl_cbrtf")
50
+ TLI_DEFINE_SCALAR_MASS_FUNC("cbrt", "__xl_cbrt")
51
+
52
+ TLI_DEFINE_SCALAR_MASS_FUNC("cosf", "__xl_cosf")
53
+ TLI_DEFINE_SCALAR_MASS_FUNC("cos", "__xl_cos")
54
+
55
+ TLI_DEFINE_SCALAR_MASS_FUNC("coshf", "__xl_coshf")
56
+ TLI_DEFINE_SCALAR_MASS_FUNC("__coshf_finite", "__xl_coshf")
57
+ TLI_DEFINE_SCALAR_MASS_FUNC("cosh", "__xl_cosh")
58
+ TLI_DEFINE_SCALAR_MASS_FUNC("__cosh_finite", "__xl_cosh")
59
+
60
+ TLI_DEFINE_SCALAR_MASS_FUNC("erff", "__xl_erff")
61
+ TLI_DEFINE_SCALAR_MASS_FUNC("erf", "__xl_erf")
62
+
63
+ TLI_DEFINE_SCALAR_MASS_FUNC("erfcf", "__xl_erfcf")
64
+ TLI_DEFINE_SCALAR_MASS_FUNC("erfc", "__xl_erfc")
65
+
66
+ TLI_DEFINE_SCALAR_MASS_FUNC("expf", "__xl_expf")
67
+ TLI_DEFINE_SCALAR_MASS_FUNC("__expf_finite", "__xl_expf")
68
+ TLI_DEFINE_SCALAR_MASS_FUNC("exp", "__xl_exp")
69
+ TLI_DEFINE_SCALAR_MASS_FUNC("__exp_finite", "__xl_exp")
70
+
71
+ TLI_DEFINE_SCALAR_MASS_FUNC("expm1f", "__xl_expm1f")
72
+ TLI_DEFINE_SCALAR_MASS_FUNC("expm1", "__xl_expm1")
73
+
74
+ TLI_DEFINE_SCALAR_MASS_FUNC("hypotf", "__xl_hypotf")
75
+ TLI_DEFINE_SCALAR_MASS_FUNC("hypot", "__xl_hypot")
76
+
77
+ TLI_DEFINE_SCALAR_MASS_FUNC("lgammaf", "__xl_lgammaf")
78
+ TLI_DEFINE_SCALAR_MASS_FUNC("lgamma", "__xl_lgamma")
79
+
80
+ TLI_DEFINE_SCALAR_MASS_FUNC("logf", "__xl_logf")
81
+ TLI_DEFINE_SCALAR_MASS_FUNC("__logf_finite", "__xl_logf")
82
+ TLI_DEFINE_SCALAR_MASS_FUNC("log", "__xl_log")
83
+ TLI_DEFINE_SCALAR_MASS_FUNC("__log_finite", "__xl_log")
84
+
85
+ TLI_DEFINE_SCALAR_MASS_FUNC("log10f", "__xl_log10f")
86
+ TLI_DEFINE_SCALAR_MASS_FUNC("__log10f_finite", "__xl_log10f")
87
+ TLI_DEFINE_SCALAR_MASS_FUNC("log10", "__xl_log10")
88
+ TLI_DEFINE_SCALAR_MASS_FUNC("__log10_finite", "__xl_log10")
89
+
90
+ TLI_DEFINE_SCALAR_MASS_FUNC("log1pf", "__xl_log1pf")
91
+ TLI_DEFINE_SCALAR_MASS_FUNC("log1p", "__xl_log1p")
92
+
93
+ TLI_DEFINE_SCALAR_MASS_FUNC("powf", "__xl_powf")
94
+ TLI_DEFINE_SCALAR_MASS_FUNC("__powf_finite", "__xl_powf")
95
+ TLI_DEFINE_SCALAR_MASS_FUNC("pow", "__xl_pow")
96
+ TLI_DEFINE_SCALAR_MASS_FUNC("__pow_finite", "__xl_pow")
97
+
98
+ TLI_DEFINE_SCALAR_MASS_FUNC("rsqrt", "__xl_rsqrt")
99
+
100
+ TLI_DEFINE_SCALAR_MASS_FUNC("sinf", "__xl_sinf")
101
+ TLI_DEFINE_SCALAR_MASS_FUNC("sin", "__xl_sin")
102
+
103
+ TLI_DEFINE_SCALAR_MASS_FUNC("sinhf", "__xl_sinhf")
104
+ TLI_DEFINE_SCALAR_MASS_FUNC("__sinhf_finite", "__xl_sinhf")
105
+ TLI_DEFINE_SCALAR_MASS_FUNC("sinh", "__xl_sinh")
106
+ TLI_DEFINE_SCALAR_MASS_FUNC("__sinh_finite", "__xl_sinh")
107
+
108
+ TLI_DEFINE_SCALAR_MASS_FUNC("sqrt", "__xl_sqrt")
109
+
110
+ TLI_DEFINE_SCALAR_MASS_FUNC("tanf", "__xl_tanf")
111
+ TLI_DEFINE_SCALAR_MASS_FUNC("tan", "__xl_tan")
112
+
113
+ TLI_DEFINE_SCALAR_MASS_FUNC("tanhf", "__xl_tanhf")
114
+ TLI_DEFINE_SCALAR_MASS_FUNC("tanh", "__xl_tanh")
115
+
116
+ #undef TLI_DEFINE_SCALAR_MASS_FUNCS
117
+ #undef TLI_DEFINE_SCALAR_MASS_FUNC