LLVM 22.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
53}
54
58
61 MachineFunctionAnalysisManager::Invalidator &) {
62 // Check whether the analysis, all analyses on machine functions, or the
63 // machine function's CFG have been preserved.
64 auto PAC = PA.getChecker<ReachingDefAnalysis>();
65 return !PAC.preserved() &&
66 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
67 !PAC.preservedSet<CFGAnalyses>();
68}
69
74
79
80static bool isValidReg(const MachineOperand &MO) {
81 return MO.isReg() && MO.getReg();
82}
83
84static bool isValidRegUse(const MachineOperand &MO) {
85 return isValidReg(MO) && MO.isUse();
86}
87
89 const TargetRegisterInfo *TRI) {
90 if (!isValidRegUse(MO))
91 return false;
92 return TRI->regsOverlap(MO.getReg(), Reg);
93}
94
95static bool isValidRegDef(const MachineOperand &MO) {
96 return isValidReg(MO) && MO.isDef();
97}
98
100 const TargetRegisterInfo *TRI) {
101 if (!isValidRegDef(MO))
102 return false;
103 return TRI->regsOverlap(MO.getReg(), Reg);
104}
105
106static bool isFIDef(const MachineInstr &MI, int FrameIndex,
107 const TargetInstrInfo *TII) {
108 int DefFrameIndex = 0;
109 int SrcFrameIndex = 0;
110 if (TII->isStoreToStackSlot(MI, DefFrameIndex) ||
111 TII->isStackSlotCopy(MI, DefFrameIndex, SrcFrameIndex))
112 return DefFrameIndex == FrameIndex;
113 return false;
114}
115
116void ReachingDefInfo::enterBasicBlock(MachineBasicBlock *MBB) {
117 unsigned MBBNumber = MBB->getNumber();
118 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
119 "Unexpected basic block number.");
120 MBBReachingDefs.startBasicBlock(MBBNumber, NumRegUnits);
121
122 // Reset instruction counter in each basic block.
123 CurInstr = 0;
124
125 // Set up LiveRegs to represent registers entering MBB.
126 // Default values are 'nothing happened a long time ago'.
127 if (LiveRegs.empty())
128 LiveRegs.assign(NumRegUnits, ReachingDefDefaultVal);
129
130 // This is the entry block.
131 if (MBB->pred_empty()) {
132 for (const auto &LI : MBB->liveins()) {
133 for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
134 // Treat function live-ins as if they were defined just before the first
135 // instruction. Usually, function arguments are set up immediately
136 // before the call.
137 if (LiveRegs[Unit] != -1) {
138 LiveRegs[Unit] = -1;
139 MBBReachingDefs.append(MBBNumber, Unit, -1);
140 }
141 }
142 }
143 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": entry\n");
144 return;
145 }
146
147 // Try to coalesce live-out registers from predecessors.
148 for (MachineBasicBlock *pred : MBB->predecessors()) {
149 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
150 "Should have pre-allocated MBBInfos for all MBBs");
151 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
152 // Incoming is null if this is a backedge from a BB
153 // we haven't processed yet
154 if (Incoming.empty())
155 continue;
156
157 // Find the most recent reaching definition from a predecessor.
158 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
159 LiveRegs[Unit] = std::max(LiveRegs[Unit], Incoming[Unit]);
160 }
161
162 // Insert the most recent reaching definition we found.
163 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit)
164 if (LiveRegs[Unit] != ReachingDefDefaultVal)
165 MBBReachingDefs.append(MBBNumber, Unit, LiveRegs[Unit]);
166}
167
168void ReachingDefInfo::leaveBasicBlock(MachineBasicBlock *MBB) {
169 assert(!LiveRegs.empty() && "Must enter basic block first.");
170 unsigned MBBNumber = MBB->getNumber();
171 assert(MBBNumber < MBBOutRegsInfos.size() &&
172 "Unexpected basic block number.");
173 // Save register clearances at end of MBB - used by enterBasicBlock().
174 MBBOutRegsInfos[MBBNumber] = LiveRegs;
175
176 // While processing the basic block, we kept `Def` relative to the start
177 // of the basic block for convenience. However, future use of this information
178 // only cares about the clearance from the end of the block, so adjust
179 // everything to be relative to the end of the basic block.
180 for (int &OutLiveReg : MBBOutRegsInfos[MBBNumber])
181 if (OutLiveReg != ReachingDefDefaultVal)
182 OutLiveReg -= CurInstr;
183 LiveRegs.clear();
184}
185
186void ReachingDefInfo::processDefs(MachineInstr *MI) {
187 assert(!MI->isDebugInstr() && "Won't process debug instructions");
188
189 unsigned MBBNumber = MI->getParent()->getNumber();
190 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
191 "Unexpected basic block number.");
192
193 for (auto &MO : MI->operands()) {
194 if (MO.isFI()) {
195 int FrameIndex = MO.getIndex();
196 assert(FrameIndex >= 0 && "Can't handle negative frame indicies yet!");
197 if (!isFIDef(*MI, FrameIndex, TII))
198 continue;
199 MBBFrameObjsReachingDefs[{MBBNumber, FrameIndex}].push_back(CurInstr);
200 }
201 if (!isValidRegDef(MO))
202 continue;
203 for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
204 // This instruction explicitly defines the current reg unit.
205 LLVM_DEBUG(dbgs() << printRegUnit(Unit, TRI) << ":\t" << CurInstr << '\t'
206 << *MI);
207
208 // How many instructions since this reg unit was last written?
209 if (LiveRegs[Unit] != CurInstr) {
210 LiveRegs[Unit] = CurInstr;
211 MBBReachingDefs.append(MBBNumber, Unit, CurInstr);
212 }
213 }
214 }
215 InstIds[MI] = CurInstr;
216 ++CurInstr;
217}
218
219void ReachingDefInfo::reprocessBasicBlock(MachineBasicBlock *MBB) {
220 unsigned MBBNumber = MBB->getNumber();
221 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
222 "Unexpected basic block number.");
223
224 // Count number of non-debug instructions for end of block adjustment.
225 auto NonDbgInsts =
227 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
228
229 // When reprocessing a block, the only thing we need to do is check whether
230 // there is now a more recent incoming reaching definition from a predecessor.
231 for (MachineBasicBlock *pred : MBB->predecessors()) {
232 assert(unsigned(pred->getNumber()) < MBBOutRegsInfos.size() &&
233 "Should have pre-allocated MBBInfos for all MBBs");
234 const LiveRegsDefInfo &Incoming = MBBOutRegsInfos[pred->getNumber()];
235 // Incoming may be empty for dead predecessors.
236 if (Incoming.empty())
237 continue;
238
239 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
240 int Def = Incoming[Unit];
241 if (Def == ReachingDefDefaultVal)
242 continue;
243
244 auto Defs = MBBReachingDefs.defs(MBBNumber, Unit);
245 if (!Defs.empty() && Defs.front() < 0) {
246 if (Defs.front() >= Def)
247 continue;
248
249 // Update existing reaching def from predecessor to a more recent one.
250 MBBReachingDefs.replaceFront(MBBNumber, Unit, Def);
251 } else {
252 // Insert new reaching def from predecessor.
253 MBBReachingDefs.prepend(MBBNumber, Unit, Def);
254 }
255
256 // Update reaching def at end of BB. Keep in mind that these are
257 // adjusted relative to the end of the basic block.
258 if (MBBOutRegsInfos[MBBNumber][Unit] < Def - NumInsts)
259 MBBOutRegsInfos[MBBNumber][Unit] = Def - NumInsts;
260 }
261 }
262}
263
264void ReachingDefInfo::processBasicBlock(
265 const LoopTraversal::TraversedMBBInfo &TraversedMBB) {
266 MachineBasicBlock *MBB = TraversedMBB.MBB;
268 << (!TraversedMBB.IsDone ? ": incomplete\n"
269 : ": all preds known\n"));
270
271 if (!TraversedMBB.PrimaryPass) {
272 // Reprocess MBB that is part of a loop.
273 reprocessBasicBlock(MBB);
274 return;
275 }
276
277 enterBasicBlock(MBB);
278 for (MachineInstr &MI :
280 processDefs(&MI);
281 leaveBasicBlock(MBB);
282}
283
285 MF = &mf;
286 const TargetSubtargetInfo &STI = MF->getSubtarget();
287 TRI = STI.getRegisterInfo();
288 TII = STI.getInstrInfo();
289 LLVM_DEBUG(dbgs() << "********** REACHING DEFINITION ANALYSIS **********\n");
290 init();
291 traverse();
292}
293
295 OS << "RDA results for " << MF->getName() << "\n";
296 int Num = 0;
299 for (MachineBasicBlock &MBB : *MF) {
300 for (MachineInstr &MI : MBB) {
301 for (MachineOperand &MO : MI.operands()) {
302 Register Reg;
303 if (MO.isFI()) {
304 int FrameIndex = MO.getIndex();
305 assert(FrameIndex >= 0 &&
306 "Can't handle negative frame indicies yet!");
307 Reg = Register::index2StackSlot(FrameIndex);
308 } else if (MO.isReg()) {
309 if (MO.isDef())
310 continue;
311 Reg = MO.getReg();
312 if (!Reg.isValid())
313 continue;
314 } else
315 continue;
316 Defs.clear();
317 getGlobalReachingDefs(&MI, Reg, Defs);
318 MO.print(OS, TRI);
320 for (MachineInstr *Def : Defs)
321 Nums.push_back(InstToNumMap[Def]);
322 llvm::sort(Nums);
323 OS << ":{ ";
324 for (int Num : Nums)
325 OS << Num << " ";
326 OS << "}\n";
327 }
328 OS << Num << ": " << MI << "\n";
329 InstToNumMap[&MI] = Num;
330 ++Num;
331 }
332 }
333}
334
336 RDI.run(mf);
337 return false;
338}
339
341 // Clear the internal vectors.
342 MBBOutRegsInfos.clear();
343 MBBReachingDefs.clear();
344 MBBFrameObjsReachingDefs.clear();
345 InstIds.clear();
346 LiveRegs.clear();
347}
348
351 init();
352 traverse();
353}
354
356 NumRegUnits = TRI->getNumRegUnits();
357 NumStackObjects = MF->getFrameInfo().getNumObjects();
358 ObjectIndexBegin = MF->getFrameInfo().getObjectIndexBegin();
359 MBBReachingDefs.init(MF->getNumBlockIDs());
360 // Initialize the MBBOutRegsInfos
361 MBBOutRegsInfos.resize(MF->getNumBlockIDs());
362 LoopTraversal Traversal;
363 TraversedMBBOrder = Traversal.traverse(*MF);
364}
365
367 // Traverse the basic blocks.
368 for (LoopTraversal::TraversedMBBInfo TraversedMBB : TraversedMBBOrder)
369 processBasicBlock(TraversedMBB);
370#ifndef NDEBUG
371 // Make sure reaching defs are sorted and unique.
372 for (unsigned MBBNumber = 0, NumBlockIDs = MF->getNumBlockIDs();
373 MBBNumber != NumBlockIDs; ++MBBNumber) {
374 for (unsigned Unit = 0; Unit != NumRegUnits; ++Unit) {
375 int LastDef = ReachingDefDefaultVal;
376 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
377 assert(Def > LastDef && "Defs must be sorted and unique");
378 LastDef = Def;
379 }
380 }
381 }
382#endif
383}
384
386 assert(InstIds.count(MI) && "Unexpected machine instuction.");
387 int InstId = InstIds.lookup(MI);
388 int DefRes = ReachingDefDefaultVal;
389 unsigned MBBNumber = MI->getParent()->getNumber();
390 assert(MBBNumber < MBBReachingDefs.numBlockIDs() &&
391 "Unexpected basic block number.");
392 int LatestDef = ReachingDefDefaultVal;
393
394 if (Reg.isStack()) {
395 // Check that there was a reaching def.
396 int FrameIndex = Reg.stackSlotIndex();
397 auto Lookup = MBBFrameObjsReachingDefs.find({MBBNumber, FrameIndex});
398 if (Lookup == MBBFrameObjsReachingDefs.end())
399 return LatestDef;
400 auto &Defs = Lookup->second;
401 for (int Def : Defs) {
402 if (Def >= InstId)
403 break;
404 DefRes = Def;
405 }
406 LatestDef = std::max(LatestDef, DefRes);
407 return LatestDef;
408 }
409
410 for (MCRegUnit Unit : TRI->regunits(Reg)) {
411 for (int Def : MBBReachingDefs.defs(MBBNumber, Unit)) {
412 if (Def >= InstId)
413 break;
414 DefRes = Def;
415 }
416 LatestDef = std::max(LatestDef, DefRes);
417 }
418 return LatestDef;
419}
420
421MachineInstr *ReachingDefInfo::getReachingLocalMIDef(MachineInstr *MI,
422 Register Reg) const {
423 return hasLocalDefBefore(MI, Reg)
424 ? getInstFromId(MI->getParent(), getReachingDef(MI, Reg))
425 : nullptr;
426}
427
429 Register Reg) const {
430 MachineBasicBlock *ParentA = A->getParent();
431 MachineBasicBlock *ParentB = B->getParent();
432 if (ParentA != ParentB)
433 return false;
434
435 return getReachingDef(A, Reg) == getReachingDef(B, Reg);
436}
437
438MachineInstr *ReachingDefInfo::getInstFromId(MachineBasicBlock *MBB,
439 int InstId) const {
440 assert(static_cast<size_t>(MBB->getNumber()) <
441 MBBReachingDefs.numBlockIDs() &&
442 "Unexpected basic block number.");
443 assert(InstId < static_cast<int>(MBB->size()) &&
444 "Unexpected instruction id.");
445
446 if (InstId < 0)
447 return nullptr;
448
449 for (auto &MI : *MBB) {
450 auto F = InstIds.find(&MI);
451 if (F != InstIds.end() && F->second == InstId)
452 return &MI;
453 }
454
455 return nullptr;
456}
457
459 assert(InstIds.count(MI) && "Unexpected machine instuction.");
460 return InstIds.lookup(MI) - getReachingDef(MI, Reg);
461}
462
464 return getReachingDef(MI, Reg) >= 0;
465}
466
468 InstSet &Uses) const {
469 MachineBasicBlock *MBB = Def->getParent();
471 while (++MI != MBB->end()) {
472 if (MI->isDebugInstr())
473 continue;
474
475 // If/when we find a new reaching def, we know that there's no more uses
476 // of 'Def'.
477 if (getReachingLocalMIDef(&*MI, Reg) != Def)
478 return;
479
480 for (auto &MO : MI->operands()) {
481 if (!isValidRegUseOf(MO, Reg, TRI))
482 continue;
483
484 Uses.insert(&*MI);
485 if (MO.isKill())
486 return;
487 }
488 }
489}
490
492 InstSet &Uses) const {
493 for (MachineInstr &MI :
494 instructionsWithoutDebug(MBB->instr_begin(), MBB->instr_end())) {
495 for (auto &MO : MI.operands()) {
496 if (!isValidRegUseOf(MO, Reg, TRI))
497 continue;
498 if (getReachingDef(&MI, Reg) >= 0)
499 return false;
500 Uses.insert(&MI);
501 }
502 }
503 auto Last = MBB->getLastNonDebugInstr();
504 if (Last == MBB->end())
505 return true;
506 return isReachingDefLiveOut(&*Last, Reg);
507}
508
510 InstSet &Uses) const {
511 MachineBasicBlock *MBB = MI->getParent();
512
513 // Collect the uses that each def touches within the block.
515
516 // Handle live-out values.
517 if (auto *LiveOut = getLocalLiveOutMIDef(MI->getParent(), Reg)) {
518 if (LiveOut != MI)
519 return;
520
521 SmallVector<MachineBasicBlock *, 4> ToVisit(MBB->successors());
523 while (!ToVisit.empty()) {
525 if (Visited.count(MBB) || !MBB->isLiveIn(Reg))
526 continue;
527 if (getLiveInUses(MBB, Reg, Uses))
528 llvm::append_range(ToVisit, MBB->successors());
529 Visited.insert(MBB);
530 }
531 }
532}
533
535 InstSet &Defs) const {
536 if (auto *Def = getUniqueReachingMIDef(MI, Reg)) {
537 Defs.insert(Def);
538 return;
539 }
540
541 for (auto *MBB : MI->getParent()->predecessors())
542 getLiveOuts(MBB, Reg, Defs);
543}
544
546 InstSet &Defs) const {
548 getLiveOuts(MBB, Reg, Defs, VisitedBBs);
549}
550
552 InstSet &Defs, BlockSet &VisitedBBs) const {
553 if (VisitedBBs.count(MBB))
554 return;
555
556 VisitedBBs.insert(MBB);
557 LiveRegUnits LiveRegs(*TRI);
558 LiveRegs.addLiveOuts(*MBB);
559 if (Reg.isPhysical() && LiveRegs.available(Reg))
560 return;
561
562 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
563 Defs.insert(Def);
564 else
565 for (auto *Pred : MBB->predecessors())
566 getLiveOuts(Pred, Reg, Defs, VisitedBBs);
567}
568
570 Register Reg) const {
571 // If there's a local def before MI, return it.
572 MachineInstr *LocalDef = getReachingLocalMIDef(MI, Reg);
573 if (LocalDef && InstIds.lookup(LocalDef) < InstIds.lookup(MI))
574 return LocalDef;
575
577 MachineBasicBlock *Parent = MI->getParent();
578 for (auto *Pred : Parent->predecessors())
579 getLiveOuts(Pred, Reg, Incoming);
580
581 // Check that we have a single incoming value and that it does not
582 // come from the same block as MI - since it would mean that the def
583 // is executed after MI.
584 if (Incoming.size() == 1 && (*Incoming.begin())->getParent() != Parent)
585 return *Incoming.begin();
586 return nullptr;
587}
588
590 unsigned Idx) const {
591 assert(MI->getOperand(Idx).isReg() && "Expected register operand");
592 return getUniqueReachingMIDef(MI, MI->getOperand(Idx).getReg());
593}
594
596 MachineOperand &MO) const {
597 assert(MO.isReg() && "Expected register operand");
598 return getUniqueReachingMIDef(MI, MO.getReg());
599}
600
602 MachineBasicBlock *MBB = MI->getParent();
603 LiveRegUnits LiveRegs(*TRI);
604 LiveRegs.addLiveOuts(*MBB);
605
606 // Yes if the register is live out of the basic block.
607 if (!LiveRegs.available(Reg))
608 return true;
609
610 // Walk backwards through the block to see if the register is live at some
611 // point.
612 for (MachineInstr &Last :
613 instructionsWithoutDebug(MBB->instr_rbegin(), MBB->instr_rend())) {
614 LiveRegs.stepBackward(Last);
615 if (!LiveRegs.available(Reg))
616 return InstIds.lookup(&Last) > InstIds.lookup(MI);
617 }
618 return false;
619}
620
622 MachineBasicBlock *MBB = MI->getParent();
623 auto Last = MBB->getLastNonDebugInstr();
624 if (Last != MBB->end() &&
625 getReachingDef(MI, Reg) != getReachingDef(&*Last, Reg))
626 return true;
627
628 if (auto *Def = getLocalLiveOutMIDef(MBB, Reg))
629 return Def == getReachingLocalMIDef(MI, Reg);
630
631 return false;
632}
633
635 Register Reg) const {
636 MachineBasicBlock *MBB = MI->getParent();
637 LiveRegUnits LiveRegs(*TRI);
638 LiveRegs.addLiveOuts(*MBB);
639 if (Reg.isPhysical() && LiveRegs.available(Reg))
640 return false;
641
642 auto Last = MBB->getLastNonDebugInstr();
643 int Def = getReachingDef(MI, Reg);
644 if (Last != MBB->end() && getReachingDef(&*Last, Reg) != Def)
645 return false;
646
647 // Finally check that the last instruction doesn't redefine the register.
648 for (auto &MO : Last->operands())
649 if (isValidRegDefOf(MO, Reg, TRI))
650 return false;
651
652 return true;
653}
654
656 Register Reg) const {
657 LiveRegUnits LiveRegs(*TRI);
658 LiveRegs.addLiveOuts(*MBB);
659 if (Reg.isPhysical() && LiveRegs.available(Reg))
660 return nullptr;
661
662 auto Last = MBB->getLastNonDebugInstr();
663 if (Last == MBB->end())
664 return nullptr;
665
666 if (Reg.isStack()) {
667 int FrameIndex = Reg.stackSlotIndex();
668 if (isFIDef(*Last, FrameIndex, TII))
669 return &*Last;
670 }
671
672 int Def = getReachingDef(&*Last, Reg);
673
674 for (auto &MO : Last->operands())
675 if (isValidRegDefOf(MO, Reg, TRI))
676 return &*Last;
677
678 return Def < 0 ? nullptr : getInstFromId(MBB, Def);
679}
680
682 return MI.mayLoadOrStore() || MI.mayRaiseFPException() ||
683 MI.hasUnmodeledSideEffects() || MI.isTerminator() ||
684 MI.isCall() || MI.isBarrier() || MI.isBranch() || MI.isReturn();
685}
686
687// Can we safely move 'From' to just before 'To'? To satisfy this, 'From' must
688// not define a register that is used by any instructions, after and including,
689// 'To'. These instructions also must not redefine any of Froms operands.
690template <typename Iterator>
691bool ReachingDefInfo::isSafeToMove(MachineInstr *From, MachineInstr *To) const {
692 if (From->getParent() != To->getParent() || From == To)
693 return false;
694
695 SmallSet<Register, 2> Defs;
696 // First check that From would compute the same value if moved.
697 for (auto &MO : From->operands()) {
698 if (!isValidReg(MO))
699 continue;
700 if (MO.isDef())
701 Defs.insert(MO.getReg());
702 else if (!hasSameReachingDef(From, To, MO.getReg()))
703 return false;
704 }
705
706 // Now walk checking that the rest of the instructions will compute the same
707 // value and that we're not overwriting anything. Don't move the instruction
708 // past any memory, control-flow or other ambiguous instructions.
709 for (auto I = ++Iterator(From), E = Iterator(To); I != E; ++I) {
710 if (mayHaveSideEffects(*I))
711 return false;
712 for (auto &MO : I->operands())
713 if (MO.isReg() && MO.getReg() && Defs.count(MO.getReg()))
714 return false;
715 }
716 return true;
717}
718
720 MachineInstr *To) const {
721 using Iterator = MachineBasicBlock::iterator;
722 // Walk forwards until we find the instruction.
723 for (auto I = Iterator(From), E = From->getParent()->end(); I != E; ++I)
724 if (&*I == To)
725 return isSafeToMove<Iterator>(From, To);
726 return false;
727}
728
730 MachineInstr *To) const {
732 // Walk backwards until we find the instruction.
733 for (auto I = Iterator(From), E = From->getParent()->rend(); I != E; ++I)
734 if (&*I == To)
735 return isSafeToMove<Iterator>(From, To);
736 return false;
737}
738
745
747 InstSet &Ignore) const {
749 return isSafeToRemove(MI, Visited, ToRemove, Ignore);
750}
751
752bool ReachingDefInfo::isSafeToRemove(MachineInstr *MI, InstSet &Visited,
753 InstSet &ToRemove, InstSet &Ignore) const {
754 if (Visited.count(MI) || Ignore.count(MI))
755 return true;
756 else if (mayHaveSideEffects(*MI)) {
757 // Unless told to ignore the instruction, don't remove anything which has
758 // side effects.
759 return false;
760 }
761
762 Visited.insert(MI);
763 for (auto &MO : MI->operands()) {
764 if (!isValidRegDef(MO))
765 continue;
766
768 getGlobalUses(MI, MO.getReg(), Uses);
769
770 for (auto *I : Uses) {
771 if (Ignore.count(I) || ToRemove.count(I))
772 continue;
773 if (!isSafeToRemove(I, Visited, ToRemove, Ignore))
774 return false;
775 }
776 }
777 ToRemove.insert(MI);
778 return true;
779}
780
782 InstSet &Dead) const {
783 Dead.insert(MI);
784 auto IsDead = [this, &Dead](MachineInstr *Def, Register Reg) {
785 if (mayHaveSideEffects(*Def))
786 return false;
787
788 unsigned LiveDefs = 0;
789 for (auto &MO : Def->operands()) {
790 if (!isValidRegDef(MO))
791 continue;
792 if (!MO.isDead())
793 ++LiveDefs;
794 }
795
796 if (LiveDefs > 1)
797 return false;
798
800 getGlobalUses(Def, Reg, Uses);
801 return llvm::set_is_subset(Uses, Dead);
802 };
803
804 for (auto &MO : MI->operands()) {
805 if (!isValidRegUse(MO))
806 continue;
807 if (MachineInstr *Def = getMIOperand(MI, MO))
808 if (IsDead(Def, MO.getReg()))
809 collectKilledOperands(Def, Dead);
810 }
811}
812
817
819 InstSet &Ignore) const {
820 // Check for any uses of the register after MI.
821 if (isRegUsedAfter(MI, Reg)) {
822 if (auto *Def = getReachingLocalMIDef(MI, Reg)) {
824 getGlobalUses(Def, Reg, Uses);
826 return false;
827 } else
828 return false;
829 }
830
831 MachineBasicBlock *MBB = MI->getParent();
832 // Check for any defs after MI.
833 if (isRegDefinedAfter(MI, Reg)) {
835 for (auto E = MBB->end(); I != E; ++I) {
836 if (Ignore.count(&*I))
837 continue;
838 for (auto &MO : I->operands())
839 if (isValidRegDefOf(MO, Reg, TRI))
840 return false;
841 }
842 }
843 return true;
844}
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:55
#define I(x, y, z)
Definition MD5.cpp:58
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
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.
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.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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:19
static Register index2StackSlot(int FI)
Convert a non-negative frame index to a stack slot register value.
Definition Register.h:48
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:181
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.
LLVM_ABI void initializeReachingDefInfoWrapperPassPass(PassRegistry &)
LLVM_ABI Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
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:2116
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1624
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
unsigned MCRegUnit
Register units are used to compute register aliasing.
Definition MCRegister.h:30
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.