LLVM 23.0.0git
ReachingDefAnalysis.cpp
Go to the documentation of this file.
1//===---- ReachingDefAnalysis.cpp - Reaching Def Analysis ---*- C++ -*-----===//
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
11#include "llvm/ADT/SmallSet.h"
17#include "llvm/Support/Debug.h"
18
19using namespace llvm;
20
21#define DEBUG_TYPE "reaching-defs-analysis"
22
23AnalysisKey ReachingDefAnalysis::Key;
24
32
36 MFPropsModifier _(*this, MF);
37
38 auto &RDI = MFAM.getResult<ReachingDefAnalysis>(MF);
39 OS << "Reaching definitions for for machine function: " << MF.getName()
40 << '\n';
41 RDI.print(OS);
43}
44
46 "Reaching Definitions Analysis", false, true)
47
49
52
56
59 MachineFunctionAnalysisManager::Invalidator &) {
60 // Check whether the analysis, all analyses on machine functions, or the
61 // machine function's CFG have been preserved.
62 auto PAC = PA.getChecker<ReachingDefAnalysis>();
63 return !PAC.preserved() &&
64 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
65 !PAC.preservedSet<CFGAnalyses>();
66}
67
72
77
78static bool isValidReg(const MachineOperand &MO) {
79 return MO.isReg() && MO.getReg();
80}
81
82static bool isValidRegUse(const MachineOperand &MO) {
83 return isValidReg(MO) && MO.isUse();
84}
85
87 const TargetRegisterInfo *TRI) {
88 if (!isValidRegUse(MO))
89 return false;
90 return TRI->regsOverlap(MO.getReg(), Reg);
91}
92
93static bool isValidRegDef(const MachineOperand &MO) {
94 return isValidReg(MO) && MO.isDef();
95}
96
98 const TargetRegisterInfo *TRI) {
99 if (!isValidRegDef(MO))
100 return false;
101 return TRI->regsOverlap(MO.getReg(), Reg);
102}
103
104static bool isFIDef(const MachineInstr &MI, int FrameIndex,
105 const TargetInstrInfo *TII) {
106 int DefFrameIndex = 0;
107 int SrcFrameIndex = 0;
108 if (TII->isStoreToStackSlot(MI, DefFrameIndex) ||
109 TII->isStackSlotCopy(MI, DefFrameIndex, SrcFrameIndex))
110 return DefFrameIndex == FrameIndex;
111 return false;
112}
113
114void ReachingDefInfo::enterBasicBlock(MachineBasicBlock *MBB) {
115 unsigned MBBNumber = MBB->getNumber();
116 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
117 "Unexpected basic block number.");
118 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
119
120 // Reset instruction counter in each basic block.
121 CurInstr = 0;
122
123 // Set up LiveRegs to represent registers entering MBB.
124 // Default values are 'nothing happened a long time ago'.
125 if (LiveRegs.empty())
126 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
127
128 // This is the entry block.
129 if (MBB == &MBB->getParent()->front()) {
130 for (const auto &LI : MBB->liveins()) {
131 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
132 // Treat function live-ins as if they were defined just before the first
133 // instruction. Usually, function arguments are set up immediately
134 // before the call.
135 if (LiveRegs[static_cast<unsigned>(Unit)] != FunctionLiveInMarker) {
136 LiveRegs[static_cast<unsigned>(Unit)] = FunctionLiveInMarker;
137 MBBReachingDefs.append(MBBNumber, Unit, FunctionLiveInMarker);
138 }
139 }
140 }
141 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
142 return;
143 }
144
145 // Try to coalesce live-out registers from predecessors.
146 for (MachineBasicBlock *pred : MBB->predecessors()) {
147 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
148 "Should have pre-allocated MBBInfos for all MBBs");
149 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
150 // Incoming is null if this is a backedge from a BB
151 // we haven't processed yet
152 if (Incoming.empty())
153 continue;
154
155 // Find the most recent reaching definition from a predecessor.
156 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
157 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
158 }
159
160 // Insert the most recent reaching definition we found.
161 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
162 if (LiveRegs[Unit] != ReachingDefDefaultVal)
163 MBBReachingDefs.append(MBBNumber, static_cast<MCRegUnit>(Unit),
164 LiveRegs[Unit]);
165}
166
167void ReachingDefInfo::leaveBasicBlock(MachineBasicBlock *MBB) {
168 assert(!LiveRegs.empty() && "Must enter basic block first.");
169 unsigned MBBNumber = MBB->getNumber();
170 assert(MBBNumber < MBBOutRegsInfos.size() &&
171 "Unexpected basic block number.");
172 // Save register clearances at end of MBB - used by enterBasicBlock().
173 MBBOutRegsInfos[MBBNumber] = LiveRegs;
174
175 // While processing the basic block, we kept `Def` relative to the start
176 // of the basic block for convenience. However, future use of this information
177 // only cares about the clearance from the end of the block, so adjust
178 // everything to be relative to the end of the basic block.
179 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
180 if (OutLiveReg != ReachingDefDefaultVal)
181 OutLiveReg -= CurInstr;
182 LiveRegs.clear();
183}
184
185void ReachingDefInfo::processDefs(MachineInstr *MI) {
186 assert(!MI->isDebugInstr() && "Won't process debug instructions");
187
188 unsigned MBBNumber = MI->getParent()->getNumber();
189 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
190 "Unexpected basic block number.");
191
192 for (auto &MO : MI->operands()) {
193 if (MO.isFI()) {
194 int FrameIndex = MO.getIndex();
195 if (!isFIDef(*MI, FrameIndex, TII))
196 continue;
197 MBBFrameObjsReachingDefs[{MBBNumber, FrameIndex}].push_back(CurInstr);
198 }
199 if (!isValidRegDef(MO))
200 continue;
201 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
202 // This instruction explicitly defines the current reg unit.
203 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
204 << *MI);
205
206 // How many instructions since this reg unit was last written?
207 if (LiveRegs[static_cast<unsigned>(Unit)] != CurInstr) {
208 LiveRegs[static_cast<unsigned>(Unit)] = CurInstr;
209 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
210 }
211 }
212 }
213 InstIds[MI] = CurInstr;
214 ++CurInstr;
215}
216
217void ReachingDefInfo::reprocessBasicBlock(MachineBasicBlock *MBB) {
218 unsigned MBBNumber = MBB->getNumber();
219 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
220 "Unexpected basic block number.");
221
222 // Count number of non-debug instructions for end of block adjustment.
223 auto NonDbgInsts =
225 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
226
227 // When reprocessing a block, the only thing we need to do is check whether
228 // there is now a more recent incoming reaching definition from a predecessor.
229 for (MachineBasicBlock *pred : MBB->predecessors()) {
230 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
231 "Should have pre-allocated MBBInfos for all MBBs");
232 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
233 // Incoming may be empty for dead predecessors.
234 if (Incoming.empty())
235 continue;
236
237 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
238 int Def = Incoming[Unit];
239 if (Def == ReachingDefDefaultVal)
240 continue;
241
242 auto Defs = MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit));
243 if (!Defs.empty() && Defs.front() < 0) {
244 if (Defs.front() >= Def)
245 continue;
246
247 // Update existing reaching def from predecessor to a more recent one.
248 MBBReachingDefs.replaceFront(MBBNumber, static_cast<MCRegUnit>(Unit),
249 Def);
250 } else {
251 // Insert new reaching def from predecessor.
252 MBBReachingDefs.prepend(MBBNumber, static_cast<MCRegUnit>(Unit), Def);
253 }
254
255 // Update reaching def at end of BB. Keep in mind that these are
256 // adjusted relative to the end of the basic block.
257 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
258 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
259 }
260 }
261}
262
263void ReachingDefInfo::processBasicBlock(
264 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
265 MachineBasicBlock *MBB = TraversedMBB.MBB;
267 << (!TraversedMBB.IsDone ? ": incomplete\n"
268 : ": all preds known\n"));
269
270 if (!TraversedMBB.PrimaryPass) {
271 // Reprocess MBB that is part of a loop.
272 reprocessBasicBlock(MBB);
273 return;
274 }
275
276 enterBasicBlock(MBB);
277 for (MachineInstr &MI :
279 processDefs(&MI);
280 leaveBasicBlock(MBB);
281}
282
284 MF = &mf;
285 const TargetSubtargetInfo &STI = MF->getSubtarget();
286 TRI = STI.getRegisterInfo();
287 TII = STI.getInstrInfo();
288 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
289 init();
290 traverse();
291}
292
294 // Create a map from instruction to numerical ids.
295 // Since a reaching def can come after instruction,
296 // this map needs to be populated first.
297 int Num = 0;
299 for (MachineBasicBlock &MBB : *MF) {
300 for (MachineInstr &MI : MBB) {
301 InstToNumMap[&MI] = Num;
302 ++Num;
303 }
304 }
305
307 for (MachineBasicBlock &MBB : *MF) {
308 OS << printMBBReference(MBB) << ":\n";
309 for (MachineInstr &MI : MBB) {
310 for (MachineOperand &MO : MI.operands()) {
311 Register Reg;
312 if (MO.isFI()) {
313 int FrameIndex = MO.getIndex();
314 Reg = Register::index2StackSlot(FrameIndex);
315 } else if (MO.isReg()) {
316 if (MO.isDef())
317 continue;
318 Reg = MO.getReg();
319 if (!Reg.isValid())
320 continue;
321 } else
322 continue;
323 Defs.clear();
324 getGlobalReachingDefs(&MI, Reg, Defs);
325 MO.print(OS, TRI);
327 for (MachineInstr *Def : Defs)
328 Nums.push_back(InstToNumMap[Def]);
329 llvm::sort(Nums);
330 OS << ":{ ";
331 for (int Num : Nums)
332 OS << Num << " ";
333 OS << "}\n";
334 }
335 OS << InstToNumMap[&MI] << ": " << MI << "\n";
336 }
337 }
338}
339
341 RDI.run(mf);
342 return false;
343}
344
346 // Clear the internal vectors.
347 MBBOutRegsInfos.clear();
348 MBBReachingDefs.clear();
349 MBBFrameObjsReachingDefs.clear();
350 InstIds.clear();
351 LiveRegs.clear();
352}
353
356 init();
357 traverse();
358}
359
361 NumRegUnits = TRI->getNumRegUnits();
362 NumStackObjects = MF->getFrameInfo().getNumObjects();
363 ObjectIndexBegin = MF->getFrameInfo().getObjectIndexBegin();
364 MBBReachingDefs.init(MF->getNumBlockIDs());
365 // Initialize the MBBOutRegsInfos
366 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
367 LoopTraversal Traversal;
368 TraversedMBBOrder = Traversal.traverse(*MF);
369}
370
372 // Traverse the basic blocks.
373 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
374 processBasicBlock(TraversedMBB);
375#ifndef NDEBUG
376 // Make sure reaching defs are sorted and unique.
377 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
378 MBBNumber != NumBlockIDs; ++MBBNumber) {
379 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
380 int LastDef = ReachingDefDefaultVal;
381 for (int Def :
382 MBBReachingDefs.defs(MBBNumber, static_cast<MCRegUnit>(Unit))) {
383 assert(Def > LastDef && "Defs must be sorted and unique");
384 LastDef = Def;
385 }
386 }
387 }
388#endif
389}
390
392 assert(InstIds.count(MI) && "Unexpected machine instuction.");
393 int InstId = InstIds.lookup(MI);
394 int DefRes = ReachingDefDefaultVal;
395 unsigned MBBNumber = MI->getParent()->getNumber();
396 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
397 "Unexpected basic block number.");
398 int LatestDef = ReachingDefDefaultVal;
399
400 if (Reg.isStack()) {
401 // Check that there was a reaching def.
402 int FrameIndex = Reg.stackSlotIndex();
403 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
404 if (Lookup == MBBFrameObjsReachingDefs.end())
405 return LatestDef;
406 auto &Defs = Lookup->second;
407 for (int Def : Defs) {
408 if (Def >= InstId)
409 break;
410 DefRes = Def;
411 }
412 LatestDef = std::max(LatestDef, DefRes);
413 return LatestDef;
414 }
415
416 for (MCRegUnit Unit : TRI->regunits(Reg)) {
417 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
418 if (Def >= InstId)
419 break;
420 DefRes = Def;
421 }
422 LatestDef = std::max(LatestDef, DefRes);
423 }
424 return LatestDef;
425}
426
427MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
428 Register Reg) const {
429 return hasLocalDefBefore(MI, Reg)
430 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
431 : nullptr;
432}
433
435 Register Reg) const {
436 MachineBasicBlock *ParentA = A->getParent();
437 MachineBasicBlock *ParentB = B->getParent();
438 if (ParentA != ParentB)
439 return false;
440
441 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
442}
443
444MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
445 int InstId) const {
446 assert(static_cast<size_t>(MBB->getNumber()) <
447 MBBReachingDefs.numBlockIDs() &&
448 "Unexpected basic block number.");
449 assert(InstId < static_cast<int>(MBB->size()) &&
450 "Unexpected instruction id.");
451
452 if (InstId < 0)
453 return nullptr;
454
455 for (auto &MI : *MBB) {
456 auto F = InstIds.find(&MI);
457 if (F != InstIds.end() && F->second == InstId)
458 return &MI;
459 }
460
461 return nullptr;
462}
463
465 assert(InstIds.count(MI) && "Unexpected machine instuction.");
466 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
467}
468
470 return getReachingDef(MI, Reg) >= 0;
471}
472
474 InstSet &Uses) const {
475 MachineBasicBlock *MBB = Def->getParent();
477 while (++MI != MBB->end()) {
478 if (MI->isDebugInstr())
479 continue;
480
481 // If/when we find a new reaching def, we know that there's no more uses
482 // of 'Def'.
483 if (getReachingLocalMIDef(&*MI, Reg) != Def)
484 return;
485
486 for (auto &MO : MI->operands()) {
487 if (!isValidRegUseOf(MO, Reg, TRI))
488 continue;
489
490 Uses.insert(&*MI);
491 if (MO.isKill())
492 return;
493 }
494 }
495}
496
498 InstSet &Uses) const {
499 for (MachineInstr &MI :
500 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
501 for (auto &MO : MI.operands()) {
502 if (!isValidRegUseOf(MO, Reg, TRI))
503 continue;
504 if (getReachingDef(&MI, Reg) >= 0)
505 return false;
506 Uses.insert(&MI);
507 }
508 }
509 auto Last = MBB->getLastNonDebugInstr();
510 if (Last == MBB->end())
511 return true;
512 return isReachingDefLiveOut(&*Last, Reg);
513}
514
516 InstSet &Uses) const {
517 MachineBasicBlock *MBB = MI->getParent();
518
519 // Collect the uses that each def touches within the block.
521
522 // Handle live-out values.
523 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
524 if (LiveOut != MI)
525 return;
526
527 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
529 while (!ToVisit.empty()) {
531 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
532 continue;
533 if (getLiveInUses(MBB, Reg, Uses))
534 llvm::append_range(ToVisit, MBB->successors());
535 Visited.insert(MBB);
536 }
537 }
538}
539
541 InstSet &Defs) const {
542 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
543 Defs.insert(Def);
544 return;
545 }
546
547 for (auto *MBB : MI->getParent()->predecessors())
548 getLiveOuts(MBB, Reg, Defs);
549}
550
552 InstSet &Defs) const {
554 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
555}
556
558 InstSet &Defs, BlockSet &VisitedBBs) const {
559 if (VisitedBBs.count(MBB))
560 return;
561
562 VisitedBBs.insert(MBB);
563 LiveRegUnits LiveRegs(*TRI);
564 LiveRegs.addLiveOuts(*MBB);
565 if (Reg.isPhysical() && LiveRegs.available(Reg))
566 return;
567
568 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
569 Defs.insert(Def);
570 else
571 for (auto *Pred : MBB->predecessors())
572 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
573}
574
576 Register Reg) const {
577 // If there's a local def before MI, return it.
578 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
579 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
580 return LocalDef;
581
583 MachineBasicBlock *Parent = MI->getParent();
584 for (auto *Pred : Parent->predecessors())
585 getLiveOuts(Pred, Reg, Incoming);
586
587 // Check that we have a single incoming value and that it does not
588 // come from the same block as MI - since it would mean that the def
589 // is executed after MI.
590 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
591 return *Incoming.begin();
592 return nullptr;
593}
594
596 unsigned Idx) const {
597 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
598 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
599}
600
602 MachineOperand &MO) const {
603 assert(MO.isReg() && "Expected register operand");
604 return getUniqueReachingMIDef(MI, MO.getReg());
605}
606
608 MachineBasicBlock *MBB = MI->getParent();
609 LiveRegUnits LiveRegs(*TRI);
610 LiveRegs.addLiveOuts(*MBB);
611
612 // Yes if the register is live out of the basic block.
613 if (!LiveRegs.available(Reg))
614 return true;
615
616 // Walk backwards through the block to see if the register is live at some
617 // point.
618 for (MachineInstr &Last :
619 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
620 LiveRegs.stepBackward(Last);
621 if (!LiveRegs.available(Reg))
622 return InstIds.lookup(&Last) > InstIds.lookup(MI);
623 }
624 return false;
625}
626
628 MachineBasicBlock *MBB = MI->getParent();
629 auto Last = MBB->getLastNonDebugInstr();
630 if (Last != MBB->end() &&
631 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
632 return true;
633
634 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
635 return Def == getReachingLocalMIDef(MI, Reg);
636
637 return false;
638}
639
641 Register Reg) const {
642 MachineBasicBlock *MBB = MI->getParent();
643 LiveRegUnits LiveRegs(*TRI);
644 LiveRegs.addLiveOuts(*MBB);
645 if (Reg.isPhysical() && LiveRegs.available(Reg))
646 return false;
647
648 auto Last = MBB->getLastNonDebugInstr();
649 int Def = getReachingDef(MI, Reg);
650 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
651 return false;
652
653 // Finally check that the last instruction doesn't redefine the register.
654 for (auto &MO : Last->operands())
655 if (isValidRegDefOf(MO, Reg, TRI))
656 return false;
657
658 return true;
659}
660
662 Register Reg) const {
663 LiveRegUnits LiveRegs(*TRI);
664 LiveRegs.addLiveOuts(*MBB);
665 if (Reg.isPhysical() && LiveRegs.available(Reg))
666 return nullptr;
667
668 auto Last = MBB->getLastNonDebugInstr();
669 if (Last == MBB->end())
670 return nullptr;
671
672 // Check if Last is the definition
673 if (Reg.isStack()) {
674 int FrameIndex = Reg.stackSlotIndex();
675 if (isFIDef(*Last, FrameIndex, TII))
676 return &*Last;
677 } else {
678 for (auto &MO : Last->operands())
679 if (isValidRegDefOf(MO, Reg, TRI))
680 return &*Last;
681 }
682
683 int Def = getReachingDef(&*Last, Reg);
684 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
685}
686
688 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
689 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
690 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
691}
692
693// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
694// not define a register that is used by any instructions, after and including,
695// 'To'. These instructions also must not redefine any of Froms operands.
696template <typename Iterator>
697bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
698 if (From->getParent() != To->getParent() || From == To)
699 return false;
700
701 SmallSet<Register, 2> Defs;
702 // First check that From would compute the same value if moved.
703 for (auto &MO : From->operands()) {
704 if (!isValidReg(MO))
705 continue;
706 if (MO.isDef())
707 Defs.insert(MO.getReg());
708 else if (!hasSameReachingDef(From, To, MO.getReg()))
709 return false;
710 }
711
712 // Now walk checking that the rest of the instructions will compute the same
713 // value and that we're not overwriting anything. Don't move the instruction
714 // past any memory, control-flow or other ambiguous instructions.
715 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
716 if (mayHaveSideEffects(*I))
717 return false;
718 for (auto &MO : I->operands())
719 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
720 return false;
721 }
722 return true;
723}
724
726 MachineInstr *To) const {
727 using Iterator = MachineBasicBlock::iterator;
728 // Walk forwards until we find the instruction.
729 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
730 if (&*I == To)
731 return isSafeToMove<Iterator>(From, To);
732 return false;
733}
734
736 MachineInstr *To) const {
738 // Walk backwards until we find the instruction.
739 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
740 if (&*I == To)
741 return isSafeToMove<Iterator>(From, To);
742 return false;
743}
744
751
753 InstSet &Ignore) const {
755 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
756}
757
758bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
759 InstSet &ToRemove, InstSet &Ignore) const {
760 if (Visited.count(MI) || Ignore.count(MI))
761 return true;
762 else if (mayHaveSideEffects(*MI)) {
763 // Unless told to ignore the instruction, don't remove anything which has
764 // side effects.
765 return false;
766 }
767
768 Visited.insert(MI);
769 for (auto &MO : MI->operands()) {
770 if (!isValidRegDef(MO))
771 continue;
772
774 getGlobalUses(MI, MO.getReg(), Uses);
775
776 for (auto *I : Uses) {
777 if (Ignore.count(I) || ToRemove.count(I))
778 continue;
779 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
780 return false;
781 }
782 }
783 ToRemove.insert(MI);
784 return true;
785}
786
788 InstSet &Dead) const {
789 Dead.insert(MI);
790 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
791 if (mayHaveSideEffects(*Def))
792 return false;
793
794 unsigned LiveDefs = 0;
795 for (auto &MO : Def->operands()) {
796 if (!isValidRegDef(MO))
797 continue;
798 if (!MO.isDead())
799 ++LiveDefs;
800 }
801
802 if (LiveDefs > 1)
803 return false;
804
806 getGlobalUses(Def, Reg, Uses);
808 };
809
810 for (auto &MO : MI->operands()) {
811 if (!isValidRegUse(MO))
812 continue;
813 if (MachineInstr *Def = getMIOperand(MI, MO))
814 if (IsDead(Def, MO.getReg()))
816 }
817}
818
823
825 InstSet &Ignore) const {
826 // Check for any uses of the register after MI.
827 if (isRegUsedAfter(MI, Reg)) {
828 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
830 getGlobalUses(Def, Reg, Uses);
832 return false;
833 } else
834 return false;
835 }
836
837 MachineBasicBlock *MBB = MI->getParent();
838 // Check for any defs after MI.
839 if (isRegDefinedAfter(MI, Reg)) {
841 for (auto E = MBB->end(); I != E; ++I) {
842 if (Ignore.count(&*I))
843 continue;
844 for (auto &MO : I->operands())
845 if (isValidRegDefOf(MO, Reg, TRI))
846 return false;
847 }
848 }
849 return true;
850}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo & RDI
ReachingDefInfo InstSet InstSet & Ignore
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
A set of register units.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool isValidRegUseOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool mayHaveSideEffects(MachineInstr &MI)
static bool isValidReg(const MachineOperand &MO)
static bool isFIDef(const MachineInstr &MI, int FrameIndex, const TargetInstrInfo *TII)
static bool isValidRegDef(const MachineOperand &MO)
static bool isValidRegDefOf(const MachineOperand &MO, Register Reg, const TargetRegisterInfo *TRI)
static bool isValidRegUse(const MachineOperand &MO)
Remove Loads Into Fake Uses
bool IsDead
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
A set of register units used to track register liveness.
This class provides the basic blocks traversal order used by passes like ReachingDefAnalysis and Exec...
TraversalOrder traverse(MachineFunction &MF)
An RAII based helper class to modify MachineFunctionProperties when running pass.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
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.
Properties which a MachineFunction may have at a given point in time.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
const MachineBasicBlock & front() const
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
mop_range operands()
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineFunctionProperties getRequiredProperties() const override
This class provides the reaching def analysis.
MachineInstr * getUniqueReachingMIDef(MachineInstr *MI, Register Reg) const
If a single MachineInstr creates the reaching definition, then return it.
bool isReachingDefLiveOut(MachineInstr *MI, Register Reg) const
Return whether the reaching def for MI also is live out of its parent block.
bool isSafeToMoveForwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved forwards to just before To.
int getReachingDef(MachineInstr *MI, Register Reg) const
Provides the instruction id of the closest reaching def instruction of Reg that reaches MI,...
void run(MachineFunction &mf)
void getReachingLocalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Provides the uses, in the same block as MI, of register that MI defines.
int getClearance(MachineInstr *MI, Register Reg) const
Provides the clearance - the number of instructions since the closest reaching def instuction of Reg ...
bool isRegDefinedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is defined after MI.
void init()
Initialize data structures.
void print(raw_ostream &OS)
bool hasLocalDefBefore(MachineInstr *MI, Register Reg) const
Provide whether the register has been defined in the same basic block as, and before,...
void reset()
Re-run the analysis.
void getGlobalUses(MachineInstr *MI, Register Reg, InstSet &Uses) const
Collect the users of the value stored in Reg, which is defined by MI.
MachineInstr * getMIOperand(MachineInstr *MI, unsigned Idx) const
If a single MachineInstr creates the reaching definition, for MIs operand at Idx, then return it.
void getLiveOuts(MachineBasicBlock *MBB, Register Reg, InstSet &Defs, BlockSet &VisitedBBs) const
Search MBB for a definition of Reg and insert it into Defs.
void traverse()
Traverse the machine function, mapping definitions.
bool isSafeToMoveBackwards(MachineInstr *From, MachineInstr *To) const
Return whether From can be moved backwards to just after To.
void collectKilledOperands(MachineInstr *MI, InstSet &Dead) const
Assuming MI is dead, recursively search the incoming operands which are killed by MI and collect thos...
bool hasSameReachingDef(MachineInstr *A, MachineInstr *B, Register Reg) const
Return whether A and B use the same def of Reg.
bool isRegUsedAfter(MachineInstr *MI, Register Reg) const
Return whether the given register is used after MI, whether it's a local use or a live out.
void getGlobalReachingDefs(MachineInstr *MI, Register Reg, InstSet &Defs) const
Collect all possible definitions of the value stored in Reg, which is used by MI.
bool isSafeToRemove(MachineInstr *MI, InstSet &ToRemove) const
Return whether removing this instruction will have no effect on the program, returning the redundant ...
MachineInstr * getLocalLiveOutMIDef(MachineBasicBlock *MBB, Register Reg) const
Return the local MI that produces the live out value for Reg, or nullptr for a non-live out or non-lo...
bool invalidate(MachineFunction &F, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
bool getLiveInUses(MachineBasicBlock *MBB, Register Reg, InstSet &Uses) const
For the given block, collect the instructions that use the live-in value of the provided register.
bool isSafeToDefRegAt(MachineInstr *MI, Register Reg) const
Return whether a MachineInstr could be inserted at MI and safely define the given register without af...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2StackSlot(int FI)
Convert a non-negative frame index to a stack slot register value.
Definition Register.h:51
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:183
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Dead
Unused definition.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2198
LLVM_ABI Printable printRegUnit(MCRegUnit Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
MachineBasicBlock * MBB
The basic block.
bool IsDone
True if the block that is ready for its final round of processing.
bool PrimaryPass
True if this is the first time we process the basic block.