1 //===- MLRegAllocEvictAdvisor.cpp - ML eviction advisor -------------------===//
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 // Implementation of the ML eviction advisor and reward injection pass
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "RegAllocEvictionAdvisor.h"
14 #include "RegAllocGreedy.h"
15 #include "RegAllocScore.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/MLModelRunner.h"
18 #include "llvm/Analysis/ModelUnderTrainingRunner.h"
19 #include "llvm/Analysis/NoInferenceModelRunner.h"
20 #include "llvm/Analysis/ReleaseModeModelRunner.h"
21 #include "llvm/Analysis/Utils/TFUtils.h"
22 #include "llvm/CodeGen/CalcSpillWeights.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/Config/config.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/PassRegistry.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Target/TargetMachine.h"
38 
39 #include <array>
40 #include <memory>
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "ml-regalloc"
45 #ifdef LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL
46 #define LLVM_HAVE_TF_AOT
47 #endif
48 // Generated header in release (AOT) mode
49 #if defined LLVM_HAVE_TF_AOT
50 #include "RegallocEvictModel.h"
51 #endif
52 
53 // Options that only make sense in development mode
54 #ifdef LLVM_HAVE_TF_API
55 static cl::opt<std::string> TrainingLog(
56     "regalloc-training-log", cl::Hidden,
57     cl::desc("Training log for the register allocator eviction model"));
58 
59 static cl::opt<std::string> ModelUnderTraining(
60     "regalloc-model", cl::Hidden,
61     cl::desc("The model being trained for register allocation eviction"));
62 
63 #endif // #ifdef LLVM_HAVE_TF_API
64 
65 /// The score injection pass.
66 /// This pass calculates the score for a function and inserts it in the log, but
67 /// this happens only in development mode. It's a no-op otherwise.
68 namespace llvm {
69 class RegAllocScoring : public MachineFunctionPass {
70 public:
71   static char ID;
72 
73   RegAllocScoring() : MachineFunctionPass(ID) {
74     initializeRegAllocScoringPass(*PassRegistry::getPassRegistry());
75   }
76 
77   ~RegAllocScoring() override = default;
78 
79   StringRef getPassName() const override {
80     return "Register Allocation Pass Scoring";
81   }
82 
83   /// RegAllocReward analysis usage.
84   void getAnalysisUsage(AnalysisUsage &AU) const override {
85     AU.setPreservesAll();
86     AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
87     AU.addRequired<MachineBlockFrequencyInfo>();
88     AU.addRequired<AAResultsWrapperPass>();
89     MachineFunctionPass::getAnalysisUsage(AU);
90   }
91 
92   /// Performs this pass
93   bool runOnMachineFunction(MachineFunction &) override;
94 };
95 
96 char RegAllocScoring::ID = 0;
97 FunctionPass *createRegAllocScoringPass() { return new RegAllocScoring(); }
98 
99 } // namespace llvm
100 
101 INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
102                 "Register Allocation Scoring Pass", false, false)
103 
104 // ===================================
105 // Common ML Advisor declarations
106 // ===================================
107 #if defined(LLVM_HAVE_TF_AOT) || defined(LLVM_HAVE_TF_API)
108 namespace {
109 // This is the maximum number of interfererring ranges. That's the number of
110 // distinct AllocationOrder values, which comes from MCRegisterClass::RegsSize.
111 // For X86, that's 32.
112 // TODO: find a way to get this, statically, in a programmatic way.
113 static const int64_t MaxInterferences = 32;
114 
115 // Logically, we can think of the feature set given to the evaluator as a 2D
116 // matrix. The rows are the features (see next). The columns correspond to the
117 // interferences. We treat the candidate virt reg as an 'interference', too, as
118 // its feature set is the same as that of the interferring ranges. So we'll have
119 // MaxInterferences + 1 columns and by convention, we will use the last column
120 // for the virt reg seeking allocation.
121 static const int64_t CandidateVirtRegPos = MaxInterferences;
122 static const int64_t NumberOfInterferences = CandidateVirtRegPos + 1;
123 
124 // Most features are as described above, so we'll reuse this vector in defining
125 // them.
126 static const std::vector<int64_t> PerLiveRangeShape{1, NumberOfInterferences};
127 
128 // --------------
129 // Features table
130 // --------------
131 // For each interfering live range (incl. the candidate) we collect a number of
132 // features. However, because the features are of different types (and because
133 // of ML best practices), we organize the tensors per feature, not per
134 // candidate. Each such tensor has a scalar value corresponding to the
135 // interferring live range at that position, in the order in AllocationOrder.
136 // The last position corresponds to the virt reg seeking allocation.
137 // Exception to all that is the progression feature, which is just a scalar (see
138 // its documentation for details).
139 // Note on naming: the "_by_max" are normalized using the largest value of that
140 // tensor, as observed in the current decision making stage (i.e. for the
141 // current call to the advisor's tryFindEvictionCandidate)
142 //
143 // The feature list format: type, name, shape, documentation.
144 // Note: we can really just use int64 and float, hence the modeling of some
145 // bools as int64 values.
146 #define RA_EVICT_FEATURES_LIST(M)                                              \
147   M(int64_t, mask, PerLiveRangeShape,                                          \
148     "boolean values, 0 for unavailable candidates (i.e. if a position is 0, "  \
149     "it "                                                                      \
150     "can't be evicted)")                                                       \
151   M(int64_t, is_free, PerLiveRangeShape,                                       \
152     "boolean values, 1 if this phys reg is actually free (no interferences)")  \
153   M(float, nr_urgent, PerLiveRangeShape,                                       \
154     "number of 'urgent' intervals, normalized. Urgent are those that are OK "  \
155     "to break cascades")                                                       \
156   M(float, nr_broken_hints, PerLiveRangeShape,                                 \
157     "if this position were evicted, how many broken hints would there be")     \
158   M(int64_t, is_hint, PerLiveRangeShape,                                       \
159     "is this a preferred phys reg for the candidate")                          \
160   M(int64_t, is_local, PerLiveRangeShape,                                      \
161     "is this live range local to a basic block")                               \
162   M(float, nr_rematerializable, PerLiveRangeShape,                             \
163     "nr rematerializable ranges")                                              \
164   M(float, nr_defs_and_uses, PerLiveRangeShape,                                \
165     "bb freq - weighed nr defs and uses")                                      \
166   M(float, weighed_reads_by_max, PerLiveRangeShape,                            \
167     "bb freq - weighed nr of reads, normalized")                               \
168   M(float, weighed_writes_by_max, PerLiveRangeShape,                           \
169     "bb feq - weighed nr of writes, normalized")                               \
170   M(float, weighed_read_writes_by_max, PerLiveRangeShape,                      \
171     "bb freq - weighed nr of uses that are both read and writes, normalized")  \
172   M(float, weighed_indvars_by_max, PerLiveRangeShape,                          \
173     "bb freq - weighed nr of uses that are indvars, normalized")               \
174   M(float, hint_weights_by_max, PerLiveRangeShape,                             \
175     "bb freq - weighed nr of uses that are hints, normalized")                 \
176   M(float, start_bb_freq_by_max, PerLiveRangeShape,                            \
177     "the freq in the start block, normalized")                                 \
178   M(float, end_bb_freq_by_max, PerLiveRangeShape,                              \
179     "freq of end block, normalized")                                           \
180   M(float, hottest_bb_freq_by_max, PerLiveRangeShape,                          \
181     "hottest BB freq, normalized")                                             \
182   M(float, liverange_size, PerLiveRangeShape,                                  \
183     "size (instr index diff) of the LR")                                       \
184   M(float, use_def_density, PerLiveRangeShape,                                 \
185     "the max weight, as computed by the manual heuristic")                     \
186   M(int64_t, max_stage, PerLiveRangeShape,                                     \
187     "largest stage of an interval in this LR")                                 \
188   M(int64_t, min_stage, PerLiveRangeShape,                                     \
189     "lowest stage of an interval in this LR")                                  \
190   M(float, progress, {1}, "ratio of current queue size to initial size")
191 
192 // The model learns to pick one of the mask == 1 interferences. This is the name
193 // of the output tensor.
194 // The contract with the model is that the output will be guaranteed to be to a
195 // mask == 1 position.
196 const char *const DecisionName = "index_to_evict";
197 
198 // Named features index.
199 enum FeatureIDs {
200 #define _FEATURE_IDX(_, name, __, ___) name,
201   RA_EVICT_FEATURES_LIST(_FEATURE_IDX)
202 #undef _FEATURE_IDX
203       FeatureCount
204 };
205 
206 // The ML advisor will typically have a sparse input to the evaluator, because
207 // various phys regs won't be available. It's easier (maintenance-wise) to
208 // bulk-reset the state of the evaluator each time we are about to use it again.
209 template <typename T> size_t getTotalSize(const std::vector<int64_t> &Shape) {
210   size_t Ret = sizeof(T);
211   for (const auto V : Shape)
212     Ret *= V;
213   return Ret;
214 }
215 
216 void resetInputs(MLModelRunner &Runner) {
217 #define _RESET(TYPE, NAME, SHAPE, __)                                          \
218   std::memset(Runner.getTensorUntyped(FeatureIDs::NAME), 0,                    \
219               getTotalSize<TYPE>(SHAPE));
220   RA_EVICT_FEATURES_LIST(_RESET)
221 #undef _RESET
222 }
223 
224 using CandidateRegList =
225     std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
226 using FeaturesListNormalizer = std::array<float, FeatureIDs::FeatureCount>;
227 
228 /// The ML evictor (commonalities between release and development mode)
229 class MLEvictAdvisor : public RegAllocEvictionAdvisor {
230 public:
231   MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
232                  MLModelRunner *Runner, const MachineBlockFrequencyInfo &MBFI,
233                  const MachineLoopInfo &Loops);
234 
235 protected:
236   const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
237     return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
238   }
239 
240   // The assumption is that if the Runner could not be constructed, we emit-ed
241   // error, and we shouldn't be asking for it here.
242   const MLModelRunner &getRunner() const { return *Runner; }
243 
244   /// This just calls Evaluate on the Runner, but in the development mode case,
245   /// if we're just capturing the log of the default advisor, it needs to call
246   /// the latter instead, so we need to pass all the necessary parameters for
247   /// it. In the development case, it will also log.
248   virtual int64_t tryFindEvictionCandidatePosition(
249       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
250       uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const;
251 
252   /// Load the features of the given VirtReg (allocated or not) at column Pos,
253   /// but if  that can't be evicted, return false instead.
254   bool
255   loadInterferenceFeatures(LiveInterval &VirtReg, MCRegister PhysReg,
256                            bool IsHint, const SmallVirtRegSet &FixedRegisters,
257                            std::array<float, FeatureIDs::FeatureCount> &Largest,
258                            size_t Pos) const;
259 
260 private:
261   static float getInitialQueueSize(const MachineFunction &MF);
262 
263   MCRegister tryFindEvictionCandidate(
264       LiveInterval &VirtReg, const AllocationOrder &Order,
265       uint8_t CostPerUseLimit,
266       const SmallVirtRegSet &FixedRegisters) const override;
267 
268   void extractFeatures(const SmallVectorImpl<LiveInterval *> &Intervals,
269                        std::array<float, FeatureIDs::FeatureCount> &Largest,
270                        size_t Pos, int64_t IsHint, int64_t LocalIntfsCount,
271                        float NrUrgent) const;
272 
273   // Point-in-time: we didn't learn this, so we always delegate to the default.
274   bool canEvictHintInterference(
275       LiveInterval &VirtReg, MCRegister PhysReg,
276       const SmallVirtRegSet &FixedRegisters) const override {
277     return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
278                                                         FixedRegisters);
279   }
280 
281   // Hold on to a default advisor for:
282   // 1) the implementation of canEvictHintInterference, because we didn't learn
283   // that nuance yet;
284   // 2) for bootstrapping (logging) in the development mode case.
285   const DefaultEvictionAdvisor DefaultAdvisor;
286   MLModelRunner *const Runner;
287   const MachineBlockFrequencyInfo &MBFI;
288   const MachineLoopInfo &Loops;
289 
290   // Indices of those features we don't want to normalize.
291   // This could be static and shared, but its initialization is non-trivial.
292   std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
293   const float InitialQSize;
294 };
295 
296 // ===================================
297 // Release (AOT) - specifics
298 // ===================================
299 #ifdef LLVM_HAVE_TF_AOT
300 const std::array<std::string, FeatureIDs::FeatureCount> FeatureNames{
301 #define _GETNAME(_, NAME, __, ___) #NAME,
302     RA_EVICT_FEATURES_LIST(_GETNAME)
303 #undef _GETNAME
304 };
305 
306 class ReleaseModeEvictionAdvisorAnalysis final
307     : public RegAllocEvictionAdvisorAnalysis {
308 public:
309   ReleaseModeEvictionAdvisorAnalysis()
310       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {}
311   // support for isa<> and dyn_cast.
312   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
313     return R->getAdvisorMode() == AdvisorMode::Release;
314   }
315 
316 private:
317   void getAnalysisUsage(AnalysisUsage &AU) const override {
318     AU.addRequired<MachineBlockFrequencyInfo>();
319     AU.addRequired<MachineLoopInfo>();
320     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
321   }
322 
323   std::unique_ptr<RegAllocEvictionAdvisor>
324   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
325     if (!Runner)
326       Runner = std::make_unique<ReleaseModeModelRunner<RegallocEvictModel>>(
327           MF.getFunction().getContext(), FeatureNames, DecisionName);
328     return std::make_unique<MLEvictAdvisor>(
329         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
330         getAnalysis<MachineLoopInfo>());
331   }
332   std::unique_ptr<ReleaseModeModelRunner<RegallocEvictModel>> Runner;
333 };
334 #endif // LLVM_HAVE_TF_AOT
335 
336 // ===================================
337 // Development mode-specifics
338 // ===================================
339 //
340 // Features we log
341 #ifdef LLVM_HAVE_TF_API
342 #define _DECL_FEATURES(type, name, shape, _)                                   \
343   TensorSpec::createSpec<type>(#name, shape),
344 
345 static const std::vector<TensorSpec> InputFeatures{
346     {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)},
347 };
348 #undef _DECL_FEATURES
349 static const TensorSpec Output =
350     TensorSpec::createSpec<int64_t>(DecisionName, {1});
351 static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
352 
353 // Features we bind on the model. The tensor names have a prefix, and we also
354 // need to include some tensors that are expected to be present by the training
355 // algo.
356 // TODO: can we just get rid of these?
357 #define _DECL_TRAIN_FEATURES(type, name, shape, _)                             \
358   TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
359 
360 static const std::vector<TensorSpec> TrainingInputFeatures{
361     {RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
362          TensorSpec::createSpec<float>("action_discount", {1}),
363      TensorSpec::createSpec<int32_t>("action_step_type", {1}),
364      TensorSpec::createSpec<float>("action_reward", {1})}};
365 #undef _DECL_TRAIN_FEATURES
366 
367 class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
368 public:
369   DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
370                               MLModelRunner *Runner,
371                               const MachineBlockFrequencyInfo &MBFI,
372                               const MachineLoopInfo &Loops, Logger *Log)
373       : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
374 
375 private:
376   int64_t tryFindEvictionCandidatePosition(
377       LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
378       uint8_t CostPerUseLimit,
379       const SmallVirtRegSet &FixedRegisters) const override;
380 
381   Logger *const Log;
382 };
383 
384 class DevelopmentModeEvictionAdvisorAnalysis final
385     : public RegAllocEvictionAdvisorAnalysis {
386 public:
387   DevelopmentModeEvictionAdvisorAnalysis()
388       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {}
389   // support for isa<> and dyn_cast.
390   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
391     return R->getAdvisorMode() == AdvisorMode::Development;
392   }
393 
394   /// get the logger for the given function, or nullptr if we didn't collect
395   /// one. This is used to inject the score by the RegAllocScoring pass.
396   Logger *getLogger(const MachineFunction &MF) const {
397     auto I = LogMap.find(MF.getName());
398     if (I == LogMap.end())
399       return nullptr;
400     return I->second.get();
401   }
402 
403 private:
404   void getAnalysisUsage(AnalysisUsage &AU) const override {
405     AU.addRequired<MachineBlockFrequencyInfo>();
406     AU.addRequired<MachineLoopInfo>();
407     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
408   }
409 
410   // Save all the logs (when requested).
411   bool doFinalization(Module &M) override {
412     if (TrainingLog.empty())
413       return false;
414     std::error_code EC;
415     auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
416     if (EC) {
417       M.getContext().emitError(EC.message() + ":" + TrainingLog);
418       return false;
419     }
420     Logger::flushLogs(*OS, LogMap);
421     return false;
422   }
423 
424   std::unique_ptr<RegAllocEvictionAdvisor>
425   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
426     LLVMContext &Ctx = MF.getFunction().getContext();
427     if (ModelUnderTraining.empty() && TrainingLog.empty()) {
428       Ctx.emitError("Regalloc development mode should be requested with at "
429                     "least logging enabled and/or a training model");
430       return nullptr;
431     }
432     if (!Runner) {
433       if (ModelUnderTraining.empty())
434         Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
435       else
436         Runner = ModelUnderTrainingRunner::createAndEnsureValid(
437             Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
438       if (!Runner) {
439         Ctx.emitError("Regalloc: could not set up the model runner");
440         return nullptr;
441       }
442     }
443 
444     Logger *Log = nullptr;
445     if (!TrainingLog.empty()) {
446       std::vector<LoggedFeatureSpec> LFS;
447       for (const auto &FS : InputFeatures)
448         LFS.push_back({FS, None});
449       if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
450         if (MUTR->outputLoggedFeatureSpecs().size() > 1)
451           append_range(LFS, drop_begin(MUTR->outputLoggedFeatureSpecs()));
452       // We always log the output; in particular, if we're not evaluating, we
453       // don't have an output spec json file. That's why we handle the
454       // 'normal' output separately.
455       LFS.push_back({Output, None});
456       auto I = LogMap.insert(std::make_pair(
457           MF.getFunction().getName(),
458           std::make_unique<Logger>(LFS, Reward, /*IncludeReward*/ true)));
459       assert(I.second);
460       Log = I.first->second.get();
461     }
462     return std::make_unique<DevelopmentModeEvictAdvisor>(
463         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
464         getAnalysis<MachineLoopInfo>(), Log);
465   }
466 
467   std::unique_ptr<MLModelRunner> Runner;
468   StringMap<std::unique_ptr<Logger>> LogMap;
469 };
470 #endif //#ifdef LLVM_HAVE_TF_API
471 } // namespace
472 
473 float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
474   auto &MRI = MF.getRegInfo();
475   float Ret = 0.0;
476   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
477     Register Reg = Register::index2VirtReg(I);
478     if (MRI.reg_nodbg_empty(Reg))
479       continue;
480     ++Ret;
481   }
482   return Ret;
483 }
484 
485 MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
486                                MLModelRunner *Runner,
487                                const MachineBlockFrequencyInfo &MBFI,
488                                const MachineLoopInfo &Loops)
489     : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
490       Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
491       InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
492   assert(this->Runner);
493   DoNotNormalize.set(FeatureIDs::mask);
494   DoNotNormalize.set(FeatureIDs::is_free);
495   DoNotNormalize.set(FeatureIDs::is_hint);
496   DoNotNormalize.set(FeatureIDs::is_local);
497   DoNotNormalize.set(FeatureIDs::min_stage);
498   DoNotNormalize.set(FeatureIDs::max_stage);
499   DoNotNormalize.set(FeatureIDs::progress);
500 }
501 
502 int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
503     LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
504     const SmallVirtRegSet &) const {
505   int64_t Ret = Runner->evaluate<int64_t>();
506   assert(Ret >= 0);
507   assert(Ret <= CandidateVirtRegPos);
508   return Ret;
509 }
510 
511 bool MLEvictAdvisor::loadInterferenceFeatures(
512     LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
513     const SmallVirtRegSet &FixedRegisters, FeaturesListNormalizer &Largest,
514     size_t Pos) const {
515   // It is only possible to evict virtual register interference.
516   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
517     // leave unavailable
518     return false;
519   }
520 
521   const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
522   int64_t LocalIntfs = 0;
523   float NrUrgent = 0.0f;
524 
525   // The cascade tracking is the same as in the default advisor
526   unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
527 
528   SmallVector<LiveInterval *, MaxInterferences> InterferingIntervals;
529   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
530     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
531     // Different from the default heuristic, we don't make any assumptions about
532     // what having more than 10 results in the query may mean.
533     const auto &IFIntervals = Q.interferingVRegs();
534     if (IFIntervals.empty() && InterferingIntervals.empty())
535       continue;
536     InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
537     for (LiveInterval *Intf : reverse(IFIntervals)) {
538       assert(Register::isVirtualRegister(Intf->reg()) &&
539              "Only expecting virtual register interference from query");
540       // This is the same set of legality checks as in the default case: don't
541       // try to evict fixed regs or 'done' ones. Also don't break cascades,
542       // except in the urgent case, with the same nuances used in the default
543       // heuristic.
544       // We could try sharing this between the advisors, but it may end up
545       // more complex than it is right now.
546       if (FixedRegisters.count(Intf->reg()))
547         return false;
548       if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
549         return false;
550       bool Urgent =
551           !VirtReg.isSpillable() &&
552           (Intf->isSpillable() ||
553            RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
554                RegClassInfo.getNumAllocatableRegs(
555                    MRI->getRegClass(Intf->reg())));
556       // Only evict older cascades or live ranges without a cascade.
557       unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
558       if (Cascade <= IntfCascade) {
559         if (!Urgent)
560           return false;
561         ++NrUrgent;
562       }
563 
564       LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
565                      (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
566     }
567   }
568   // OK, so if we made it this far, this LR is an eviction candidate, load its
569   // features.
570   extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
571                   NrUrgent);
572   return true;
573 }
574 
575 MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
576     LiveInterval &VirtReg, const AllocationOrder &Order,
577     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
578   auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
579   if (!MaybeOrderLimit)
580     return MCRegister::NoRegister;
581   unsigned OrderLimit = *MaybeOrderLimit;
582 
583   // The heuristic sets initial costs such as, if CostPerUseLimit is
584   // max<uint8_t>, then any of the costs of the legally-evictable intervals
585   // would be lower. When that happens, one of those will be selected.
586   // Therefore, we allow the candidate be selected, unless the candidate is
587   // unspillable, in which case it would be incorrect to not find a register for
588   // it.
589   const bool MustFindEviction =
590       (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
591   // Number of available candidates - if 0, no need to continue.
592   size_t Available = 0;
593   // Make sure we don't have leftover partial state from an attempt where we had
594   // no available candidates and bailed out early.
595   resetInputs(*Runner);
596 
597   // Track the index->register mapping because AllocationOrder doesn't do that
598   // and we'd have to scan it.
599   // Also track their mask, to write asserts/debug.
600   CandidateRegList Regs;
601   Regs.fill({0, false});
602 
603   // Track the largest value of features seen during this eviction session. We
604   // only normalize (some of) the float features, but it's just simpler to
605   // dimension 'Largest' to all the features, especially since we have the
606   // 'DoNotNormalize' list.
607   FeaturesListNormalizer Largest;
608   Largest.fill(0.0);
609 
610   // Same overal idea as in the default eviction policy - we visit the values of
611   // AllocationOrder one at a time. If it's not legally available, we mask off
612   // the corresponding feature column (==do nothing because we already reset all
613   // the features to 0)
614   // Use Pos to capture the column we load features at - in AllocationOrder
615   // order.
616   size_t Pos = 0;
617   for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
618        ++I, ++Pos) {
619     MCRegister PhysReg = *I;
620     Regs[Pos] = std::make_pair(PhysReg, true);
621     assert(PhysReg);
622     if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
623       Regs[Pos].second = false;
624       continue;
625     }
626     if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
627                                  Largest, Pos)) {
628       ++Available;
629       Regs[Pos].second = true;
630     }
631   }
632   if (Available == 0) {
633     // Nothing to decide, nothing to learn.
634     assert(!MustFindEviction);
635     return MCRegister::NoRegister;
636   }
637   // If we must find eviction, the candidate should be masked out of the
638   // decision making process.
639   Regs[CandidateVirtRegPos].second = !MustFindEviction;
640   if (!MustFindEviction)
641     extractFeatures(SmallVector<LiveInterval *, 1>(1, &VirtReg), Largest,
642                     CandidateVirtRegPos, /*IsHint*/ 0, /*LocalIntfsCount*/ 0,
643                     /*NrUrgent*/ 0.0);
644   assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
645                                "nothing to allocate initially.");
646   // Normalize the features.
647   for (auto &V : Largest)
648     V = V ? V : 1.0;
649   for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
650        ++FeatureIndex) {
651     if (DoNotNormalize.test(FeatureIndex))
652       continue;
653     for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
654       Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
655     }
656   }
657   *Runner->getTensor<float>(FeatureIDs::progress) =
658       static_cast<float>(RA.getQueueSize()) / InitialQSize;
659 
660   // Get a decision.
661   size_t CandidatePos = tryFindEvictionCandidatePosition(
662       VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
663   // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
664   // Regs[CandidatePos].second)
665   assert(Regs[CandidatePos].second);
666   if (CandidatePos == CandidateVirtRegPos) {
667     assert(!MustFindEviction);
668     return MCRegister::NoRegister;
669   }
670   return Regs[CandidatePos].first;
671 }
672 
673 // Overall, this currently mimics what we do for weight calculation, but instead
674 // of accummulating the various features, we keep them separate.
675 void MLEvictAdvisor::extractFeatures(
676     const SmallVectorImpl<LiveInterval *> &Intervals,
677     std::array<float, FeatureIDs::FeatureCount> &Largest, size_t Pos,
678     int64_t IsHint, int64_t LocalIntfsCount, float NrUrgent) const {
679   int64_t NrDefsAndUses = 0;
680   int64_t NrBrokenHints = 0;
681   float R = 0;
682   float W = 0;
683   float RW = 0;
684   float IndVarUpdates = 0;
685   float HintWeights = 0.0;
686   float StartBBFreq = 0.0;
687   float EndBBFreq = 0.0;
688   float HottestBlockFreq = 0.0;
689   int32_t NrRematerializable = 0;
690   float TotalWeight = 0.0;
691 
692   SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
693   SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
694   int64_t MaxStage = 0;
695   int64_t MinStage =
696       Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
697 
698   for (const auto *L : Intervals) {
699     const LiveInterval &LI = *L;
700     MaxStage = std::max<int64_t>(
701         MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
702     MinStage = std::min<int64_t>(
703         MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
704 
705     TotalWeight = std::max(TotalWeight, LI.weight());
706 
707     if (LI.beginIndex() < StartSI)
708       StartSI = LI.beginIndex();
709 
710     if (LI.endIndex() > EndSI)
711       EndSI = LI.endIndex();
712 
713     SmallPtrSet<MachineInstr *, 8> Visited;
714     const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
715     NrBrokenHints += VRM->hasPreferredPhys(LI.reg());
716 
717     for (MachineRegisterInfo::reg_instr_nodbg_iterator
718              I = MRI->reg_instr_nodbg_begin(LI.reg()),
719              E = MRI->reg_instr_nodbg_end();
720          I != E;) {
721       MachineInstr *MI = &*(I++);
722 
723       ++NrDefsAndUses;
724       if (!Visited.insert(MI).second)
725         continue;
726 
727       if (MI->isIdentityCopy() || MI->isImplicitDef())
728         continue;
729 
730       bool Reads, Writes;
731       std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
732 
733       float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
734       if (Freq > HottestBlockFreq)
735         HottestBlockFreq = Freq;
736       R += (Reads && !Writes) * Freq;
737       W += (!Reads && Writes) * Freq;
738       RW += (Reads && Writes) * Freq;
739 
740       auto *MBB = MI->getParent();
741       auto *Loop = Loops.getLoopFor(MBB);
742       bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
743 
744       if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
745         IndVarUpdates += Freq;
746 
747       if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
748         HintWeights += Freq;
749     }
750     NrRematerializable += VirtRegAuxInfo::isRematerializable(
751         LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
752   }
753   size_t Size = 0;
754   if (!Intervals.empty()) {
755     StartBBFreq =
756         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
757     if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
758       EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
759     EndBBFreq =
760         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
761     Size = StartSI.distance(EndSI);
762   }
763   // Set the features at the column 'Pos'.
764 #define SET(ID, TYPE, VAL)                                                     \
765   do {                                                                         \
766     Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL);     \
767     if (!DoNotNormalize.test(FeatureIDs::ID))                                  \
768       Largest[FeatureIDs::ID] =                                                \
769           std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL));          \
770   } while (false)
771   SET(mask, int64_t, 1);
772   SET(is_free, int64_t, Intervals.empty());
773   SET(nr_urgent, float, NrUrgent);
774   SET(nr_broken_hints, float, NrBrokenHints);
775   SET(is_hint, int64_t, IsHint);
776   SET(is_local, int64_t, LocalIntfsCount);
777   SET(nr_rematerializable, float, NrRematerializable);
778   SET(nr_defs_and_uses, float, NrDefsAndUses);
779   SET(weighed_reads_by_max, float, R);
780   SET(weighed_writes_by_max, float, W);
781   SET(weighed_read_writes_by_max, float, RW);
782   SET(weighed_indvars_by_max, float, IndVarUpdates);
783   SET(hint_weights_by_max, float, HintWeights);
784   SET(start_bb_freq_by_max, float, StartBBFreq);
785   SET(end_bb_freq_by_max, float, EndBBFreq);
786   SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
787   SET(liverange_size, float, Size);
788   SET(use_def_density, float, TotalWeight);
789   SET(max_stage, int64_t, MaxStage);
790   SET(min_stage, int64_t, MinStage);
791 #undef SET
792 }
793 
794 // Development mode-specific implementations
795 #ifdef LLVM_HAVE_TF_API
796 RegAllocEvictionAdvisorAnalysis *llvm::createDevelopmentModeAdvisor() {
797   return new DevelopmentModeEvictionAdvisorAnalysis();
798 }
799 
800 int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
801     LiveInterval &VirtReg, const AllocationOrder &Order, unsigned OrderLimit,
802     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
803   int64_t Ret = 0;
804   if (isa<ModelUnderTrainingRunner>(getRunner())) {
805     Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
806         VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
807   } else {
808     MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
809         VirtReg, Order, CostPerUseLimit, FixedRegisters);
810     // Find the index of the selected PhysReg. We need it for logging, otherwise
811     // this is wasted cycles (but so would starting development mode without a
812     // model nor logging)
813     if (!PhysReg)
814       Ret = CandidateVirtRegPos;
815     else
816       for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
817            I != E; ++I, ++Ret)
818         if (*I == PhysReg)
819           break;
820   }
821   if (TrainingLog.empty())
822     return Ret;
823   size_t CurrentFeature = 0;
824   for (; CurrentFeature < FeatureIDs::FeatureCount; ++CurrentFeature) {
825     Log->logSpecifiedTensorValue(
826         CurrentFeature, reinterpret_cast<const char *>(
827                             getRunner().getTensorUntyped(CurrentFeature)));
828   }
829   if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
830     for (size_t I = 1; I < MUTR->outputLoggedFeatureSpecs().size();
831          ++I, ++CurrentFeature)
832       Log->logSpecifiedTensorValue(
833           CurrentFeature,
834           reinterpret_cast<const char *>(
835               MUTR->lastEvaluationResult()->getUntypedTensorValue(I)));
836   // The output is right after the features and the extra outputs
837   Log->logInt64Value(CurrentFeature, &Ret);
838   return Ret;
839 }
840 
841 bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
842   if (auto *DevModeAnalysis = dyn_cast<DevelopmentModeEvictionAdvisorAnalysis>(
843           &getAnalysis<RegAllocEvictionAdvisorAnalysis>()))
844     if (auto *Log = DevModeAnalysis->getLogger(MF))
845       Log->logFloatFinalReward(static_cast<float>(
846           calculateRegAllocScore(
847               MF, getAnalysis<MachineBlockFrequencyInfo>(),
848               getAnalysis<AAResultsWrapperPass>().getAAResults())
849               .getScore()));
850 
851   return false;
852 }
853 #endif // #ifdef LLVM_HAVE_TF_API
854 
855 // Release mode specific implementations
856 #if defined LLVM_HAVE_TF_AOT
857 RegAllocEvictionAdvisorAnalysis *llvm::createReleaseModeAdvisor() {
858   return new ReleaseModeEvictionAdvisorAnalysis();
859 }
860 #endif // defined(LLVM_HAVE_TF_AOT)
861 #endif // defined(LLVM_HAVE_TF_AOT) || defined(LLVM_HAVE_TF_API)
862 
863 // In all cases except development mode, we don't need scoring.
864 #if !defined(LLVM_HAVE_TF_API)
865 bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
866 #endif
867