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