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