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