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 
315 // ===================================
316 // Release (AOT) - specifics
317 // ===================================
318 #if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
319 const std::array<std::string, FeatureIDs::FeatureCount> FeatureNames{
320 #define _GETNAME(_, NAME, __, ___) #NAME,
321     RA_EVICT_FEATURES_LIST(_GETNAME)
322 #undef _GETNAME
323 };
324 class ReleaseModeEvictionAdvisorAnalysis final
325     : public RegAllocEvictionAdvisorAnalysis {
326 public:
327   ReleaseModeEvictionAdvisorAnalysis()
328       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {}
329   // support for isa<> and dyn_cast.
330   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
331     return R->getAdvisorMode() == AdvisorMode::Release;
332   }
333 
334 private:
335   void getAnalysisUsage(AnalysisUsage &AU) const override {
336     AU.addRequired<MachineBlockFrequencyInfo>();
337     AU.addRequired<MachineLoopInfo>();
338     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
339   }
340 
341   std::unique_ptr<RegAllocEvictionAdvisor>
342   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
343     if (!Runner)
344       Runner = std::make_unique<ReleaseModeModelRunner<RegallocEvictModel>>(
345           MF.getFunction().getContext(), FeatureNames, DecisionName);
346     return std::make_unique<MLEvictAdvisor>(
347         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
348         getAnalysis<MachineLoopInfo>());
349   }
350   std::unique_ptr<ReleaseModeModelRunner<RegallocEvictModel>> Runner;
351 };
352 #endif
353 
354 // ===================================
355 // Development mode-specifics
356 // ===================================
357 //
358 // Features we log
359 #ifdef LLVM_HAVE_TF_API
360 #define _DECL_FEATURES(type, name, shape, _)                                   \
361   TensorSpec::createSpec<type>(#name, shape),
362 
363 static const std::vector<TensorSpec> InputFeatures{
364     {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)},
365 };
366 #undef _DECL_FEATURES
367 static const TensorSpec Output =
368     TensorSpec::createSpec<int64_t>(DecisionName, {1});
369 static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
370 
371 // Features we bind on the model. The tensor names have a prefix, and we also
372 // need to include some tensors that are expected to be present by the training
373 // algo.
374 // TODO: can we just get rid of these?
375 #define _DECL_TRAIN_FEATURES(type, name, shape, _)                             \
376   TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
377 
378 static const std::vector<TensorSpec> TrainingInputFeatures{
379     {RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
380          TensorSpec::createSpec<float>("action_discount", {1}),
381      TensorSpec::createSpec<int32_t>("action_step_type", {1}),
382      TensorSpec::createSpec<float>("action_reward", {1})}};
383 #undef _DECL_TRAIN_FEATURES
384 
385 class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
386 public:
387   DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
388                               MLModelRunner *Runner,
389                               const MachineBlockFrequencyInfo &MBFI,
390                               const MachineLoopInfo &Loops, Logger *Log)
391       : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
392 
393 private:
394   int64_t tryFindEvictionCandidatePosition(
395       const LiveInterval &VirtReg, const AllocationOrder &Order,
396       unsigned OrderLimit, uint8_t CostPerUseLimit,
397       const SmallVirtRegSet &FixedRegisters) const override;
398 
399   Logger *const Log;
400 };
401 
402 class DevelopmentModeEvictionAdvisorAnalysis final
403     : public RegAllocEvictionAdvisorAnalysis {
404 public:
405   DevelopmentModeEvictionAdvisorAnalysis()
406       : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {}
407   // support for isa<> and dyn_cast.
408   static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
409     return R->getAdvisorMode() == AdvisorMode::Development;
410   }
411 
412   /// get the logger for the given function, or nullptr if we didn't collect
413   /// one. This is used to inject the score by the RegAllocScoring pass.
414   Logger *getLogger(const MachineFunction &MF) const {
415     auto I = LogMap.find(MF.getName());
416     if (I == LogMap.end())
417       return nullptr;
418     return I->second.get();
419   }
420 
421 private:
422   void getAnalysisUsage(AnalysisUsage &AU) const override {
423     AU.addRequired<MachineBlockFrequencyInfo>();
424     AU.addRequired<MachineLoopInfo>();
425     RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
426   }
427 
428   // Save all the logs (when requested).
429   bool doFinalization(Module &M) override {
430     if (TrainingLog.empty())
431       return false;
432     std::error_code EC;
433     auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
434     if (EC) {
435       M.getContext().emitError(EC.message() + ":" + TrainingLog);
436       return false;
437     }
438     Logger::flushLogs(*OS, LogMap);
439     return false;
440   }
441 
442   std::unique_ptr<RegAllocEvictionAdvisor>
443   getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
444     LLVMContext &Ctx = MF.getFunction().getContext();
445     if (ModelUnderTraining.empty() && TrainingLog.empty()) {
446       Ctx.emitError("Regalloc development mode should be requested with at "
447                     "least logging enabled and/or a training model");
448       return nullptr;
449     }
450     if (!Runner) {
451       if (ModelUnderTraining.empty())
452         Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
453       else
454         Runner = ModelUnderTrainingRunner::createAndEnsureValid(
455             Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
456       if (!Runner) {
457         Ctx.emitError("Regalloc: could not set up the model runner");
458         return nullptr;
459       }
460     }
461 
462     Logger *Log = nullptr;
463     if (!TrainingLog.empty()) {
464       std::vector<LoggedFeatureSpec> LFS;
465       for (const auto &FS : InputFeatures)
466         LFS.push_back({FS, None});
467       if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
468         if (MUTR->outputLoggedFeatureSpecs().size() > 1)
469           append_range(LFS, drop_begin(MUTR->outputLoggedFeatureSpecs()));
470       // We always log the output; in particular, if we're not evaluating, we
471       // don't have an output spec json file. That's why we handle the
472       // 'normal' output separately.
473       LFS.push_back({Output, None});
474       auto I = LogMap.insert(std::make_pair(
475           MF.getFunction().getName(),
476           std::make_unique<Logger>(LFS, Reward, /*IncludeReward*/ true)));
477       assert(I.second);
478       Log = I.first->second.get();
479     }
480     return std::make_unique<DevelopmentModeEvictAdvisor>(
481         MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
482         getAnalysis<MachineLoopInfo>(), Log);
483   }
484 
485   std::unique_ptr<MLModelRunner> Runner;
486   StringMap<std::unique_ptr<Logger>> LogMap;
487 };
488 #endif //#ifdef LLVM_HAVE_TF_API
489 } // namespace
490 
491 float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
492   auto &MRI = MF.getRegInfo();
493   float Ret = 0.0;
494   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
495     Register Reg = Register::index2VirtReg(I);
496     if (MRI.reg_nodbg_empty(Reg))
497       continue;
498     ++Ret;
499   }
500   return Ret;
501 }
502 
503 MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
504                                MLModelRunner *Runner,
505                                const MachineBlockFrequencyInfo &MBFI,
506                                const MachineLoopInfo &Loops)
507     : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
508       Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
509       InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
510   assert(this->Runner);
511   DoNotNormalize.set(FeatureIDs::mask);
512   DoNotNormalize.set(FeatureIDs::is_free);
513   DoNotNormalize.set(FeatureIDs::is_hint);
514   DoNotNormalize.set(FeatureIDs::is_local);
515   DoNotNormalize.set(FeatureIDs::min_stage);
516   DoNotNormalize.set(FeatureIDs::max_stage);
517   DoNotNormalize.set(FeatureIDs::progress);
518 }
519 
520 int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
521     const LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
522     const SmallVirtRegSet &) const {
523   int64_t Ret = Runner->evaluate<int64_t>();
524   assert(Ret >= 0);
525   assert(Ret <= CandidateVirtRegPos);
526   return Ret;
527 }
528 
529 bool MLEvictAdvisor::loadInterferenceFeatures(
530     const LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
531     const SmallVirtRegSet &FixedRegisters, FeaturesListNormalizer &Largest,
532     size_t Pos) const {
533   // It is only possible to evict virtual register interference.
534   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
535     // leave unavailable
536     return false;
537   }
538 
539   const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
540   int64_t LocalIntfs = 0;
541   float NrUrgent = 0.0f;
542 
543   // The cascade tracking is the same as in the default advisor
544   unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
545 
546   SmallVector<const LiveInterval *, MaxInterferences> InterferingIntervals;
547   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
548     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
549     // Different from the default heuristic, we don't make any assumptions about
550     // what having more than 10 results in the query may mean.
551     const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
552     if (IFIntervals.empty() && InterferingIntervals.empty())
553       continue;
554     if (IFIntervals.size() >= EvictInterferenceCutoff)
555       return false;
556     InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
557     for (const LiveInterval *Intf : reverse(IFIntervals)) {
558       assert(Register::isVirtualRegister(Intf->reg()) &&
559              "Only expecting virtual register interference from query");
560       // This is the same set of legality checks as in the default case: don't
561       // try to evict fixed regs or 'done' ones. Also don't break cascades,
562       // except in the urgent case, with the same nuances used in the default
563       // heuristic.
564       // We could try sharing this between the advisors, but it may end up
565       // more complex than it is right now.
566       if (FixedRegisters.count(Intf->reg()))
567         return false;
568       if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
569         return false;
570       bool Urgent =
571           !VirtReg.isSpillable() &&
572           (Intf->isSpillable() ||
573            RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
574                RegClassInfo.getNumAllocatableRegs(
575                    MRI->getRegClass(Intf->reg())));
576       // Only evict older cascades or live ranges without a cascade.
577       unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
578       if (Cascade <= IntfCascade) {
579         if (!Urgent)
580           return false;
581         ++NrUrgent;
582       }
583 
584       LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
585                      (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
586     }
587   }
588   // OK, so if we made it this far, this LR is an eviction candidate, load its
589   // features.
590   extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
591                   NrUrgent);
592   return true;
593 }
594 
595 MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
596     const LiveInterval &VirtReg, const AllocationOrder &Order,
597     uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
598   auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
599   if (!MaybeOrderLimit)
600     return MCRegister::NoRegister;
601   unsigned OrderLimit = *MaybeOrderLimit;
602 
603   // The heuristic sets initial costs such as, if CostPerUseLimit is
604   // max<uint8_t>, then any of the costs of the legally-evictable intervals
605   // would be lower. When that happens, one of those will be selected.
606   // Therefore, we allow the candidate be selected, unless the candidate is
607   // unspillable, in which case it would be incorrect to not find a register for
608   // it.
609   const bool MustFindEviction =
610       (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
611   // Number of available candidates - if 0, no need to continue.
612   size_t Available = 0;
613   // Make sure we don't have leftover partial state from an attempt where we had
614   // no available candidates and bailed out early.
615   resetInputs(*Runner);
616 
617   // Track the index->register mapping because AllocationOrder doesn't do that
618   // and we'd have to scan it.
619   // Also track their mask, to write asserts/debug.
620   CandidateRegList Regs;
621   Regs.fill({0, false});
622 
623   // Track the largest value of features seen during this eviction session. We
624   // only normalize (some of) the float features, but it's just simpler to
625   // dimension 'Largest' to all the features, especially since we have the
626   // 'DoNotNormalize' list.
627   FeaturesListNormalizer Largest;
628   Largest.fill(0.0);
629 
630   // Same overal idea as in the default eviction policy - we visit the values of
631   // AllocationOrder one at a time. If it's not legally available, we mask off
632   // the corresponding feature column (==do nothing because we already reset all
633   // the features to 0)
634   // Use Pos to capture the column we load features at - in AllocationOrder
635   // order.
636   size_t Pos = 0;
637   for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
638        ++I, ++Pos) {
639     MCRegister PhysReg = *I;
640     assert(!Regs[Pos].second);
641     assert(PhysReg);
642     if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
643       continue;
644     }
645     if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
646                                  Largest, Pos)) {
647       ++Available;
648       Regs[Pos] = std::make_pair(PhysReg, true);
649     }
650   }
651   if (Available == 0) {
652     // Nothing to decide, nothing to learn.
653     assert(!MustFindEviction);
654     return MCRegister::NoRegister;
655   }
656   const size_t ValidPosLimit = Pos;
657   // If we must find eviction, the candidate should be masked out of the
658   // decision making process.
659   Regs[CandidateVirtRegPos].second = !MustFindEviction;
660   if (!MustFindEviction)
661     extractFeatures(SmallVector<const LiveInterval *, 1>(1, &VirtReg), Largest,
662                     CandidateVirtRegPos, /*IsHint*/ 0, /*LocalIntfsCount*/ 0,
663                     /*NrUrgent*/ 0.0);
664   assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
665                                "nothing to allocate initially.");
666   // Normalize the features.
667   for (auto &V : Largest)
668     V = V ? V : 1.0;
669   for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
670        ++FeatureIndex) {
671     if (DoNotNormalize.test(FeatureIndex))
672       continue;
673     for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
674       Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
675     }
676   }
677   *Runner->getTensor<float>(FeatureIDs::progress) =
678       static_cast<float>(RA.getQueueSize()) / InitialQSize;
679 
680   // Get a decision.
681   size_t CandidatePos = tryFindEvictionCandidatePosition(
682       VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
683   // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
684   // Regs[CandidatePos].second)
685   assert(Regs[CandidatePos].second);
686   if (CandidatePos == CandidateVirtRegPos) {
687     assert(!MustFindEviction);
688     return MCRegister::NoRegister;
689   }
690   assert(CandidatePos < ValidPosLimit);
691   (void)ValidPosLimit;
692   return Regs[CandidatePos].first;
693 }
694 
695 const LIFeatureComponents
696 MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
697   LIFeatureComponents Ret;
698   SmallPtrSet<MachineInstr *, 8> Visited;
699   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
700 
701   for (MachineRegisterInfo::reg_instr_nodbg_iterator
702            I = MRI->reg_instr_nodbg_begin(LI.reg()),
703            E = MRI->reg_instr_nodbg_end();
704        I != E;) {
705     MachineInstr *MI = &*(I++);
706 
707     ++Ret.NrDefsAndUses;
708     if (!Visited.insert(MI).second)
709       continue;
710 
711     if (MI->isIdentityCopy() || MI->isImplicitDef())
712       continue;
713 
714     bool Reads, Writes;
715     std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
716 
717     float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
718     Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
719 
720     Ret.R += (Reads && !Writes) * Freq;
721     Ret.W += (!Reads && Writes) * Freq;
722     Ret.RW += (Reads && Writes) * Freq;
723 
724     auto *MBB = MI->getParent();
725     auto *Loop = Loops.getLoopFor(MBB);
726     bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
727 
728     if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
729       Ret.IndVarUpdates += Freq;
730 
731     if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
732       Ret.HintWeights += Freq;
733   }
734   Ret.IsRemat = VirtRegAuxInfo::isRematerializable(
735       LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
736   return Ret;
737 }
738 
739 // Overall, this currently mimics what we do for weight calculation, but instead
740 // of accummulating the various features, we keep them separate.
741 void MLEvictAdvisor::extractFeatures(
742     const SmallVectorImpl<const LiveInterval *> &Intervals,
743     std::array<float, FeatureIDs::FeatureCount> &Largest, size_t Pos,
744     int64_t IsHint, int64_t LocalIntfsCount, float NrUrgent) const {
745   int64_t NrDefsAndUses = 0;
746   int64_t NrBrokenHints = 0;
747   double R = 0.0;
748   double W = 0.0;
749   double RW = 0.0;
750   double IndVarUpdates = 0.0;
751   double HintWeights = 0.0;
752   float StartBBFreq = 0.0;
753   float EndBBFreq = 0.0;
754   float HottestBlockFreq = 0.0;
755   int32_t NrRematerializable = 0;
756   float TotalWeight = 0.0;
757 
758   SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
759   SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
760   int64_t MaxStage = 0;
761   int64_t MinStage =
762       Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
763 
764   for (const auto *L : Intervals) {
765     const LiveInterval &LI = *L;
766     MaxStage = std::max<int64_t>(
767         MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
768     MinStage = std::min<int64_t>(
769         MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
770 
771     TotalWeight = std::max(TotalWeight, LI.weight());
772 
773     if (LI.beginIndex() < StartSI)
774       StartSI = LI.beginIndex();
775 
776     if (LI.endIndex() > EndSI)
777       EndSI = LI.endIndex();
778     const LIFeatureComponents LIFC = getLIFeatureComponents(LI);
779     NrBrokenHints += VRM->hasPreferredPhys(LI.reg());
780 
781     NrDefsAndUses += LIFC.NrDefsAndUses;
782     HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
783     R += LIFC.R;
784     W += LIFC.W;
785     RW += LIFC.RW;
786 
787     IndVarUpdates += LIFC.IndVarUpdates;
788 
789     HintWeights += LIFC.HintWeights;
790     NrRematerializable += LIFC.IsRemat;
791   }
792   size_t Size = 0;
793   if (!Intervals.empty()) {
794     StartBBFreq =
795         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
796     if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
797       EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
798     EndBBFreq =
799         MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
800     Size = StartSI.distance(EndSI);
801   }
802   // Set the features at the column 'Pos'.
803 #define SET(ID, TYPE, VAL)                                                     \
804   do {                                                                         \
805     Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL);     \
806     if (!DoNotNormalize.test(FeatureIDs::ID))                                  \
807       Largest[FeatureIDs::ID] =                                                \
808           std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL));          \
809   } while (false)
810   SET(mask, int64_t, 1);
811   SET(is_free, int64_t, Intervals.empty());
812   SET(nr_urgent, float, NrUrgent);
813   SET(nr_broken_hints, float, NrBrokenHints);
814   SET(is_hint, int64_t, IsHint);
815   SET(is_local, int64_t, LocalIntfsCount);
816   SET(nr_rematerializable, float, NrRematerializable);
817   SET(nr_defs_and_uses, float, NrDefsAndUses);
818   SET(weighed_reads_by_max, float, R);
819   SET(weighed_writes_by_max, float, W);
820   SET(weighed_read_writes_by_max, float, RW);
821   SET(weighed_indvars_by_max, float, IndVarUpdates);
822   SET(hint_weights_by_max, float, HintWeights);
823   SET(start_bb_freq_by_max, float, StartBBFreq);
824   SET(end_bb_freq_by_max, float, EndBBFreq);
825   SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
826   SET(liverange_size, float, Size);
827   SET(use_def_density, float, TotalWeight);
828   SET(max_stage, int64_t, MaxStage);
829   SET(min_stage, int64_t, MinStage);
830 #undef SET
831 }
832 
833 // Development mode-specific implementations
834 #ifdef LLVM_HAVE_TF_API
835 RegAllocEvictionAdvisorAnalysis *llvm::createDevelopmentModeAdvisor() {
836   return new DevelopmentModeEvictionAdvisorAnalysis();
837 }
838 
839 int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
840     const LiveInterval &VirtReg, const AllocationOrder &Order,
841     unsigned OrderLimit, uint8_t CostPerUseLimit,
842     const SmallVirtRegSet &FixedRegisters) const {
843   int64_t Ret = 0;
844   if (isa<ModelUnderTrainingRunner>(getRunner())) {
845     Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
846         VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
847   } else {
848     MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
849         VirtReg, Order, CostPerUseLimit, FixedRegisters);
850     // Find the index of the selected PhysReg. We need it for logging, otherwise
851     // this is wasted cycles (but so would starting development mode without a
852     // model nor logging)
853     if (!PhysReg)
854       Ret = CandidateVirtRegPos;
855     else
856       for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
857            I != E; ++I, ++Ret)
858         if (*I == PhysReg)
859           break;
860   }
861   if (TrainingLog.empty())
862     return Ret;
863   size_t CurrentFeature = 0;
864   for (; CurrentFeature < FeatureIDs::FeatureCount; ++CurrentFeature) {
865     Log->logSpecifiedTensorValue(
866         CurrentFeature, reinterpret_cast<const char *>(
867                             getRunner().getTensorUntyped(CurrentFeature)));
868   }
869   if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
870     for (size_t I = 1; I < MUTR->outputLoggedFeatureSpecs().size();
871          ++I, ++CurrentFeature)
872       Log->logSpecifiedTensorValue(
873           CurrentFeature,
874           reinterpret_cast<const char *>(
875               MUTR->lastEvaluationResult()->getUntypedTensorValue(I)));
876   // The output is right after the features and the extra outputs
877   Log->logInt64Value(CurrentFeature, &Ret);
878   return Ret;
879 }
880 
881 bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
882   if (auto *DevModeAnalysis = dyn_cast<DevelopmentModeEvictionAdvisorAnalysis>(
883           &getAnalysis<RegAllocEvictionAdvisorAnalysis>()))
884     if (auto *Log = DevModeAnalysis->getLogger(MF))
885       Log->logFloatFinalReward(static_cast<float>(
886           calculateRegAllocScore(
887               MF, getAnalysis<MachineBlockFrequencyInfo>(),
888               getAnalysis<AAResultsWrapperPass>().getAAResults())
889               .getScore()));
890 
891   return false;
892 }
893 #endif // #ifdef LLVM_HAVE_TF_API
894 
895 #if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
896 RegAllocEvictionAdvisorAnalysis *llvm::createReleaseModeAdvisor() {
897   return new ReleaseModeEvictionAdvisorAnalysis();
898 }
899 #endif
900 
901 // In all cases except development mode, we don't need scoring.
902 #if !defined(LLVM_HAVE_TF_API)
903 bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
904 #endif
905