[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / lib / CodeGen / MLRegallocEvictAdvisor.cpp
blob17f9e3ede639a2acee87e2811d87d5644270c400
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
11 //===----------------------------------------------------------------------===//
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 #include "llvm/Analysis/Utils/TrainingLogger.h"
22 #endif
23 #include "llvm/Analysis/ReleaseModeModelRunner.h"
24 #include "llvm/CodeGen/CalcSpillWeights.h"
25 #include "llvm/CodeGen/LiveRegMatrix.h"
26 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/RegisterClassInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/PassRegistry.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
39 #include <array>
40 #include <memory>
42 using namespace llvm;
44 #define DEBUG_TYPE "ml-regalloc"
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
54 // Options that only make sense in development mode
55 #ifdef LLVM_HAVE_TF_API
56 #include "RegAllocScore.h"
57 #include "llvm/Analysis/Utils/TFUtils.h"
59 static cl::opt<std::string> TrainingLog(
60 "regalloc-training-log", cl::Hidden,
61 cl::desc("Training log for the register allocator eviction model"));
63 static cl::opt<std::string> ModelUnderTraining(
64 "regalloc-model", cl::Hidden,
65 cl::desc("The model being trained for register allocation eviction"));
67 #endif // #ifdef LLVM_HAVE_TF_API
69 extern cl::opt<unsigned> EvictInterferenceCutoff;
71 /// The score injection pass.
72 /// This pass calculates the score for a function and inserts it in the log, but
73 /// this happens only in development mode. It's a no-op otherwise.
74 namespace llvm {
75 class RegAllocScoring : public MachineFunctionPass {
76 public:
77 static char ID;
79 RegAllocScoring() : MachineFunctionPass(ID) {
80 initializeRegAllocScoringPass(*PassRegistry::getPassRegistry());
83 ~RegAllocScoring() override = default;
85 StringRef getPassName() const override {
86 return "Register Allocation Pass Scoring";
89 /// RegAllocReward analysis usage.
90 void getAnalysisUsage(AnalysisUsage &AU) const override {
91 AU.setPreservesAll();
92 AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
93 AU.addRequired<MachineBlockFrequencyInfo>();
94 MachineFunctionPass::getAnalysisUsage(AU);
97 /// Performs this pass
98 bool runOnMachineFunction(MachineFunction &) override;
101 char RegAllocScoring::ID = 0;
102 FunctionPass *createRegAllocScoringPass() { return new RegAllocScoring(); }
104 } // namespace llvm
106 INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
107 "Register Allocation Scoring Pass", false, false)
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;
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;
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};
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)
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")
196 // The model learns to pick one of the mask == 1 interferences. This is the
197 // name of the output tensor. The contract with the model is that the output
198 // will be guaranteed to be to a mask == 1 position. Using a macro here to
199 // avoid 'not used' warnings (and keep cond compilation to a minimum)
200 #define DecisionName "index_to_evict"
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
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
213 // again.
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;
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
229 // Per-live interval components that get aggregated into the feature values
230 // that 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;
242 using CandidateRegList =
243 std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
244 using FeaturesListNormalizer =
245 llvm::SmallVector<float, FeatureIDs::FeatureCount>;
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);
254 protected:
255 const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
256 return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
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; }
263 /// This just calls Evaluate on the Runner, but in the development mode
264 /// case, if we're just capturing the log of the default advisor, it needs
265 /// to call the latter instead, so we need to pass all the necessary
266 /// parameters for 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;
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 loadInterferenceFeatures(const LiveInterval &VirtReg, MCRegister PhysReg,
276 bool IsHint,
277 const SmallVirtRegSet &FixedRegisters,
278 llvm::SmallVectorImpl<float> &Largest,
279 size_t Pos) const;
281 private:
282 static float getInitialQueueSize(const MachineFunction &MF);
284 MCRegister tryFindEvictionCandidate(
285 const LiveInterval &VirtReg, const AllocationOrder &Order,
286 uint8_t CostPerUseLimit,
287 const SmallVirtRegSet &FixedRegisters) const override;
289 void extractFeatures(const SmallVectorImpl<const LiveInterval *> &Intervals,
290 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
291 int64_t IsHint, int64_t LocalIntfsCount,
292 float NrUrgent) const;
294 // Point-in-time: we didn't learn this, so we always delegate to the
295 // default.
296 bool canEvictHintInterference(
297 const LiveInterval &VirtReg, MCRegister PhysReg,
298 const SmallVirtRegSet &FixedRegisters) const override {
299 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
300 FixedRegisters);
303 const LIFeatureComponents &
304 getLIFeatureComponents(const LiveInterval &LI) const;
306 // Hold on to a default advisor for:
307 // 1) the implementation of canEvictHintInterference, because we didn't
308 // learn that nuance yet; 2) for bootstrapping (logging) in the development
309 // mode case.
310 const DefaultEvictionAdvisor DefaultAdvisor;
311 MLModelRunner *const Runner;
312 const MachineBlockFrequencyInfo &MBFI;
313 const MachineLoopInfo &Loops;
315 // Indices of those features we don't want to normalize.
316 // This could be static and shared, but its initialization is non-trivial.
317 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
318 const float InitialQSize;
320 using RegID = unsigned;
321 mutable DenseMap<RegID, LIFeatureComponents> CachedFeatures;
324 #define _DECL_FEATURES(type, name, shape, _) \
325 TensorSpec::createSpec<type>(#name, shape),
327 // ===================================
328 // Release (AOT) - specifics
329 // ===================================
330 class ReleaseModeEvictionAdvisorAnalysis final
331 : public RegAllocEvictionAdvisorAnalysis {
332 public:
333 ReleaseModeEvictionAdvisorAnalysis()
334 : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {
335 InputFeatures = {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)};
337 // support for isa<> and dyn_cast.
338 static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
339 return R->getAdvisorMode() == AdvisorMode::Release;
342 private:
343 std::vector<TensorSpec> InputFeatures;
345 void getAnalysisUsage(AnalysisUsage &AU) const override {
346 AU.addRequired<MachineBlockFrequencyInfo>();
347 AU.addRequired<MachineLoopInfo>();
348 RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
351 std::unique_ptr<RegAllocEvictionAdvisor>
352 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
353 if (!Runner)
354 Runner = std::make_unique<ReleaseModeModelRunner<CompiledModelType>>(
355 MF.getFunction().getContext(), InputFeatures, DecisionName);
356 return std::make_unique<MLEvictAdvisor>(
357 MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
358 getAnalysis<MachineLoopInfo>());
360 std::unique_ptr<ReleaseModeModelRunner<CompiledModelType>> Runner;
363 // ===================================
364 // Development mode-specifics
365 // ===================================
367 // Features we log
368 #ifdef LLVM_HAVE_TF_API
369 static const TensorSpec Output =
370 TensorSpec::createSpec<int64_t>(DecisionName, {1});
371 static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
373 // Features we bind on the model. The tensor names have a prefix, and we also
374 // need to include some tensors that are expected to be present by the
375 // training algo.
376 // TODO: can we just get rid of these?
377 #define _DECL_TRAIN_FEATURES(type, name, shape, _) \
378 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
380 class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
381 public:
382 DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
383 MLModelRunner *Runner,
384 const MachineBlockFrequencyInfo &MBFI,
385 const MachineLoopInfo &Loops, Logger *Log)
386 : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
388 private:
389 int64_t tryFindEvictionCandidatePosition(
390 const LiveInterval &VirtReg, const AllocationOrder &Order,
391 unsigned OrderLimit, uint8_t CostPerUseLimit,
392 const SmallVirtRegSet &FixedRegisters) const override;
394 Logger *const Log;
397 class DevelopmentModeEvictionAdvisorAnalysis final
398 : public RegAllocEvictionAdvisorAnalysis {
399 public:
400 DevelopmentModeEvictionAdvisorAnalysis()
401 : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {
402 InputFeatures = {RA_EVICT_FEATURES_LIST(_DECL_FEATURES)};
403 TrainingInputFeatures = {
404 RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
405 TensorSpec::createSpec<float>("action_discount", {1}),
406 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
407 TensorSpec::createSpec<float>("action_reward", {1})};
409 // support for isa<> and dyn_cast.
410 static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
411 return R->getAdvisorMode() == AdvisorMode::Development;
414 /// get the logger for the given function, or nullptr if we didn't collect
415 /// one. This is used to inject the score by the RegAllocScoring pass.
416 Logger *getLogger(const MachineFunction &MF) const {
417 auto I = LogMap.find(MF.getName());
418 if (I == LogMap.end())
419 return nullptr;
420 return I->second.get();
423 private:
424 std::vector<TensorSpec> InputFeatures;
425 std::vector<TensorSpec> TrainingInputFeatures;
427 void getAnalysisUsage(AnalysisUsage &AU) const override {
428 AU.addRequired<MachineBlockFrequencyInfo>();
429 AU.addRequired<MachineLoopInfo>();
430 RegAllocEvictionAdvisorAnalysis::getAnalysisUsage(AU);
433 // Save all the logs (when requested).
434 bool doFinalization(Module &M) override {
435 if (TrainingLog.empty())
436 return false;
437 std::error_code EC;
438 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
439 if (EC) {
440 M.getContext().emitError(EC.message() + ":" + TrainingLog);
441 return false;
443 Logger::flushLogs(*OS, LogMap);
444 return false;
447 std::unique_ptr<RegAllocEvictionAdvisor>
448 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
449 LLVMContext &Ctx = MF.getFunction().getContext();
450 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
451 Ctx.emitError("Regalloc development mode should be requested with at "
452 "least logging enabled and/or a training model");
453 return nullptr;
455 if (!Runner) {
456 if (ModelUnderTraining.empty())
457 Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
458 else
459 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
460 Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
461 if (!Runner) {
462 Ctx.emitError("Regalloc: could not set up the model runner");
463 return nullptr;
467 Logger *Log = nullptr;
468 if (!TrainingLog.empty()) {
469 std::vector<LoggedFeatureSpec> LFS;
470 for (const auto &FS : InputFeatures)
471 LFS.push_back({FS, None});
472 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
473 if (MUTR->outputLoggedFeatureSpecs().size() > 1)
474 append_range(LFS, drop_begin(MUTR->outputLoggedFeatureSpecs()));
475 // We always log the output; in particular, if we're not evaluating, we
476 // don't have an output spec json file. That's why we handle the
477 // 'normal' output separately.
478 LFS.push_back({Output, None});
479 auto I = LogMap.insert(std::make_pair(
480 MF.getFunction().getName(),
481 std::make_unique<Logger>(LFS, Reward, /*IncludeReward*/ true)));
482 assert(I.second);
483 Log = I.first->second.get();
485 return std::make_unique<DevelopmentModeEvictAdvisor>(
486 MF, RA, Runner.get(), getAnalysis<MachineBlockFrequencyInfo>(),
487 getAnalysis<MachineLoopInfo>(), Log);
490 std::unique_ptr<MLModelRunner> Runner;
491 StringMap<std::unique_ptr<Logger>> LogMap;
494 #endif //#ifdef LLVM_HAVE_TF_API
495 } // namespace
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;
506 return Ret;
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);
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;
535 bool MLEvictAdvisor::loadInterferenceFeatures(
536 const LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
537 const SmallVirtRegSet &FixedRegisters,
538 llvm::SmallVectorImpl<float> &Largest, 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;
545 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
546 int64_t LocalIntfs = 0;
547 float NrUrgent = 0.0f;
549 // The cascade tracking is the same as in the default advisor
550 unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
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
556 // about 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;
590 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
591 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
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;
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;
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
614 // for 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
620 // had no available candidates and bailed out early.
621 resetInputs(*Runner);
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});
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(FeatureIDs::FeatureCount, 0.0);
635 // Same overal idea as in the default eviction policy - we visit the values
636 // of AllocationOrder one at a time. If it's not legally available, we mask
637 // off the corresponding feature column (==do nothing because we already
638 // reset all the features to 0) Use Pos to capture the column we load
639 // features at - in AllocationOrder 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;
649 if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
650 Largest, Pos)) {
651 ++Available;
652 Regs[Pos] = std::make_pair(PhysReg, true);
655 if (Available == 0) {
656 // Nothing to decide, nothing to learn.
657 assert(!MustFindEviction);
658 return MCRegister::NoRegister;
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,
667 /*LocalIntfsCount*/ 0,
668 /*NrUrgent*/ 0.0);
669 assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
670 "nothing to allocate initially.");
671 // Normalize the features.
672 for (auto &V : Largest)
673 V = V ? V : 1.0;
674 for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
675 ++FeatureIndex) {
676 if (DoNotNormalize.test(FeatureIndex))
677 continue;
678 for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
679 Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
682 *Runner->getTensor<float>(FeatureIDs::progress) =
683 static_cast<float>(RA.getQueueSize()) / InitialQSize;
685 // Get a decision.
686 size_t CandidatePos = tryFindEvictionCandidatePosition(
687 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
688 // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
689 // Regs[CandidatePos].second)
690 assert(Regs[CandidatePos].second);
691 if (CandidatePos == CandidateVirtRegPos) {
692 assert(!MustFindEviction);
693 return MCRegister::NoRegister;
695 assert(CandidatePos < ValidPosLimit);
696 (void)ValidPosLimit;
697 return Regs[CandidatePos].first;
700 const LIFeatureComponents &
701 MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
702 RegID ID = LI.reg().id();
703 LIFeatureComponents Empty;
704 auto I = CachedFeatures.insert(std::make_pair(ID, Empty));
705 LIFeatureComponents &Ret = I.first->getSecond();
706 if (!I.second)
707 return Ret;
709 SmallPtrSet<MachineInstr *, 8> Visited;
710 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
712 for (MachineRegisterInfo::reg_instr_nodbg_iterator
713 I = MRI->reg_instr_nodbg_begin(LI.reg()),
714 E = MRI->reg_instr_nodbg_end();
715 I != E;) {
716 MachineInstr *MI = &*(I++);
718 ++Ret.NrDefsAndUses;
719 if (!Visited.insert(MI).second)
720 continue;
722 if (MI->isIdentityCopy() || MI->isImplicitDef())
723 continue;
725 bool Reads, Writes;
726 std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
728 float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
729 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
731 Ret.R += (Reads && !Writes) * Freq;
732 Ret.W += (!Reads && Writes) * Freq;
733 Ret.RW += (Reads && Writes) * Freq;
735 auto *MBB = MI->getParent();
736 auto *Loop = Loops.getLoopFor(MBB);
737 bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
739 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
740 Ret.IndVarUpdates += Freq;
742 if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
743 Ret.HintWeights += Freq;
745 Ret.IsRemat = VirtRegAuxInfo::isRematerializable(
746 LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
747 return Ret;
750 // Overall, this currently mimics what we do for weight calculation, but instead
751 // of accummulating the various features, we keep them separate.
752 void MLEvictAdvisor::extractFeatures(
753 const SmallVectorImpl<const LiveInterval *> &Intervals,
754 llvm::SmallVectorImpl<float> &Largest, size_t Pos, int64_t IsHint,
755 int64_t LocalIntfsCount, float NrUrgent) const {
756 int64_t NrDefsAndUses = 0;
757 int64_t NrBrokenHints = 0;
758 double R = 0.0;
759 double W = 0.0;
760 double RW = 0.0;
761 double IndVarUpdates = 0.0;
762 double HintWeights = 0.0;
763 float StartBBFreq = 0.0;
764 float EndBBFreq = 0.0;
765 float HottestBlockFreq = 0.0;
766 int32_t NrRematerializable = 0;
767 float TotalWeight = 0.0;
769 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
770 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
771 int64_t MaxStage = 0;
772 int64_t MinStage =
773 Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
775 for (const auto *L : Intervals) {
776 const LiveInterval &LI = *L;
777 MaxStage = std::max<int64_t>(
778 MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
779 MinStage = std::min<int64_t>(
780 MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
782 TotalWeight = std::max(TotalWeight, LI.weight());
784 if (LI.beginIndex() < StartSI)
785 StartSI = LI.beginIndex();
787 if (LI.endIndex() > EndSI)
788 EndSI = LI.endIndex();
789 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
790 NrBrokenHints += VRM->hasPreferredPhys(LI.reg());
792 NrDefsAndUses += LIFC.NrDefsAndUses;
793 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
794 R += LIFC.R;
795 W += LIFC.W;
796 RW += LIFC.RW;
798 IndVarUpdates += LIFC.IndVarUpdates;
800 HintWeights += LIFC.HintWeights;
801 NrRematerializable += LIFC.IsRemat;
803 size_t Size = 0;
804 if (!Intervals.empty()) {
805 StartBBFreq =
806 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
807 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
808 EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
809 EndBBFreq =
810 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
811 Size = StartSI.distance(EndSI);
813 // Set the features at the column 'Pos'.
814 #define SET(ID, TYPE, VAL) \
815 do { \
816 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
817 if (!DoNotNormalize.test(FeatureIDs::ID)) \
818 Largest[FeatureIDs::ID] = \
819 std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL)); \
820 } while (false)
821 SET(mask, int64_t, 1);
822 SET(is_free, int64_t, Intervals.empty());
823 SET(nr_urgent, float, NrUrgent);
824 SET(nr_broken_hints, float, NrBrokenHints);
825 SET(is_hint, int64_t, IsHint);
826 SET(is_local, int64_t, LocalIntfsCount);
827 SET(nr_rematerializable, float, NrRematerializable);
828 SET(nr_defs_and_uses, float, NrDefsAndUses);
829 SET(weighed_reads_by_max, float, R);
830 SET(weighed_writes_by_max, float, W);
831 SET(weighed_read_writes_by_max, float, RW);
832 SET(weighed_indvars_by_max, float, IndVarUpdates);
833 SET(hint_weights_by_max, float, HintWeights);
834 SET(start_bb_freq_by_max, float, StartBBFreq);
835 SET(end_bb_freq_by_max, float, EndBBFreq);
836 SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
837 SET(liverange_size, float, Size);
838 SET(use_def_density, float, TotalWeight);
839 SET(max_stage, int64_t, MaxStage);
840 SET(min_stage, int64_t, MinStage);
841 #undef SET
844 // Development mode-specific implementations
845 #ifdef LLVM_HAVE_TF_API
846 RegAllocEvictionAdvisorAnalysis *llvm::createDevelopmentModeAdvisor() {
847 return new DevelopmentModeEvictionAdvisorAnalysis();
850 int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
851 const LiveInterval &VirtReg, const AllocationOrder &Order,
852 unsigned OrderLimit, uint8_t CostPerUseLimit,
853 const SmallVirtRegSet &FixedRegisters) const {
854 int64_t Ret = 0;
855 if (isa<ModelUnderTrainingRunner>(getRunner())) {
856 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
857 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
858 } else {
859 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
860 VirtReg, Order, CostPerUseLimit, FixedRegisters);
861 // Find the index of the selected PhysReg. We need it for logging,
862 // otherwise this is wasted cycles (but so would starting development mode
863 // without a model nor logging)
864 if (!PhysReg)
865 Ret = CandidateVirtRegPos;
866 else
867 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
868 I != E; ++I, ++Ret)
869 if (*I == PhysReg)
870 break;
872 if (TrainingLog.empty())
873 return Ret;
874 size_t CurrentFeature = 0;
875 for (; CurrentFeature < FeatureIDs::FeatureCount; ++CurrentFeature) {
876 Log->logSpecifiedTensorValue(
877 CurrentFeature, reinterpret_cast<const char *>(
878 getRunner().getTensorUntyped(CurrentFeature)));
880 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
881 for (size_t I = 1; I < MUTR->outputLoggedFeatureSpecs().size();
882 ++I, ++CurrentFeature)
883 Log->logSpecifiedTensorValue(
884 CurrentFeature,
885 reinterpret_cast<const char *>(
886 MUTR->lastEvaluationResult()->getUntypedTensorValue(I)));
887 // The output is right after the features and the extra outputs
888 Log->logInt64Value(CurrentFeature, &Ret);
889 return Ret;
892 bool RegAllocScoring::runOnMachineFunction(MachineFunction &MF) {
893 if (auto *DevModeAnalysis = dyn_cast<DevelopmentModeEvictionAdvisorAnalysis>(
894 &getAnalysis<RegAllocEvictionAdvisorAnalysis>()))
895 if (auto *Log = DevModeAnalysis->getLogger(MF))
896 Log->logFloatFinalReward(static_cast<float>(
897 calculateRegAllocScore(MF, getAnalysis<MachineBlockFrequencyInfo>())
898 .getScore()));
900 return false;
902 #endif // #ifdef LLVM_HAVE_TF_API
904 RegAllocEvictionAdvisorAnalysis *llvm::createReleaseModeAdvisor() {
905 return new ReleaseModeEvictionAdvisorAnalysis();
908 // In all cases except development mode, we don't need scoring.
909 #if !defined(LLVM_HAVE_TF_API)
910 bool RegAllocScoring::runOnMachineFunction(MachineFunction &) { return false; }
911 #endif