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