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