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