LLVM 20.0.0git
MLRegAllocEvictAdvisor.cpp
Go to the documentation of this file.
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"
15#include "RegAllocGreedy.h"
19#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL) || defined(LLVM_HAVE_TFLITE)
23#endif
32#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Module.h"
37#include "llvm/Pass.h"
38#include "llvm/PassRegistry.h"
41
42#include <array>
43#include <bitset>
44#include <memory>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "ml-regalloc"
49
50// Generated header in release (AOT) mode
51#if defined(LLVM_HAVE_TF_AOT_REGALLOCEVICTMODEL)
52#include "RegAllocEvictModel.h"
53using CompiledModelType = RegAllocEvictModel;
54#else
56#endif
57
59 "regalloc-evict-interactive-channel-base", cl::Hidden,
61 "Base file path for the interactive mode. The incoming filename should "
62 "have the name <regalloc-evict-interactive-channel-base>.in, while the "
63 "outgoing name should be "
64 "<regalloc-evict-interactive-channel-base>.out"));
65
67 MaxCascade("mlregalloc-max-cascade", cl::Hidden,
68 cl::desc("The maximum number of times a live range can be "
69 "evicted before preventing it from being evicted"),
70 cl::init(20));
71
72// Options that only make sense in development mode
73#ifdef LLVM_HAVE_TFLITE
74#include "RegAllocScore.h"
76
77static cl::opt<std::string> TrainingLog(
78 "regalloc-training-log", cl::Hidden,
79 cl::desc("Training log for the register allocator eviction model"));
80
81static cl::opt<std::string> ModelUnderTraining(
82 "regalloc-model", cl::Hidden,
83 cl::desc("The model being trained for register allocation eviction"));
84
86 "regalloc-enable-development-features", cl::Hidden,
87 cl::desc("Whether or not to enable features under development for the ML "
88 "regalloc advisor"));
89
90#else
91static const bool EnableDevelopmentFeatures = false;
92#endif // #ifdef LLVM_HAVE_TFLITE
93
94/// The score injection pass.
95/// This pass calculates the score for a function and inserts it in the log, but
96/// this happens only in development mode. It's a no-op otherwise.
97namespace llvm {
99
101public:
102 static char ID;
103
106 }
107
108 ~RegAllocScoring() override = default;
109
110 StringRef getPassName() const override {
111 return "Register Allocation Pass Scoring";
112 }
113
114 /// RegAllocReward analysis usage.
115 void getAnalysisUsage(AnalysisUsage &AU) const override {
116 AU.setPreservesAll();
121 }
122
123 /// Performs this pass
124 bool runOnMachineFunction(MachineFunction &) override;
125};
126
127char RegAllocScoring::ID = 0;
129
130} // namespace llvm
131
132INITIALIZE_PASS(RegAllocScoring, "regallocscoringpass",
133 "Register Allocation Scoring Pass", false, false)
134
135// ===================================
136// Common ML Advisor declarations
137// ===================================
138namespace {
139// The model can only accept a specified number of opcodes and will error it if
140// fed an opcode it hasn't seen before. This constant sets the current cutoff.
141static const int OpcodeValueCutoff = 17716;
142
143// Most features are as described above, so we'll reuse this vector in defining
144// them.
145static const std::vector<int64_t> PerLiveRangeShape{1, NumberOfInterferences};
146
147// --------------
148// Features table
149// --------------
150// For each interfering live range (incl. the candidate) we collect a number of
151// features. However, because the features are of different types (and because
152// of ML best practices), we organize the tensors per feature, not per
153// candidate. Each such tensor has a scalar value corresponding to the
154// interferring live range at that position, in the order in AllocationOrder.
155// The last position corresponds to the virt reg seeking allocation.
156// Exception to all that is the progression feature, which is just a scalar (see
157// its documentation for details).
158// Note on naming: the "_by_max" are normalized using the largest value of that
159// tensor, as observed in the current decision making stage (i.e. for the
160// current call to the advisor's tryFindEvictionCandidate)
161//
162// The feature list format: type, name, shape, documentation.
163// Note: we can really just use int64 and float, hence the modeling of some
164// bools as int64 values.
165#define RA_EVICT_FEATURES_LIST(M) \
166 M(int64_t, mask, PerLiveRangeShape, \
167 "boolean values, 0 for unavailable candidates (i.e. if a position is 0, " \
168 "it " \
169 "can't be evicted)") \
170 M(int64_t, is_free, PerLiveRangeShape, \
171 "boolean values, 1 if this phys reg is actually free (no interferences)") \
172 M(float, nr_urgent, PerLiveRangeShape, \
173 "number of 'urgent' intervals, normalized. Urgent are those that are OK " \
174 "to break cascades") \
175 M(float, nr_broken_hints, PerLiveRangeShape, \
176 "if this position were evicted, how many broken hints would there be") \
177 M(int64_t, is_hint, PerLiveRangeShape, \
178 "is this a preferred phys reg for the candidate") \
179 M(int64_t, is_local, PerLiveRangeShape, \
180 "is this live range local to a basic block") \
181 M(float, nr_rematerializable, PerLiveRangeShape, \
182 "nr rematerializable ranges") \
183 M(float, nr_defs_and_uses, PerLiveRangeShape, \
184 "bb freq - weighed nr defs and uses") \
185 M(float, weighed_reads_by_max, PerLiveRangeShape, \
186 "bb freq - weighed nr of reads, normalized") \
187 M(float, weighed_writes_by_max, PerLiveRangeShape, \
188 "bb feq - weighed nr of writes, normalized") \
189 M(float, weighed_read_writes_by_max, PerLiveRangeShape, \
190 "bb freq - weighed nr of uses that are both read and writes, normalized") \
191 M(float, weighed_indvars_by_max, PerLiveRangeShape, \
192 "bb freq - weighed nr of uses that are indvars, normalized") \
193 M(float, hint_weights_by_max, PerLiveRangeShape, \
194 "bb freq - weighed nr of uses that are hints, normalized") \
195 M(float, start_bb_freq_by_max, PerLiveRangeShape, \
196 "the freq in the start block, normalized") \
197 M(float, end_bb_freq_by_max, PerLiveRangeShape, \
198 "freq of end block, normalized") \
199 M(float, hottest_bb_freq_by_max, PerLiveRangeShape, \
200 "hottest BB freq, normalized") \
201 M(float, liverange_size, PerLiveRangeShape, \
202 "size (instr index diff) of the LR") \
203 M(float, use_def_density, PerLiveRangeShape, \
204 "the max weight, as computed by the manual heuristic") \
205 M(int64_t, max_stage, PerLiveRangeShape, \
206 "largest stage of an interval in this LR") \
207 M(int64_t, min_stage, PerLiveRangeShape, \
208 "lowest stage of an interval in this LR") \
209 M(float, progress, {1}, "ratio of current queue size to initial size")
210
211#ifdef LLVM_HAVE_TFLITE
212#define RA_EVICT_FIRST_DEVELOPMENT_FEATURE(M) \
213 M(int64_t, instructions, InstructionsShape, \
214 "Opcodes of the instructions covered by the eviction problem")
215
216#define RA_EVICT_REST_DEVELOPMENT_FEATURES(M) \
217 M(int64_t, instructions_mapping, InstructionsMappingShape, \
218 "A binary matrix mapping LRs to instruction opcodes") \
219 M(float, mbb_frequencies, MBBFrequencyShape, \
220 "A vector of machine basic block frequencies") \
221 M(int64_t, mbb_mapping, InstructionsShape, \
222 "A vector of indices mapping instructions to MBBs")
223#else
224#define RA_EVICT_FIRST_DEVELOPMENT_FEATURE(M)
225#define RA_EVICT_REST_DEVELOPMENT_FEATURES(M)
226#endif
227
228// The model learns to pick one of the mask == 1 interferences. This is the
229// name of the output tensor. The contract with the model is that the output
230// will be guaranteed to be to a mask == 1 position. Using a macro here to
231// avoid 'not used' warnings (and keep cond compilation to a minimum)
232#define DecisionName "index_to_evict"
233static const TensorSpec DecisionSpec =
234 TensorSpec::createSpec<int64_t>(DecisionName, {1});
235
236// Named features index.
237enum FeatureIDs {
238#define _FEATURE_IDX_SIMPLE(_, name, __, ___) name
239#define _FEATURE_IDX(A, B, C, D) _FEATURE_IDX_SIMPLE(A, B, C, D),
241#ifdef LLVM_HAVE_TFLITE
243#else
245#endif // #ifdef LLVM_HAVE_TFLITE
246 RA_EVICT_REST_DEVELOPMENT_FEATURES(_FEATURE_IDX) FeaturesWithDevelopmentCount
247#undef _FEATURE_IDX
248#undef _FEATURE_IDX_SIMPLE
249};
250
251// The ML advisor will typically have a sparse input to the evaluator, because
252// various phys regs won't be available. It's easier (maintenance-wise) to
253// bulk-reset the state of the evaluator each time we are about to use it
254// again.
255template <typename T> size_t getTotalSize(const std::vector<int64_t> &Shape) {
256 size_t Ret = sizeof(T);
257 for (const auto V : Shape)
258 Ret *= V;
259 return Ret;
260}
261
262void resetInputs(MLModelRunner &Runner) {
263#define _RESET(TYPE, NAME, SHAPE, __) \
264 std::memset(Runner.getTensorUntyped(FeatureIDs::NAME), 0, \
265 getTotalSize<TYPE>(SHAPE));
270#undef _RESET
271 }
272}
273
274// Per-live interval components that get aggregated into the feature values
275// that will be passed to the evaluator.
276struct LIFeatureComponents {
277 double R = 0;
278 double W = 0;
279 double RW = 0;
280 double IndVarUpdates = 0;
281 double HintWeights = 0.0;
282 int64_t NumDefsAndUses = 0;
283 float HottestBlockFreq = 0.0;
284 bool IsRemat = false;
285};
286
287using CandidateRegList =
288 std::array<std::pair<MCRegister, bool>, NumberOfInterferences>;
289using FeaturesListNormalizer =
291
292/// The ML evictor (commonalities between release and development mode)
293class MLEvictAdvisor : public RegAllocEvictionAdvisor {
294public:
295 MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
296 MLModelRunner *Runner, const MachineBlockFrequencyInfo &MBFI,
297 const MachineLoopInfo &Loops);
298
299protected:
300 const RegAllocEvictionAdvisor &getDefaultAdvisor() const {
301 return static_cast<const RegAllocEvictionAdvisor &>(DefaultAdvisor);
302 }
303
304 // The assumption is that if the Runner could not be constructed, we emit-ed
305 // error, and we shouldn't be asking for it here.
306 const MLModelRunner &getRunner() const { return *Runner; }
307
308 /// This just calls Evaluate on the Runner, but in the development mode
309 /// case, if we're just capturing the log of the default advisor, it needs
310 /// to call the latter instead, so we need to pass all the necessary
311 /// parameters for it. In the development case, it will also log.
312 virtual int64_t
313 tryFindEvictionCandidatePosition(const LiveInterval &VirtReg,
314 const AllocationOrder &Order,
315 unsigned OrderLimit, uint8_t CostPerUseLimit,
316 const SmallVirtRegSet &FixedRegisters) const;
317
318 /// Load the features of the given VirtReg (allocated or not) at column Pos,
319 /// but if that can't be evicted, return false instead.
320 bool
321 loadInterferenceFeatures(const LiveInterval &VirtReg, MCRegister PhysReg,
322 bool IsHint, const SmallVirtRegSet &FixedRegisters,
323 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
324 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
325
326private:
327 static float getInitialQueueSize(const MachineFunction &MF);
328
330 const LiveInterval &VirtReg, const AllocationOrder &Order,
331 uint8_t CostPerUseLimit,
332 const SmallVirtRegSet &FixedRegisters) const override;
333
334 void extractFeatures(const SmallVectorImpl<const LiveInterval *> &Intervals,
335 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
336 int64_t IsHint, int64_t LocalIntfsCount, float NumUrgent,
337 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const;
338
339 // Point-in-time: we didn't learn this, so we always delegate to the
340 // default.
342 const LiveInterval &VirtReg, MCRegister PhysReg,
343 const SmallVirtRegSet &FixedRegisters) const override {
344 return getDefaultAdvisor().canEvictHintInterference(VirtReg, PhysReg,
345 FixedRegisters);
346 }
347
348 const LIFeatureComponents &
349 getLIFeatureComponents(const LiveInterval &LI) const;
350
351 // Hold on to a default advisor for:
352 // 1) the implementation of canEvictHintInterference, because we didn't
353 // learn that nuance yet; 2) for bootstrapping (logging) in the development
354 // mode case.
355 const DefaultEvictionAdvisor DefaultAdvisor;
356 MLModelRunner *const Runner;
357 const MachineBlockFrequencyInfo &MBFI;
358 const MachineLoopInfo &Loops;
359
360 // Indices of those features we don't want to normalize.
361 // This could be static and shared, but its initialization is non-trivial.
362 std::bitset<FeatureIDs::FeatureCount> DoNotNormalize;
363 const float InitialQSize;
364
365 using RegID = unsigned;
366 mutable DenseMap<RegID, LIFeatureComponents> CachedFeatures;
367};
368
369#define _DECL_FEATURES(type, name, shape, _) \
370 TensorSpec::createSpec<type>(#name, shape),
371
372// ===================================
373// Release (AOT) - specifics
374// ===================================
375class ReleaseModeEvictionAdvisorAnalysis final
377public:
378 ReleaseModeEvictionAdvisorAnalysis()
379 : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Release) {
384 } else {
386 }
387 }
388 // support for isa<> and dyn_cast.
389 static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
390 return R->getAdvisorMode() == AdvisorMode::Release;
391 }
392
393private:
394 std::vector<TensorSpec> InputFeatures;
395
396 void getAnalysisUsage(AnalysisUsage &AU) const override {
400 }
401
402 std::unique_ptr<RegAllocEvictionAdvisor>
403 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
404 if (!Runner) {
405 if (InteractiveChannelBaseName.empty())
406 Runner = std::make_unique<ReleaseModeModelRunner<CompiledModelType>>(
408 else
409 Runner = std::make_unique<InteractiveModelRunner>(
413 }
414 return std::make_unique<MLEvictAdvisor>(
415 MF, RA, Runner.get(),
416 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(),
417 getAnalysis<MachineLoopInfoWrapperPass>().getLI());
418 }
419 std::unique_ptr<MLModelRunner> Runner;
420};
421
422// ===================================
423// Development mode-specifics
424// ===================================
425//
426// Features we log
427#ifdef LLVM_HAVE_TFLITE
428static const TensorSpec Reward = TensorSpec::createSpec<float>("reward", {1});
429
430// Features we bind on the model. The tensor names have a prefix, and we also
431// need to include some tensors that are expected to be present by the
432// training algo.
433// TODO: can we just get rid of these?
434#define _DECL_TRAIN_FEATURES(type, name, shape, _) \
435 TensorSpec::createSpec<type>(std::string("action_") + #name, shape),
436
437class DevelopmentModeEvictAdvisor : public MLEvictAdvisor {
438public:
439 DevelopmentModeEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
440 MLModelRunner *Runner,
441 const MachineBlockFrequencyInfo &MBFI,
442 const MachineLoopInfo &Loops, Logger *Log)
443 : MLEvictAdvisor(MF, RA, Runner, MBFI, Loops), Log(Log) {}
444
445private:
446 int64_t tryFindEvictionCandidatePosition(
447 const LiveInterval &VirtReg, const AllocationOrder &Order,
448 unsigned OrderLimit, uint8_t CostPerUseLimit,
449 const SmallVirtRegSet &FixedRegisters) const override;
450
451 Logger *const Log;
452};
453
454class DevelopmentModeEvictionAdvisorAnalysis final
456public:
457 DevelopmentModeEvictionAdvisorAnalysis()
458 : RegAllocEvictionAdvisorAnalysis(AdvisorMode::Development) {
463 TrainingInputFeatures = {
464 RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
465 RA_EVICT_FIRST_DEVELOPMENT_FEATURE(_DECL_TRAIN_FEATURES)
466 RA_EVICT_REST_DEVELOPMENT_FEATURES(_DECL_TRAIN_FEATURES)
467 TensorSpec::createSpec<float>("action_discount", {1}),
468 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
469 TensorSpec::createSpec<float>("action_reward", {1})};
470 } else {
472 TrainingInputFeatures = {
473 RA_EVICT_FEATURES_LIST(_DECL_TRAIN_FEATURES)
474 TensorSpec::createSpec<float>("action_discount", {1}),
475 TensorSpec::createSpec<int32_t>("action_step_type", {1}),
476 TensorSpec::createSpec<float>("action_reward", {1})};
477 }
478 }
479 // support for isa<> and dyn_cast.
480 static bool classof(const RegAllocEvictionAdvisorAnalysis *R) {
481 return R->getAdvisorMode() == AdvisorMode::Development;
482 }
483
484 void logRewardIfNeeded(const MachineFunction &MF,
485 llvm::function_ref<float()> GetReward) override {
486 if (!Log || !Log->hasAnyObservationForContext(MF.getName()))
487 return;
488 // The function pass manager would run all the function passes for a
489 // function, so we assume the last context belongs to this function. If
490 // this invariant ever changes, we can implement at that time switching
491 // contexts. At this point, it'd be an error
492 if (Log->currentContext() != MF.getName()) {
494 "The training log context shouldn't have had changed.");
495 }
496 if (Log->hasObservationInProgress())
497 Log->logReward<float>(GetReward());
498 }
499
500private:
501 std::vector<TensorSpec> InputFeatures;
502 std::vector<TensorSpec> TrainingInputFeatures;
503
504 void getAnalysisUsage(AnalysisUsage &AU) const override {
508 }
509
510 bool doInitialization(Module &M) override {
511 LLVMContext &Ctx = M.getContext();
512 if (ModelUnderTraining.empty() && TrainingLog.empty()) {
513 Ctx.emitError("Regalloc development mode should be requested with at "
514 "least logging enabled and/or a training model");
515 return false;
516 }
517 if (ModelUnderTraining.empty())
518 Runner = std::make_unique<NoInferenceModelRunner>(Ctx, InputFeatures);
519 else
520 Runner = ModelUnderTrainingRunner::createAndEnsureValid(
521 Ctx, ModelUnderTraining, DecisionName, TrainingInputFeatures);
522 if (!Runner) {
523 Ctx.emitError("Regalloc: could not set up the model runner");
524 return false;
525 }
526 if (TrainingLog.empty())
527 return false;
528 std::error_code EC;
529 auto OS = std::make_unique<raw_fd_ostream>(TrainingLog, EC);
530 if (EC) {
531 M.getContext().emitError(EC.message() + ":" + TrainingLog);
532 return false;
533 }
534 std::vector<TensorSpec> LFS = InputFeatures;
535 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(Runner.get()))
536 append_range(LFS, MUTR->extraOutputsForLoggingSpecs());
537 // We always log the output; in particular, if we're not evaluating, we
538 // don't have an output spec json file. That's why we handle the
539 // 'normal' output separately.
540 LFS.push_back(DecisionSpec);
541
542 Log = std::make_unique<Logger>(std::move(OS), LFS, Reward,
543 /*IncludeReward*/ true);
544 return false;
545 }
546
547 std::unique_ptr<RegAllocEvictionAdvisor>
548 getAdvisor(const MachineFunction &MF, const RAGreedy &RA) override {
549 if (!Runner)
550 return nullptr;
551 if (Log)
552 Log->switchContext(MF.getName());
553 return std::make_unique<DevelopmentModeEvictAdvisor>(
554 MF, RA, Runner.get(),
555 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(),
556 getAnalysis<MachineLoopInfoWrapperPass>().getLI(), Log.get());
557 }
558
559 std::unique_ptr<MLModelRunner> Runner;
560 std::unique_ptr<Logger> Log;
561};
562
563#endif // #ifdef LLVM_HAVE_TFLITE
564} // namespace
565
566float MLEvictAdvisor::getInitialQueueSize(const MachineFunction &MF) {
567 auto &MRI = MF.getRegInfo();
568 unsigned NumUsedRegs = 0;
569 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
571 if (!MRI.reg_nodbg_empty(Reg))
572 ++NumUsedRegs;
573 }
574 return static_cast<float>(NumUsedRegs);
575}
576
577MLEvictAdvisor::MLEvictAdvisor(const MachineFunction &MF, const RAGreedy &RA,
578 MLModelRunner *Runner,
579 const MachineBlockFrequencyInfo &MBFI,
580 const MachineLoopInfo &Loops)
581 : RegAllocEvictionAdvisor(MF, RA), DefaultAdvisor(MF, RA),
582 Runner(std::move(Runner)), MBFI(MBFI), Loops(Loops),
583 InitialQSize(MLEvictAdvisor::getInitialQueueSize(MF)) {
584 assert(this->Runner);
585 Runner->switchContext(MF.getName());
586 DoNotNormalize.set(FeatureIDs::mask);
587 DoNotNormalize.set(FeatureIDs::is_free);
588 DoNotNormalize.set(FeatureIDs::is_hint);
589 DoNotNormalize.set(FeatureIDs::is_local);
590 DoNotNormalize.set(FeatureIDs::min_stage);
591 DoNotNormalize.set(FeatureIDs::max_stage);
592 DoNotNormalize.set(FeatureIDs::progress);
593}
594
595int64_t MLEvictAdvisor::tryFindEvictionCandidatePosition(
596 const LiveInterval &, const AllocationOrder &, unsigned, uint8_t,
597 const SmallVirtRegSet &) const {
598 int64_t Ret = Runner->evaluate<int64_t>();
599 assert(Ret >= 0);
601 return Ret;
602}
603
604bool MLEvictAdvisor::loadInterferenceFeatures(
605 const LiveInterval &VirtReg, MCRegister PhysReg, bool IsHint,
606 const SmallVirtRegSet &FixedRegisters,
607 llvm::SmallVectorImpl<float> &Largest, size_t Pos,
608 llvm::SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
609 // It is only possible to evict virtual register interference.
610 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg) {
611 // leave unavailable
612 return false;
613 }
614
615 const bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
616 int64_t LocalIntfs = 0;
617 float NumUrgent = 0.0f;
618
619 // The cascade tracking is the same as in the default advisor
620 unsigned Cascade = RA.getExtraInfo().getCascadeOrCurrentNext(VirtReg.reg());
621
623 for (MCRegUnit Unit : TRI->regunits(PhysReg)) {
624 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit);
625 // Different from the default heuristic, we don't make any assumptions
626 // about what having more than 10 results in the query may mean.
627 const auto &IFIntervals = Q.interferingVRegs(EvictInterferenceCutoff);
628 if (IFIntervals.empty() && InterferingIntervals.empty())
629 continue;
630 if (IFIntervals.size() >= EvictInterferenceCutoff)
631 return false;
632 InterferingIntervals.append(IFIntervals.begin(), IFIntervals.end());
633 for (const LiveInterval *Intf : reverse(IFIntervals)) {
634 assert(Intf->reg().isVirtual() &&
635 "Only expecting virtual register interference from query");
636 // This is the same set of legality checks as in the default case: don't
637 // try to evict fixed regs or 'done' ones. Also don't break cascades,
638 // except in the urgent case, with the same nuances used in the default
639 // heuristic.
640 // We could try sharing this between the advisors, but it may end up
641 // more complex than it is right now.
642 if (FixedRegisters.count(Intf->reg()))
643 return false;
644 if (RA.getExtraInfo().getStage(*Intf) == RS_Done)
645 return false;
646 bool Urgent =
647 !VirtReg.isSpillable() &&
648 (Intf->isSpillable() ||
649 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
650 RegClassInfo.getNumAllocatableRegs(
651 MRI->getRegClass(Intf->reg())));
652
653 unsigned IntfCascade = RA.getExtraInfo().getCascade(Intf->reg());
654 // There is a potential that the model could be adversarial and
655 // continually evict live ranges over and over again, leading to a
656 // large amount of compile time being spent in regalloc. If we hit the
657 // threshold, prevent the range from being evicted. We still let the
658 // range through if it is urgent as we are required to produce an
659 // eviction if the candidate is not spillable.
660 if (IntfCascade >= MaxCascade && !Urgent)
661 return false;
662
663 // Only evict older cascades or live ranges without a cascade.
664 if (Cascade <= IntfCascade) {
665 if (!Urgent)
666 return false;
667 ++NumUrgent;
668 }
669
670 LocalIntfs += (IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
671 (!EnableLocalReassign || !canReassign(*Intf, PhysReg)));
672 }
673 }
674 // OK, so if we made it this far, this LR is an eviction candidate, load its
675 // features.
676 extractFeatures(InterferingIntervals, Largest, Pos, IsHint, LocalIntfs,
677 NumUrgent, LRPosInfo);
678 return true;
679}
680
681MCRegister MLEvictAdvisor::tryFindEvictionCandidate(
682 const LiveInterval &VirtReg, const AllocationOrder &Order,
683 uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const {
684 auto MaybeOrderLimit = getOrderLimit(VirtReg, Order, CostPerUseLimit);
685 if (!MaybeOrderLimit)
687 unsigned OrderLimit = *MaybeOrderLimit;
688
689 // The heuristic sets initial costs such as, if CostPerUseLimit is
690 // max<uint8_t>, then any of the costs of the legally-evictable intervals
691 // would be lower. When that happens, one of those will be selected.
692 // Therefore, we allow the candidate be selected, unless the candidate is
693 // unspillable, in which case it would be incorrect to not find a register
694 // for it.
695 const bool MustFindEviction =
696 (!VirtReg.isSpillable() && CostPerUseLimit == static_cast<uint8_t>(~0u));
697 // Number of available candidates - if 0, no need to continue.
698 size_t Available = 0;
699 // Make sure we don't have leftover partial state from an attempt where we
700 // had no available candidates and bailed out early.
701 resetInputs(*Runner);
702
703 // Track the index->register mapping because AllocationOrder doesn't do that
704 // and we'd have to scan it.
705 // Also track their mask, to write asserts/debug.
706 CandidateRegList Regs;
707 Regs.fill({0, false});
708
709 // Track the largest value of features seen during this eviction session. We
710 // only normalize (some of) the float features, but it's just simpler to
711 // dimension 'Largest' to all the features, especially since we have the
712 // 'DoNotNormalize' list.
713 FeaturesListNormalizer Largest(FeatureIDs::FeatureCount, 0.0);
714
715 // Same overal idea as in the default eviction policy - we visit the values
716 // of AllocationOrder one at a time. If it's not legally available, we mask
717 // off the corresponding feature column (==do nothing because we already
718 // reset all the features to 0) Use Pos to capture the column we load
719 // features at - in AllocationOrder order.
720 size_t Pos = 0;
722 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit); I != E;
723 ++I, ++Pos) {
724 MCRegister PhysReg = *I;
725 assert(!Regs[Pos].second);
726 assert(PhysReg);
727 if (!canAllocatePhysReg(CostPerUseLimit, PhysReg)) {
728 continue;
729 }
730 if (loadInterferenceFeatures(VirtReg, PhysReg, I.isHint(), FixedRegisters,
731 Largest, Pos, LRPosInfo)) {
732 ++Available;
733 Regs[Pos] = std::make_pair(PhysReg, true);
734 }
735 }
736 if (Available == 0) {
737 // Nothing to decide, nothing to learn.
738 assert(!MustFindEviction);
740 }
741 const size_t ValidPosLimit = Pos;
742 // If we must find eviction, the candidate should be masked out of the
743 // decision making process.
744 Regs[CandidateVirtRegPos].second = !MustFindEviction;
745 if (!MustFindEviction)
746 extractFeatures(SmallVector<const LiveInterval *, 1>(1, &VirtReg), Largest,
747 CandidateVirtRegPos, /*IsHint*/ 0,
748 /*LocalIntfsCount*/ 0,
749 /*NumUrgent*/ 0.0, LRPosInfo);
750 assert(InitialQSize > 0.0 && "We couldn't have gotten here if we had "
751 "nothing to allocate initially.");
752#ifdef LLVM_HAVE_TFLITE
755 LRPosInfo, Runner,
756 [this](SlotIndex InputIndex) -> int {
757 auto *CurrentMachineInstruction =
758 LIS->getInstructionFromIndex(InputIndex);
759 if (!CurrentMachineInstruction) {
760 return -1;
761 }
762 return CurrentMachineInstruction->getOpcode();
763 },
764 [this](SlotIndex InputIndex) -> float {
765 auto *CurrentMachineInstruction =
766 LIS->getInstructionFromIndex(InputIndex);
768 CurrentMachineInstruction->getParent());
769 },
770 [this](SlotIndex InputIndex) -> MachineBasicBlock * {
771 auto *CurrentMachineInstruction =
772 LIS->getInstructionFromIndex(InputIndex);
773 return CurrentMachineInstruction->getParent();
774 },
775 FeatureIDs::instructions, FeatureIDs::instructions_mapping,
776 FeatureIDs::mbb_frequencies, FeatureIDs::mbb_mapping,
777 LIS->getSlotIndexes()->getLastIndex());
778 }
779#endif // #ifdef LLVM_HAVE_TFLITE
780 // Normalize the features.
781 for (auto &V : Largest)
782 V = V ? V : 1.0;
783 for (size_t FeatureIndex = 0; FeatureIndex < FeatureIDs::FeatureCount;
784 ++FeatureIndex) {
785 if (DoNotNormalize.test(FeatureIndex))
786 continue;
787 for (size_t Pos = 0; Pos < NumberOfInterferences; ++Pos) {
788 Runner->getTensor<float>(FeatureIndex)[Pos] /= Largest[FeatureIndex];
789 }
790 }
791 *Runner->getTensor<float>(FeatureIDs::progress) =
792 static_cast<float>(RA.getQueueSize()) / InitialQSize;
793
794 // Get a decision.
795 size_t CandidatePos = tryFindEvictionCandidatePosition(
796 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
797 // The contract with the ML side is that CandidatePos is mask == 1 (i.e.
798 // Regs[CandidatePos].second)
799 assert(Regs[CandidatePos].second);
800 if (CandidatePos == CandidateVirtRegPos) {
801 assert(!MustFindEviction);
803 }
804 assert(CandidatePos < ValidPosLimit);
805 (void)ValidPosLimit;
806 return Regs[CandidatePos].first;
807}
808
809const LIFeatureComponents &
810MLEvictAdvisor::getLIFeatureComponents(const LiveInterval &LI) const {
811 RegID ID = LI.reg().id();
812 LIFeatureComponents Empty;
813 auto I = CachedFeatures.insert(std::make_pair(ID, Empty));
814 LIFeatureComponents &Ret = I.first->getSecond();
815 if (!I.second)
816 return Ret;
817
820
822 I = MRI->reg_instr_nodbg_begin(LI.reg()),
823 E = MRI->reg_instr_nodbg_end();
824 I != E;) {
825 MachineInstr *MI = &*(I++);
826
827 ++Ret.NumDefsAndUses;
828 if (!Visited.insert(MI).second)
829 continue;
830
831 if (MI->isIdentityCopy() || MI->isImplicitDef())
832 continue;
833
834 bool Reads, Writes;
835 std::tie(Reads, Writes) = MI->readsWritesVirtualRegister(LI.reg());
836
837 float Freq = MBFI.getBlockFreqRelativeToEntryBlock(MI->getParent());
838 Ret.HottestBlockFreq = std::max(Freq, Ret.HottestBlockFreq);
839
840 Ret.R += (Reads && !Writes) * Freq;
841 Ret.W += (!Reads && Writes) * Freq;
842 Ret.RW += (Reads && Writes) * Freq;
843
844 auto *MBB = MI->getParent();
845 auto *Loop = Loops.getLoopFor(MBB);
846 bool IsExiting = Loop ? Loop->isLoopExiting(MBB) : false;
847
848 if (Writes && IsExiting && LIS->isLiveOutOfMBB(LI, MBB))
849 Ret.IndVarUpdates += Freq;
850
851 if (MI->isCopy() && VirtRegAuxInfo::copyHint(MI, LI.reg(), TRI, *MRI))
852 Ret.HintWeights += Freq;
853 }
855 LI, *LIS, *VRM, *MF.getSubtarget().getInstrInfo());
856 return Ret;
857}
858
859// Overall, this currently mimics what we do for weight calculation, but instead
860// of accummulating the various features, we keep them separate.
861void MLEvictAdvisor::extractFeatures(
863 llvm::SmallVectorImpl<float> &Largest, size_t Pos, int64_t IsHint,
864 int64_t LocalIntfsCount, float NumUrgent,
865 SmallVectorImpl<LRStartEndInfo> &LRPosInfo) const {
866 int64_t NumDefsAndUses = 0;
867 int64_t NumBrokenHints = 0;
868 double R = 0.0;
869 double W = 0.0;
870 double RW = 0.0;
871 double IndVarUpdates = 0.0;
872 double HintWeights = 0.0;
873 float StartBBFreq = 0.0;
874 float EndBBFreq = 0.0;
875 float HottestBlockFreq = 0.0;
876 int32_t NumRematerializable = 0;
877 float TotalWeight = 0.0;
878
879 SlotIndex EndSI = LIS->getSlotIndexes()->getZeroIndex();
880 SlotIndex StartSI = LIS->getSlotIndexes()->getLastIndex();
881 int64_t MaxStage = 0;
882 int64_t MinStage =
883 Intervals.empty() ? 0 : std::numeric_limits<int64_t>::max();
884
885 for (const auto *L : Intervals) {
886 const LiveInterval &LI = *L;
887 MaxStage = std::max<int64_t>(
888 MaxStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
889 MinStage = std::min<int64_t>(
890 MinStage, static_cast<int64_t>(RA.getExtraInfo().getStage(LI)));
891
892 TotalWeight = std::max(TotalWeight, LI.weight());
893
894 if (LI.beginIndex() < StartSI)
895 StartSI = LI.beginIndex();
896
897 if (LI.endIndex() > EndSI)
898 EndSI = LI.endIndex();
899 const LIFeatureComponents &LIFC = getLIFeatureComponents(LI);
900 NumBrokenHints += VRM->hasPreferredPhys(LI.reg());
901
902 NumDefsAndUses += LIFC.NumDefsAndUses;
903 HottestBlockFreq = std::max(HottestBlockFreq, LIFC.HottestBlockFreq);
904 R += LIFC.R;
905 W += LIFC.W;
906 RW += LIFC.RW;
907
908 IndVarUpdates += LIFC.IndVarUpdates;
909
910 HintWeights += LIFC.HintWeights;
911 NumRematerializable += LIFC.IsRemat;
912
914 for (auto CurrentSegment : LI) {
915 LRPosInfo.push_back(
916 LRStartEndInfo{CurrentSegment.start, CurrentSegment.end, Pos});
917 }
918 }
919 }
920 size_t Size = 0;
921 if (!Intervals.empty()) {
922 StartBBFreq =
923 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(StartSI));
924 if (EndSI >= LIS->getSlotIndexes()->getLastIndex())
925 EndSI = LIS->getSlotIndexes()->getLastIndex().getPrevIndex();
926 EndBBFreq =
927 MBFI.getBlockFreqRelativeToEntryBlock(LIS->getMBBFromIndex(EndSI));
928 Size = StartSI.distance(EndSI);
929 }
930 // Set the features at the column 'Pos'.
931#define SET(ID, TYPE, VAL) \
932 do { \
933 Runner->getTensor<TYPE>(FeatureIDs::ID)[Pos] = static_cast<TYPE>(VAL); \
934 if (!DoNotNormalize.test(FeatureIDs::ID)) \
935 Largest[FeatureIDs::ID] = \
936 std::max(Largest[FeatureIDs::ID], static_cast<float>(VAL)); \
937 } while (false)
938 SET(mask, int64_t, 1);
939 SET(is_free, int64_t, Intervals.empty());
940 SET(nr_urgent, float, NumUrgent);
941 SET(nr_broken_hints, float, NumBrokenHints);
942 SET(is_hint, int64_t, IsHint);
943 SET(is_local, int64_t, LocalIntfsCount);
944 SET(nr_rematerializable, float, NumRematerializable);
945 SET(nr_defs_and_uses, float, NumDefsAndUses);
946 SET(weighed_reads_by_max, float, R);
947 SET(weighed_writes_by_max, float, W);
948 SET(weighed_read_writes_by_max, float, RW);
949 SET(weighed_indvars_by_max, float, IndVarUpdates);
950 SET(hint_weights_by_max, float, HintWeights);
951 SET(start_bb_freq_by_max, float, StartBBFreq);
952 SET(end_bb_freq_by_max, float, EndBBFreq);
953 SET(hottest_bb_freq_by_max, float, HottestBlockFreq);
954 SET(liverange_size, float, Size);
955 SET(use_def_density, float, TotalWeight);
956 SET(max_stage, int64_t, MaxStage);
957 SET(min_stage, int64_t, MinStage);
958#undef SET
959}
960
962 SmallVectorImpl<LRStartEndInfo> &LRPosInfo, MLModelRunner *RegallocRunner,
963 function_ref<int(SlotIndex)> GetOpcode,
964 function_ref<float(SlotIndex)> GetMBBFreq,
965 function_ref<MachineBasicBlock *(SlotIndex)> GetMBBReference,
966 const int InstructionsIndex, const int InstructionsMappingIndex,
967 const int MBBFreqIndex, const int MBBMappingIndex,
968 const SlotIndex LastIndex) {
969 // This function extracts instruction based features relevant to the eviction
970 // problem currently being solved. This function ends up extracting two
971 // tensors.
972 // 1 - A vector of size max instruction count. It contains the opcodes of the
973 // instructions spanned by all the intervals in the current instance of the
974 // eviction problem.
975 // 2 - A binary mapping matrix of size (LR count * max
976 // instruction count) which maps where the LRs are live to the actual opcodes
977 // for which they are live.
978 // 3 - A vector of size max supported MBB count storing MBB frequencies,
979 // encompassing all of the MBBs covered by the eviction problem.
980 // 4 - A vector of size max instruction count of indices to members of the MBB
981 // frequency vector, mapping each instruction to its associated MBB.
982
983 // Start off by sorting the segments based on the beginning slot index.
984 std::sort(
985 LRPosInfo.begin(), LRPosInfo.end(),
986 [](LRStartEndInfo A, LRStartEndInfo B) { return A.Begin < B.Begin; });
987 size_t InstructionIndex = 0;
988 size_t CurrentSegmentIndex = 0;
989 SlotIndex CurrentIndex = LRPosInfo[0].Begin;
990 std::map<MachineBasicBlock *, size_t> VisitedMBBs;
991 size_t CurrentMBBIndex = 0;
992 // This loop processes all the segments sequentially by starting at the
993 // beginning slot index of the first segment, iterating through all the slot
994 // indices before the end slot index of that segment (while checking for
995 // overlaps with segments that start at greater slot indices). After hitting
996 // that end index, the current segment being processed gets bumped until they
997 // are all processed or the max instruction count is hit, where everything is
998 // just truncated.
999 while (true) {
1000 // If the index that we are currently at is within the current segment and
1001 // we haven't hit the max instruction count, continue processing the current
1002 // segment.
1003 while (CurrentIndex <= LRPosInfo[CurrentSegmentIndex].End &&
1004 InstructionIndex < ModelMaxSupportedInstructionCount) {
1005 int CurrentOpcode = GetOpcode(CurrentIndex);
1006 // If the current machine instruction is null, skip it
1007 if (CurrentOpcode == -1) {
1008 // If we're currently at the last index in the SlotIndex analysis,
1009 // we can't go any further, so return from the function
1010 if (CurrentIndex >= LastIndex) {
1011 return;
1012 }
1013 CurrentIndex = CurrentIndex.getNextIndex();
1014 continue;
1015 }
1016 MachineBasicBlock *CurrentMBBReference = GetMBBReference(CurrentIndex);
1017 if (VisitedMBBs.count(CurrentMBBReference) == 0) {
1018 VisitedMBBs[CurrentMBBReference] = CurrentMBBIndex;
1019 ++CurrentMBBIndex;
1020 }
1021 extractMBBFrequency(CurrentIndex, InstructionIndex, VisitedMBBs,
1022 GetMBBFreq, CurrentMBBReference, RegallocRunner,
1023 MBBFreqIndex, MBBMappingIndex);
1024 // Current code assumes we're not going to get any disjointed segments
1025 assert(LRPosInfo[CurrentSegmentIndex].Begin <= CurrentIndex);
1026 RegallocRunner->getTensor<int64_t>(InstructionsIndex)[InstructionIndex] =
1027 CurrentOpcode < OpcodeValueCutoff ? CurrentOpcode : 0;
1028 // set value in the binary mapping matrix for the current instruction
1029 auto CurrentSegmentPosition = LRPosInfo[CurrentSegmentIndex].Pos;
1030 RegallocRunner->getTensor<int64_t>(
1031 InstructionsMappingIndex)[CurrentSegmentPosition *
1033 InstructionIndex] = 1;
1034 // All of the segments are sorted based on the beginning slot index, but
1035 // this doesn't mean that the beginning slot index of the next segment is
1036 // after the end segment of the one being currently processed. This while
1037 // loop checks for overlapping segments and modifies the portion of the
1038 // column in the mapping matrix for the currently processed instruction
1039 // for the LR it is checking. Also make sure that the beginning of the
1040 // current segment we're checking for overlap in is less than the current
1041 // index, otherwise we're done checking overlaps.
1042 size_t OverlapCheckCurrentSegment = CurrentSegmentIndex + 1;
1043 while (OverlapCheckCurrentSegment < LRPosInfo.size() &&
1044 LRPosInfo[OverlapCheckCurrentSegment].Begin <= CurrentIndex) {
1045 auto OverlapCurrentSegmentPosition =
1046 LRPosInfo[OverlapCheckCurrentSegment].Pos;
1047 if (LRPosInfo[OverlapCheckCurrentSegment].End >= CurrentIndex) {
1048 RegallocRunner->getTensor<int64_t>(
1049 InstructionsMappingIndex)[OverlapCurrentSegmentPosition *
1051 InstructionIndex] = 1;
1052 }
1053 ++OverlapCheckCurrentSegment;
1054 }
1055 ++InstructionIndex;
1056 if (CurrentIndex >= LastIndex) {
1057 return;
1058 }
1059 CurrentIndex = CurrentIndex.getNextIndex();
1060 }
1061 // if we've just finished processing through the last segment or if we've
1062 // hit the maximum number of instructions, break out of the loop.
1063 if (CurrentSegmentIndex == LRPosInfo.size() - 1 ||
1064 InstructionIndex >= ModelMaxSupportedInstructionCount) {
1065 break;
1066 }
1067 // If the segments are not overlapping, we need to move to the beginning
1068 // index of the next segment to avoid having instructions not attached to
1069 // any register.
1070 if (LRPosInfo[CurrentSegmentIndex + 1].Begin >
1071 LRPosInfo[CurrentSegmentIndex].End) {
1072 CurrentIndex = LRPosInfo[CurrentSegmentIndex + 1].Begin;
1073 }
1074 ++CurrentSegmentIndex;
1075 }
1076}
1077
1079 const SlotIndex CurrentIndex, const size_t CurrentInstructionIndex,
1080 std::map<MachineBasicBlock *, size_t> &VisitedMBBs,
1081 function_ref<float(SlotIndex)> GetMBBFreq,
1082 MachineBasicBlock *CurrentMBBReference, MLModelRunner *RegallocRunner,
1083 const int MBBFreqIndex, const int MBBMappingIndex) {
1084 size_t CurrentMBBIndex = VisitedMBBs[CurrentMBBReference];
1085 float CurrentMBBFreq = GetMBBFreq(CurrentIndex);
1086 if (CurrentMBBIndex < ModelMaxSupportedMBBCount) {
1087 RegallocRunner->getTensor<float>(MBBFreqIndex)[CurrentMBBIndex] =
1088 CurrentMBBFreq;
1089 RegallocRunner->getTensor<int64_t>(
1090 MBBMappingIndex)[CurrentInstructionIndex] = CurrentMBBIndex;
1091 }
1092}
1093
1094// Development mode-specific implementations
1095#ifdef LLVM_HAVE_TFLITE
1096
1098 return new DevelopmentModeEvictionAdvisorAnalysis();
1099}
1100
1101int64_t DevelopmentModeEvictAdvisor::tryFindEvictionCandidatePosition(
1102 const LiveInterval &VirtReg, const AllocationOrder &Order,
1103 unsigned OrderLimit, uint8_t CostPerUseLimit,
1104 const SmallVirtRegSet &FixedRegisters) const {
1105 int64_t Ret = 0;
1106 if (isa<ModelUnderTrainingRunner>(getRunner())) {
1107 Ret = MLEvictAdvisor::tryFindEvictionCandidatePosition(
1108 VirtReg, Order, OrderLimit, CostPerUseLimit, FixedRegisters);
1109 } else {
1110 MCRegister PhysReg = getDefaultAdvisor().tryFindEvictionCandidate(
1111 VirtReg, Order, CostPerUseLimit, FixedRegisters);
1112 // Find the index of the selected PhysReg. We need it for logging,
1113 // otherwise this is wasted cycles (but so would starting development mode
1114 // without a model nor logging)
1115 if (!PhysReg)
1117 else
1118 for (auto I = Order.begin(), E = Order.getOrderLimitEnd(OrderLimit);
1119 I != E; ++I, ++Ret)
1120 if (*I == PhysReg)
1121 break;
1122 }
1123 if (TrainingLog.empty())
1124 return Ret;
1125 // TODO(mtrofin): when we support optional rewards, this can go away. In the
1126 // meantime, we log the "pretend" reward (0) for the previous observation
1127 // before starting a new one.
1128 if (Log->hasObservationInProgress())
1129 Log->logReward<float>(0.0);
1130
1131 Log->startObservation();
1132 size_t CurrentFeature = 0;
1134 ? FeatureIDs::FeaturesWithDevelopmentCount
1135 : FeatureIDs::FeatureCount;
1136 for (; CurrentFeature < FeatureCount; ++CurrentFeature) {
1137 Log->logTensorValue(CurrentFeature,
1138 reinterpret_cast<const char *>(
1139 getRunner().getTensorUntyped(CurrentFeature)));
1140 }
1141 if (auto *MUTR = dyn_cast<ModelUnderTrainingRunner>(&getRunner()))
1142 for (size_t I = 0; I < MUTR->extraOutputsForLoggingSpecs().size();
1143 ++I, ++CurrentFeature)
1144 Log->logTensorValue(
1145 CurrentFeature,
1146 reinterpret_cast<const char *>(MUTR->getUntypedExtraOutputValue(I)));
1147 // The output is right after the features and the extra outputs
1148 Log->logTensorValue(CurrentFeature, reinterpret_cast<const char *>(&Ret));
1149 Log->endObservation();
1150 return Ret;
1151}
1152
1154 std::optional<float> CachedReward;
1155 auto GetReward = [&]() {
1156 if (!CachedReward)
1157 CachedReward = static_cast<float>(
1159 MF, getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI())
1160 .getScore());
1161 return *CachedReward;
1162 };
1163
1164 getAnalysis<RegAllocEvictionAdvisorAnalysis>().logRewardIfNeeded(MF,
1165 GetReward);
1166 getAnalysis<RegAllocPriorityAdvisorAnalysis>().logRewardIfNeeded(MF,
1167 GetReward);
1168 return false;
1169}
1170#endif // #ifdef LLVM_HAVE_TFLITE
1171
1173 return llvm::isEmbeddedModelEvaluatorValid<CompiledModelType>() ||
1175 ? new ReleaseModeEvictionAdvisorAnalysis()
1176 : nullptr;
1177}
1178
1179// In all cases except development mode, we don't need scoring.
1180#if !defined(LLVM_HAVE_TFLITE)
1182#endif
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
SmallVector< uint32_t, 0 > Writes
Definition: ELF_riscv.cpp:497
@ Available
We know the block is fully available. This is a fixpoint.
Hexagon Hardware Loops
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
Live Register Matrix
#define I(x, y, z)
Definition: MD5.cpp:58
static cl::opt< std::string > InteractiveChannelBaseName("inliner-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <inliner-interactive-channel-base>.in, while the " "outgoing name should be <inliner-interactive-channel-base>.out"))
static const bool EnableDevelopmentFeatures
#define RA_EVICT_FEATURES_LIST(M)
#define _FEATURE_IDX_SIMPLE(_, name, __, ___)
#define RA_EVICT_FIRST_DEVELOPMENT_FEATURE(M)
#define SET(ID, TYPE, VAL)
#define _RESET(TYPE, NAME, SHAPE, __)
static cl::opt< unsigned > MaxCascade("mlregalloc-max-cascade", cl::Hidden, cl::desc("The maximum number of times a live range can be " "evicted before preventing it from being evicted"), cl::init(20))
#define RA_EVICT_REST_DEVELOPMENT_FEATURES(M)
static cl::opt< std::string > InteractiveChannelBaseName("regalloc-evict-interactive-channel-base", cl::Hidden, cl::desc("Base file path for the interactive mode. The incoming filename should " "have the name <regalloc-evict-interactive-channel-base>.in, while the " "outgoing name should be " "<regalloc-evict-interactive-channel-base>.out"))
#define _FEATURE_IDX(A, B, C, D)
#define _DECL_FEATURES(type, name, shape, _)
#define DecisionName
unsigned const TargetRegisterInfo * TRI
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SI optimize exec mask operations pre RA
raw_pwrite_stream & OS
Iterator getOrderLimitEnd(unsigned OrderLimit) const
Iterator begin() const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:369
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Query interferences between a single live virtual register and a live interval union.
const SmallVectorImpl< const LiveInterval * > & interferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:687
float weight() const
Definition: LiveInterval.h:719
Register reg() const
Definition: LiveInterval.h:718
bool isSpillable() const
isSpillable - Can this interval be spilled?
Definition: LiveInterval.h:826
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:385
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
Definition: LiveInterval.h:392
@ IK_VirtReg
Virtual register interference.
Definition: LiveRegMatrix.h:94
Logging utility - given an ordered specification of features, and assuming a scalar reward,...
bool isLoopExiting(const BlockT *BB) const
True if terminator in the block can branch to another block that is outside of the current loop.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
static constexpr unsigned NoRegister
Definition: MCRegister.h:52
MLModelRunner interface: abstraction of a mechanism for evaluating a ML model.
Definition: MLModelRunner.h:26
virtual void switchContext(StringRef Name)
Definition: MLModelRunner.h:54
T * getTensor(I FeatureID)
Definition: MLModelRunner.h:37
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
double getBlockFreqRelativeToEntryBlock(const MachineBasicBlock *MBB) const
Compute the frequency of the block, relative to the entry block.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
Definition: MachineInstr.h:69
defusechain_iterator - This class provides iterator support for machine operands in the function that...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A mock class satisfying the interface expected by ReleaseModeModelRunner for its TGen parameter.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual bool doInitialization(Module &)
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Definition: Pass.h:119
ImmutableAnalysis abstraction for fetching the Eviction Advisor.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
virtual std::unique_ptr< RegAllocEvictionAdvisor > getAdvisor(const MachineFunction &MF, const RAGreedy &RA)=0
Get an advisor for the given context (i.e. machine function, etc)
virtual void logRewardIfNeeded(const MachineFunction &MF, llvm::function_ref< float()> GetReward)
virtual bool canEvictHintInterference(const LiveInterval &VirtReg, MCRegister PhysReg, const SmallVirtRegSet &FixedRegisters) const =0
Find out if we can evict the live ranges occupying the given PhysReg, which is a hint (preferred regi...
virtual MCRegister tryFindEvictionCandidate(const LiveInterval &VirtReg, const AllocationOrder &Order, uint8_t CostPerUseLimit, const SmallVirtRegSet &FixedRegisters) const =0
Find a physical register that can be freed by evicting the FixedRegisters, or return NoRegister.
double getScore() const
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
void getAnalysisUsage(AnalysisUsage &AU) const override
RegAllocReward analysis usage.
~RegAllocScoring() override=default
bool runOnMachineFunction(MachineFunction &) override
Performs this pass.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
constexpr unsigned id() const
Definition: Register.h:103
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:65
SlotIndex getNextIndex() const
Returns the next index.
Definition: SlotIndexes.h:262
int distance(SlotIndex other) const
Return the distance from this index to the given one.
Definition: SlotIndexes.h:193
SlotIndex getPrevIndex() const
Returns the previous index.
Definition: SlotIndexes.h:282
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:132
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:175
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:683
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
static Register copyHint(const MachineInstr *MI, unsigned Reg, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI)
Return the preferred allocation register for reg, given a COPY instruction.
static bool isRematerializable(const LiveInterval &LI, const LiveIntervals &LIS, const VirtRegMap &VRM, const TargetInstrInfo &TII)
Determine if all values in LI are rematerializable.
An efficient, type-erasing, non-owning reference to a callable.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
static const int ModelMaxSupportedInstructionCount
static const int64_t ModelMaxSupportedMBBCount
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2115
void extractInstructionFeatures(llvm::SmallVectorImpl< LRStartEndInfo > &LRPosInfo, MLModelRunner *RegallocRunner, function_ref< int(SlotIndex)> GetOpcode, function_ref< float(SlotIndex)> GetMBBFreq, function_ref< MachineBasicBlock *(SlotIndex)> GetMBBReference, const int InstructionsIndex, const int InstructionsMappingIndex, const int MBBFreqIndex, const int MBBMappingIndex, const SlotIndex LastIndex)
static const TensorSpec DecisionSpec
RegAllocScore calculateRegAllocScore(const MachineFunction &MF, const MachineBlockFrequencyInfo &MBFI)
Calculate a score.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:420
const char *const DecisionName
static const std::vector< TensorSpec > InputFeatures
@ RS_Done
There is nothing more we can do to this live range.
FunctionPass * createRegAllocScoringPass()
When learning an eviction policy, extract score(reward) information, otherwise this does nothing.
void initializeRegAllocScoringPass(PassRegistry &)
RegAllocEvictionAdvisorAnalysis * createReleaseModeAdvisor()
RegAllocEvictionAdvisorAnalysis * createDevelopmentModeAdvisor()
cl::opt< unsigned > EvictInterferenceCutoff
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
void extractMBBFrequency(const SlotIndex CurrentIndex, const size_t CurrentInstructionIndex, std::map< MachineBasicBlock *, size_t > &VisitedMBBs, function_ref< float(SlotIndex)> GetMBBFreq, MachineBasicBlock *CurrentMBBReference, MLModelRunner *RegallocRunner, const int MBBFreqIndex, const int MBBMappingIndex)
static const int64_t NumberOfInterferences
static const std::vector< int64_t > PerLiveRangeShape
static const int64_t CandidateVirtRegPos
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858