LLVM 23.0.0git
DependencyGraph.cpp
Go to the documentation of this file.
1//===- DependencyGraph.cpp ------------------------------------------===//
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
10#include "llvm/ADT/ArrayRef.h"
14
15namespace llvm::sandboxir {
16
17User::op_iterator PredIterator::skipBadIt(User::op_iterator OpIt,
19 const DependencyGraph &DAG) {
20 auto Skip = [&DAG](auto OpIt) {
21 auto *I = dyn_cast<Instruction>((*OpIt).get());
22 return I == nullptr || DAG.getNode(I) == nullptr;
23 };
24 while (OpIt != OpItE && Skip(OpIt))
25 ++OpIt;
26 return OpIt;
27}
28
30 // If it's a DGNode then we dereference the operand iterator.
31 if (!isa<MemDGNode>(N)) {
32 assert(OpIt != OpItE && "Can't dereference end iterator!");
33 return DAG->getNode(cast<Instruction>((Value *)*OpIt));
34 }
35 // It's a MemDGNode, so we check if we return either the use-def operand,
36 // or a mem predecessor.
37 if (OpIt != OpItE)
38 return DAG->getNode(cast<Instruction>((Value *)*OpIt));
39 // It's a MemDGNode with OpIt == end, so we need to use MemIt.
40 assert(MemIt != cast<MemDGNode>(N)->MemPreds.end() &&
41 "Cant' dereference end iterator!");
42 return *MemIt;
43}
44
45PredIterator &PredIterator::operator++() {
46 // If it's a DGNode then we increment the use-def iterator.
47 if (!isa<MemDGNode>(N)) {
48 assert(OpIt != OpItE && "Already at end!");
49 ++OpIt;
50 // Skip operands that are not instructions or are outside the DAG.
51 OpIt = PredIterator::skipBadIt(OpIt, OpItE, *DAG);
52 return *this;
53 }
54 // It's a MemDGNode, so if we are not at the end of the use-def iterator we
55 // need to first increment that.
56 if (OpIt != OpItE) {
57 ++OpIt;
58 // Skip operands that are not instructions or are outside the DAG.
59 OpIt = PredIterator::skipBadIt(OpIt, OpItE, *DAG);
60 return *this;
61 }
62 // It's a MemDGNode with OpIt == end, so we need to increment MemIt.
63 assert(MemIt != cast<MemDGNode>(N)->MemPreds.end() && "Already at end!");
64 ++MemIt;
65 return *this;
66}
67
68bool PredIterator::operator==(const PredIterator &Other) const {
69 assert(DAG == Other.DAG && "Iterators of different DAGs!");
70 assert(N == Other.N && "Iterators of different nodes!");
71 return OpIt == Other.OpIt && MemIt == Other.MemIt;
72}
73
74User::user_iterator SuccIterator::skipOutOfScope(User::user_iterator UserIt,
75 User::user_iterator UserItE,
76 const DependencyGraph &DAG) {
77 auto Skip = [&DAG](User::user_iterator UserIt) {
78 auto *I = dyn_cast<Instruction>(*UserIt);
79 return I == nullptr || DAG.getNode(I) == nullptr;
80 };
81 while (UserIt != UserItE && Skip(UserIt))
82 ++UserIt;
83 return UserIt;
84}
85
87 // If it's a DGNode then we dereference the user iterator.
88 if (!isa<MemDGNode>(N)) {
89 assert(UserIt != UserItE && "Can't dereference end iterator!");
90 return DAG->getNode(cast<Instruction>((Value *)*UserIt));
91 }
92 // It's a MemDGNode, so we check if we return either the def-use operand,
93 // or a mem predecessor.
94 if (UserIt != UserItE)
95 return DAG->getNode(cast<Instruction>((Value *)*UserIt));
96 // It's a MemDGNode with UserIt == end, so we need to use MemIt.
97 assert(MemIt != cast<MemDGNode>(N)->MemSuccs.end() &&
98 "Cant' dereference end iterator!");
99 return *MemIt;
100}
101
103 // If it's a DGNode then we increment the use-def iterator.
104 if (!isa<MemDGNode>(N)) {
105 assert(UserIt != UserItE && "Already at end!");
106 ++UserIt;
107 // Skip users that are not instructions or are outside the DAG.
108 UserIt = SuccIterator::skipOutOfScope(UserIt, UserItE, *DAG);
109 return *this;
110 }
111 // It's a MemDGNode, so if we are not at the end of the def-use iterator we
112 // need to first increment that.
113 if (UserIt != UserItE) {
114 ++UserIt;
115 // Skip operands that are not instructions or are outside the DAG.
116 UserIt = SuccIterator::skipOutOfScope(UserIt, UserItE, *DAG);
117 return *this;
118 }
119 // It's a MemDGNode with UserIt == end, so we need to increment MemIt.
120 assert(MemIt != cast<MemDGNode>(N)->MemSuccs.end() && "Already at end!");
121 ++MemIt;
122 return *this;
123}
124
125bool SuccIterator::operator==(const SuccIterator &Other) const {
126 assert(DAG == Other.DAG && "Iterators of different DAGs!");
127 assert(N == Other.N && "Iterators of different nodes!");
128 return UserIt == Other.UserIt && MemIt == Other.MemIt;
129}
130
132 if (this->SB != nullptr)
133 this->SB->eraseFromBundle(this);
134 this->SB = &SB;
135}
136
138 if (SB == nullptr)
139 return;
140 SB->eraseFromBundle(this);
141}
142
143#ifndef NDEBUG
144void DGNode::print(raw_ostream &OS, bool PrintDeps) const {
145 OS << *I << " USuccs:" << UnscheduledSuccs << " UPreds:" << UnscheduledPreds
146 << " Sched:" << Scheduled << "\n";
147}
148void DGNode::dump() const { print(dbgs()); }
149void MemDGNode::print(raw_ostream &OS, bool PrintDeps) const {
150 DGNode::print(OS, false);
151 if (PrintDeps) {
152 // Print memory preds.
153 static constexpr unsigned Indent = 4;
154 for (auto *Pred : MemPreds)
155 OS.indent(Indent) << "<-" << *Pred->getInstruction() << "\n";
156 }
157}
158#endif // NDEBUG
159
160MemDGNode *
162 const DependencyGraph &DAG) {
163 Instruction *I = Intvl.top();
164 Instruction *BeforeI = Intvl.bottom();
165 // Walk down the chain looking for a mem-dep candidate instruction.
166 while (!DGNode::isMemDepNodeCandidate(I) && I != BeforeI)
167 I = I->getNextNode();
169 return nullptr;
170 return cast<MemDGNode>(DAG.getNode(I));
171}
172
173MemDGNode *
175 const DependencyGraph &DAG) {
176 Instruction *I = Intvl.bottom();
177 Instruction *AfterI = Intvl.top();
178 // Walk up the chain looking for a mem-dep candidate instruction.
179 while (!DGNode::isMemDepNodeCandidate(I) && I != AfterI)
180 I = I->getPrevNode();
182 return nullptr;
183 return cast<MemDGNode>(DAG.getNode(I));
184}
185
188 DependencyGraph &DAG) {
189 if (Instrs.empty())
190 return {};
191 auto *TopMemN = getTopMemDGNode(Instrs, DAG);
192 // If we couldn't find a mem node in range TopN - BotN then it's empty.
193 if (TopMemN == nullptr)
194 return {};
195 auto *BotMemN = getBotMemDGNode(Instrs, DAG);
196 assert(BotMemN != nullptr && "TopMemN should be null too!");
197 // Now that we have the mem-dep nodes, create and return the range.
198 return Interval<MemDGNode>(TopMemN, BotMemN);
199}
200
201DependencyGraph::DependencyType
202DependencyGraph::getRoughDepType(Instruction *FromI, Instruction *ToI) {
203 // TODO: Perhaps compile-time improvement by skipping if neither is mem?
204 if (FromI->mayWriteToMemory()) {
205 if (ToI->mayReadFromMemory())
206 return DependencyType::ReadAfterWrite;
207 if (ToI->mayWriteToMemory())
208 return DependencyType::WriteAfterWrite;
209 } else if (FromI->mayReadFromMemory()) {
210 if (ToI->mayWriteToMemory())
211 return DependencyType::WriteAfterRead;
212 }
214 return DependencyType::Control;
215 if (ToI->isTerminator())
216 return DependencyType::Control;
219 return DependencyType::Other;
220 return DependencyType::None;
221}
222
223static bool isOrdered(Instruction *I) {
224 auto IsOrdered = [](Instruction *I) {
225 if (auto *LI = dyn_cast<LoadInst>(I))
226 return !LI->isUnordered();
227 if (auto *SI = dyn_cast<StoreInst>(I))
228 return !SI->isUnordered();
230 return true;
231 return false;
232 };
233 bool Is = IsOrdered(I);
235 "An ordered instruction must be a MemDepCandidate!");
236 return Is;
237}
238
239bool DependencyGraph::alias(Instruction *SrcI, Instruction *DstI,
240 DependencyType DepType) {
241 std::optional<MemoryLocation> DstLocOpt =
243 if (!DstLocOpt)
244 return true;
245 // Check aliasing.
246 assert((SrcI->mayReadFromMemory() || SrcI->mayWriteToMemory()) &&
247 "Expected a mem instr");
248 // TODO: Check AABudget
249 ModRefInfo SrcModRef =
250 isOrdered(SrcI)
252 : Utils::aliasAnalysisGetModRefInfo(*BatchAA, SrcI, *DstLocOpt);
253 switch (DepType) {
254 case DependencyType::ReadAfterWrite:
255 case DependencyType::WriteAfterWrite:
256 return isModSet(SrcModRef);
257 case DependencyType::WriteAfterRead:
258 return isRefSet(SrcModRef);
259 default:
260 llvm_unreachable("Expected only RAW, WAW and WAR!");
261 }
262}
263
264bool DependencyGraph::hasDep(Instruction *SrcI, Instruction *DstI) {
265 DependencyType RoughDepType = getRoughDepType(SrcI, DstI);
266 switch (RoughDepType) {
267 case DependencyType::ReadAfterWrite:
268 case DependencyType::WriteAfterWrite:
269 case DependencyType::WriteAfterRead:
270 return alias(SrcI, DstI, RoughDepType);
271 case DependencyType::Control:
272 // Adding actual dep edges from PHIs/to terminator would just create too
273 // many edges, which would be bad for compile-time.
274 // So we ignore them in the DAG formation but handle them in the
275 // scheduler, while sorting the ready list.
276 return false;
277 case DependencyType::Other:
278 return true;
279 case DependencyType::None:
280 return false;
281 }
282 llvm_unreachable("Unknown DependencyType enum");
283}
284
285void DependencyGraph::scanAndAddDeps(MemDGNode &DstN,
286 const Interval<MemDGNode> &SrcScanRange) {
287 assert(isa<MemDGNode>(DstN) &&
288 "DstN is the mem dep destination, so it must be mem");
289 Instruction *DstI = DstN.getInstruction();
290 // Walk up the instruction chain from ScanRange bottom to top, looking for
291 // memory instrs that may alias.
292 for (MemDGNode &SrcN : reverse(SrcScanRange)) {
293 Instruction *SrcI = SrcN.getInstruction();
294 if (hasDep(SrcI, DstI))
295 DstN.addMemPred(&SrcN);
296 }
297}
298
299void DependencyGraph::setDefUseUnscheduledSuccs(
300 const Interval<Instruction> &NewInterval) {
301 // +---+
302 // | | Def
303 // | | |
304 // | | v
305 // | | Use
306 // +---+
307 // Set the intra-interval counters in NewInterval.
308 for (Instruction &I : NewInterval) {
309 unsigned CntUnschedPreds = 0;
310 for (Value *Op : I.operands()) {
311 auto *OpI = dyn_cast<Instruction>(Op);
312 if (OpI == nullptr)
313 continue;
314 // TODO: For now don't cross BBs.
315 if (OpI->getParent() != I.getParent())
316 continue;
317 if (!NewInterval.contains(OpI))
318 continue;
319 auto *OpN = getNode(OpI);
320 if (OpN == nullptr)
321 continue;
322 OpN->incrUnscheduledSuccs();
323 if (!OpN->scheduled())
324 ++CntUnschedPreds;
325 }
326 getNode(&I)->UnscheduledPreds = CntUnschedPreds;
327 }
328
329 // Now handle the cross-interval edges.
330 bool NewIsAbove = DAGInterval.empty() || NewInterval.comesBefore(DAGInterval);
331 const auto &TopInterval = NewIsAbove ? NewInterval : DAGInterval;
332 const auto &BotInterval = NewIsAbove ? DAGInterval : NewInterval;
333 // +---+
334 // |Top|
335 // | | Def
336 // +---+ |
337 // | | v
338 // |Bot| Use
339 // | |
340 // +---+
341 // Walk over all instructions in "BotInterval" and update the counter
342 // of operands that are in "TopInterval".
343 for (Instruction &BotI : BotInterval) {
344 auto *BotN = getNode(&BotI);
345 // Skip scheduled nodes.
346 if (BotN->scheduled())
347 continue;
348 unsigned CntUnscheduledPreds = 0;
349 for (Value *Op : BotI.operands()) {
350 auto *OpI = dyn_cast<Instruction>(Op);
351 if (OpI == nullptr)
352 continue;
353 auto *OpN = getNode(OpI);
354 if (OpN == nullptr)
355 continue;
356 if (!TopInterval.contains(OpI))
357 continue;
358 OpN->incrUnscheduledSuccs();
359 if (!OpN->scheduled())
360 ++CntUnscheduledPreds;
361 }
362 *BotN->UnscheduledPreds += CntUnscheduledPreds;
363 }
364}
365
366void DependencyGraph::createNewNodes(const Interval<Instruction> &NewInterval) {
367 // Create Nodes only for the new sections of the DAG.
368 DGNode *LastN = getOrCreateNode(NewInterval.top());
369 MemDGNode *LastMemN = dyn_cast<MemDGNode>(LastN);
370 for (Instruction &I : drop_begin(NewInterval)) {
371 auto *N = getOrCreateNode(&I);
372 // Build the Mem node chain.
373 if (auto *MemN = dyn_cast<MemDGNode>(N)) {
374 MemN->setPrevNode(LastMemN);
375 LastMemN = MemN;
376 }
377 }
378 // Link new MemDGNode chain with the old one, if any.
379 if (!DAGInterval.empty()) {
380 bool NewIsAbove = NewInterval.comesBefore(DAGInterval);
381 const auto &TopInterval = NewIsAbove ? NewInterval : DAGInterval;
382 const auto &BotInterval = NewIsAbove ? DAGInterval : NewInterval;
383 MemDGNode *LinkTopN =
385 MemDGNode *LinkBotN =
387 assert((LinkTopN == nullptr || LinkBotN == nullptr ||
388 LinkTopN->comesBefore(LinkBotN)) &&
389 "Wrong order!");
390 if (LinkTopN != nullptr && LinkBotN != nullptr) {
391 LinkTopN->setNextNode(LinkBotN);
392 }
393#ifndef NDEBUG
394 // TODO: Remove this once we've done enough testing.
395 // Check that the chain is well formed.
396 auto UnionIntvl = DAGInterval.getUnionInterval(NewInterval);
397 MemDGNode *ChainTopN =
399 MemDGNode *ChainBotN =
401 if (ChainTopN != nullptr && ChainBotN != nullptr) {
402 for (auto *N = ChainTopN->getNextNode(), *LastN = ChainTopN; N != nullptr;
403 LastN = N, N = N->getNextNode()) {
404 assert(N == LastN->getNextNode() && "Bad chain!");
405 assert(N->getPrevNode() == LastN && "Bad chain!");
406 }
407 }
408#endif // NDEBUG
409 }
410
411 setDefUseUnscheduledSuccs(NewInterval);
412}
413
414MemDGNode *DependencyGraph::getMemDGNodeBefore(DGNode *N, bool IncludingN,
415 MemDGNode *SkipN) const {
416 auto *I = N->getInstruction();
417 for (auto *PrevI = IncludingN ? I : I->getPrevNode(); PrevI != nullptr;
418 PrevI = PrevI->getPrevNode()) {
419 auto *PrevN = getNodeOrNull(PrevI);
420 if (PrevN == nullptr)
421 return nullptr;
422 auto *PrevMemN = dyn_cast<MemDGNode>(PrevN);
423 if (PrevMemN != nullptr && PrevMemN != SkipN)
424 return PrevMemN;
425 }
426 return nullptr;
427}
428
429MemDGNode *DependencyGraph::getMemDGNodeAfter(DGNode *N, bool IncludingN,
430 MemDGNode *SkipN) const {
431 auto *I = N->getInstruction();
432 for (auto *NextI = IncludingN ? I : I->getNextNode(); NextI != nullptr;
433 NextI = NextI->getNextNode()) {
434 auto *NextN = getNodeOrNull(NextI);
435 if (NextN == nullptr)
436 return nullptr;
437 auto *NextMemN = dyn_cast<MemDGNode>(NextN);
438 if (NextMemN != nullptr && NextMemN != SkipN)
439 return NextMemN;
440 }
441 return nullptr;
442}
443
444void DependencyGraph::notifyCreateInstr(Instruction *I) {
445 if (Ctx->getTracker().getState() == Tracker::TrackerState::Reverting)
446 // We don't maintain the DAG while reverting.
447 return;
448 // Nothing to do if the node is not in the focus range of the DAG.
449 if (!(DAGInterval.contains(I) || DAGInterval.touches(I)))
450 return;
451 // Include `I` into the interval.
452 DAGInterval = DAGInterval.getUnionInterval({I, I});
453 auto *N = getOrCreateNode(I);
454 auto *MemN = dyn_cast<MemDGNode>(N);
455
456 // Update the MemDGNode chain if this is a memory node.
457 if (MemN != nullptr) {
458 if (auto *PrevMemN = getMemDGNodeBefore(MemN, /*IncludingN=*/false)) {
459 PrevMemN->NextMemN = MemN;
460 MemN->PrevMemN = PrevMemN;
461 }
462 if (auto *NextMemN = getMemDGNodeAfter(MemN, /*IncludingN=*/false)) {
463 NextMemN->PrevMemN = MemN;
464 MemN->NextMemN = NextMemN;
465 }
466
467 // Add Mem dependencies.
468 // 1. Scan for deps above `I` for deps to `I`: AboveN->MemN.
469 if (DAGInterval.top()->comesBefore(I)) {
470 Interval<Instruction> AboveIntvl(DAGInterval.top(), I->getPrevNode());
471 auto SrcInterval = MemDGNodeIntervalBuilder::make(AboveIntvl, *this);
472 scanAndAddDeps(*MemN, SrcInterval);
473 }
474 // 2. Scan for deps below `I` for deps from `I`: MemN->BelowN.
475 if (I->comesBefore(DAGInterval.bottom())) {
476 Interval<Instruction> BelowIntvl(I->getNextNode(), DAGInterval.bottom());
477 for (MemDGNode &BelowN :
478 MemDGNodeIntervalBuilder::make(BelowIntvl, *this))
479 scanAndAddDeps(BelowN, Interval<MemDGNode>(MemN, MemN));
480 }
481 }
482}
483
484void DependencyGraph::notifyMoveInstr(Instruction *I, const BBIterator &To) {
485 if (Ctx->getTracker().getState() == Tracker::TrackerState::Reverting)
486 // We don't maintain the DAG while reverting.
487 return;
488 // NOTE: This function runs before `I` moves to its new destination.
489 BasicBlock *BB = To.getNodeParent();
490 assert(!(To != BB->end() && &*To == I->getNextNode()) &&
491 !(To == BB->end() && std::next(I->getIterator()) == BB->end()) &&
492 "Should not have been called if destination is same as origin.");
493
494 // TODO: We can only handle fully internal movements within DAGInterval or at
495 // the borders, i.e., right before the top or right after the bottom.
496 assert(To.getNodeParent() == I->getParent() &&
497 "TODO: We don't support movement across BBs!");
498 assert(
499 (To == std::next(DAGInterval.bottom()->getIterator()) ||
500 (To != BB->end() && std::next(To) == DAGInterval.top()->getIterator()) ||
501 (To != BB->end() && DAGInterval.contains(&*To))) &&
502 "TODO: To should be either within the DAGInterval or right "
503 "before/after it.");
504
505 // Make a copy of the DAGInterval before we update it.
506 auto OrigDAGInterval = DAGInterval;
507
508 // Maintain the DAGInterval.
509 DAGInterval.notifyMoveInstr(I, To);
510
511 // TODO: Perhaps check if this is legal by checking the dependencies?
512
513 // Update the MemDGNode chain to reflect the instr movement if necessary.
515 if (N == nullptr)
516 return;
518 if (MemN == nullptr)
519 return;
520
521 // First safely detach it from the existing chain.
522 MemN->detachFromChain();
523
524 // Now insert it back into the chain at the new location.
525 //
526 // We won't always have a DGNode to insert before it. If `To` is BB->end() or
527 // if it points to an instr after DAGInterval.bottom() then we will have to
528 // find a node to insert *after*.
529 //
530 // BB: BB:
531 // I1 I1 ^
532 // I2 I2 | DAGInteval [I1 to I3]
533 // I3 I3 V
534 // I4 I4 <- `To` == right after DAGInterval
535 // <- `To` == BB->end()
536 //
537 if (To == BB->end() ||
538 To == std::next(OrigDAGInterval.bottom()->getIterator())) {
539 // If we don't have a node to insert before, find a node to insert after and
540 // update the chain.
541 DGNode *InsertAfterN = getNode(&*std::prev(To));
542 MemN->setPrevNode(
543 getMemDGNodeBefore(InsertAfterN, /*IncludingN=*/true, /*SkipN=*/MemN));
544 } else {
545 // We have a node to insert before, so update the chain.
546 DGNode *BeforeToN = getNode(&*To);
547 MemN->setPrevNode(
548 getMemDGNodeBefore(BeforeToN, /*IncludingN=*/false, /*SkipN=*/MemN));
549 MemN->setNextNode(
550 getMemDGNodeAfter(BeforeToN, /*IncludingN=*/true, /*SkipN=*/MemN));
551 }
552}
553
554void DependencyGraph::notifyEraseInstr(Instruction *I) {
555 if (Ctx->getTracker().getState() == Tracker::TrackerState::Reverting)
556 // We don't maintain the DAG while reverting.
557 return;
558 auto *N = getNode(I);
559 if (N == nullptr)
560 // Early return if there is no DAG node for `I`.
561 return;
562 if (auto *MemN = dyn_cast<MemDGNode>(getNode(I))) {
563 // Update the MemDGNode chain if this is a memory node.
564 auto *PrevMemN = getMemDGNodeBefore(MemN, /*IncludingN=*/false);
565 auto *NextMemN = getMemDGNodeAfter(MemN, /*IncludingN=*/false);
566 if (PrevMemN != nullptr)
567 PrevMemN->NextMemN = NextMemN;
568 if (NextMemN != nullptr)
569 NextMemN->PrevMemN = PrevMemN;
570
571 // Drop the memory dependencies from both predecessors and successors.
572 while (!MemN->memPreds().empty()) {
573 auto *PredN = *MemN->memPreds().begin();
574 MemN->removeMemPred(PredN);
575 }
576 while (!MemN->memSuccs().empty()) {
577 auto *SuccN = *MemN->memSuccs().begin();
578 SuccN->removeMemPred(MemN);
579 }
580 // NOTE: The unscheduled succs for MemNodes get updated be setMemPred().
581 } else {
582 // If this is a non-mem node we only need to update UnscheduledSuccs.
583 if (!N->scheduled()) {
584 for (auto *PredN : N->preds(*this))
585 PredN->decrUnscheduledSuccs();
586 for (auto *SuccN : N->succs(*this))
587 SuccN->decrUnscheduledPreds();
588 }
589 }
590 // Finally erase the Node.
591 InstrToNodeMap.erase(I);
592}
593
594void DependencyGraph::notifySetUse(const Use &U, Value *NewSrc) {
595 // If U.User is not in the DAG, then we should not attempt to decrement
596 // CurrSrcN's unscheduled successors.
597 // ------- ------- -
598 // CurrSrc | DAG interval
599 // | NewSrc |
600 // ---|--- ---|--- -
601 // U.User U.User
602 auto *UserI = dyn_cast_or_null<Instruction>(U.getUser());
603 if (UserI == nullptr)
604 return;
605 auto *UserN = getNode(UserI);
606 if (UserN == nullptr)
607 return;
608 // If UserN is marked as scheduled then we should not update CrrSrcN' or
609 // NewSrcN's unscheduled successors.
610 if (UserN->scheduled())
611 return;
612 // Update the UnscheduledSuccs counter for both the current source and
613 // NewSrc if needed.
614 if (auto *CurrSrcI = dyn_cast<Instruction>(U.get())) {
615 if (auto *CurrSrcN = getNode(CurrSrcI)) {
616 // If CurrSrcN is scheduled there is no point in updating UnscheduleSuccs.
617 if (!CurrSrcN->scheduled()) {
618 CurrSrcN->decrUnscheduledSuccs();
619 UserN->decrUnscheduledPreds();
620 }
621 }
622 }
623 if (auto *NewSrcI = dyn_cast<Instruction>(NewSrc)) {
624 if (auto *NewSrcN = getNode(NewSrcI)) {
625 // If CurrSrcN is scheduled there is no point in updating UnscheduleSuccs.
626 if (!NewSrcN->scheduled()) {
627 NewSrcN->incrUnscheduledSuccs();
628 UserN->incrUnscheduledPreds();
629 }
630 }
631 }
632}
633
635 if (Instrs.empty())
636 return {};
637
638 Interval<Instruction> InstrsInterval(Instrs);
639 Interval<Instruction> Union = DAGInterval.getUnionInterval(InstrsInterval);
640 auto NewInterval = Union.getSingleDiff(DAGInterval);
641 if (NewInterval.empty())
642 return {};
643
644 createNewNodes(NewInterval);
645
646 // Create the dependencies.
647 //
648 // 1. This is a new DAG, DAGInterval is empty. Fully scan the whole interval.
649 // +---+ - -
650 // | | SrcN | |
651 // | | | | SrcRange |
652 // |New| v | | DstRange
653 // | | DstN - |
654 // | | |
655 // +---+ -
656 // We are scanning for deps with destination in NewInterval and sources in
657 // NewInterval until DstN, for each DstN.
658 auto FullScan = [this](const Interval<Instruction> Intvl) {
659 auto DstRange = MemDGNodeIntervalBuilder::make(Intvl, *this);
660 if (!DstRange.empty()) {
661 for (MemDGNode &DstN : drop_begin(DstRange)) {
662 auto SrcRange = Interval<MemDGNode>(DstRange.top(), DstN.getPrevNode());
663 scanAndAddDeps(DstN, SrcRange);
664 }
665 }
666 };
667 auto MemDAGInterval = MemDGNodeIntervalBuilder::make(DAGInterval, *this);
668 if (MemDAGInterval.empty()) {
669 FullScan(NewInterval);
670 }
671 // 2. The new section is below the old section.
672 // +---+ -
673 // | | |
674 // |Old| SrcN |
675 // | | | |
676 // +---+ | | SrcRange
677 // +---+ | | -
678 // | | | | |
679 // |New| v | | DstRange
680 // | | DstN - |
681 // | | |
682 // +---+ -
683 // We are scanning for deps with destination in NewInterval because the deps
684 // in DAGInterval have already been computed. We consider sources in the whole
685 // range including both NewInterval and DAGInterval until DstN, for each DstN.
686 else if (DAGInterval.bottom()->comesBefore(NewInterval.top())) {
687 auto DstRange = MemDGNodeIntervalBuilder::make(NewInterval, *this);
688 auto SrcRangeFull = MemDAGInterval.getUnionInterval(DstRange);
689 for (MemDGNode &DstN : DstRange) {
690 auto SrcRange =
691 Interval<MemDGNode>(SrcRangeFull.top(), DstN.getPrevNode());
692 scanAndAddDeps(DstN, SrcRange);
693 }
694 }
695 // 3. The new section is above the old section.
696 else if (NewInterval.bottom()->comesBefore(DAGInterval.top())) {
697 // +---+ - -
698 // | | SrcN | |
699 // |New| | | SrcRange | DstRange
700 // | | v | |
701 // | | DstN - |
702 // | | |
703 // +---+ -
704 // +---+
705 // |Old|
706 // | |
707 // +---+
708 // When scanning for deps with destination in NewInterval we need to fully
709 // scan the interval. This is the same as the scanning for a new DAG.
710 FullScan(NewInterval);
711
712 // +---+ -
713 // | | |
714 // |New| SrcN | SrcRange
715 // | | | |
716 // | | | |
717 // | | | |
718 // +---+ | -
719 // +---+ | -
720 // |Old| v | DstRange
721 // | | DstN |
722 // +---+ -
723 // When scanning for deps with destination in DAGInterval we need to
724 // consider sources from the NewInterval only, because all intra-DAGInterval
725 // dependencies have already been created.
726 auto DstRangeOld = MemDAGInterval;
727 auto SrcRange = MemDGNodeIntervalBuilder::make(NewInterval, *this);
728 for (MemDGNode &DstN : DstRangeOld)
729 scanAndAddDeps(DstN, SrcRange);
730 } else {
731 llvm_unreachable("We don't expect extending in both directions!");
732 }
733
734 DAGInterval = Union;
735 return NewInterval;
736}
737
738#ifndef NDEBUG
740 // InstrToNodeMap is unordered so we need to create an ordered vector.
742 Nodes.reserve(InstrToNodeMap.size());
743 for (const auto &Pair : InstrToNodeMap)
744 Nodes.push_back(Pair.second.get());
745 // Sort them based on which one comes first in the BB.
746 sort(Nodes, [](DGNode *N1, DGNode *N2) {
747 return N1->getInstruction()->comesBefore(N2->getInstruction());
748 });
749 for (auto *N : Nodes)
750 N->print(OS, /*PrintDeps=*/true);
751}
752
754 print(dbgs());
755 dbgs() << "\n";
756}
757#endif // NDEBUG
758
759} // namespace llvm::sandboxir
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define I(x, y, z)
Definition MD5.cpp:57
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A DependencyGraph Node that points to an Instruction and contains memory dependency edges.
virtual void print(raw_ostream &OS, bool PrintDeps=true) const
static bool isMemDepCandidate(Instruction *I)
We consider I as a Memory Dependency Candidate instruction if it reads/write memory or if it has side...
void setSchedBundle(SchedBundle &SB)
SchedBundle * SB
The scheduler bundle that this node belongs to.
bool Scheduled
This is true if this node has been scheduled.
std::optional< unsigned > UnscheduledSuccs
The number of unscheduled successors.
static bool isMemDepNodeCandidate(Instruction *I)
\Returns true if I is a memory dependency candidate instruction.
static bool isFenceLike(Instruction *I)
\Returns true if I is fence like. It excludes non-mem intrinsics.
LLVM_DUMP_METHOD void dump() const
Instruction * getInstruction() const
static bool isStackSaveOrRestoreIntrinsic(Instruction *I)
std::optional< unsigned > UnscheduledPreds
LLVM_DUMP_METHOD void dump() const
DGNode * getNode(Instruction *I) const
DGNode * getNodeOrNull(Instruction *I) const
Like getNode() but returns nullptr if I is nullptr.
void print(raw_ostream &OS) const
DGNode * getOrCreateNode(Instruction *I)
LLVM_ABI Interval< Instruction > extend(ArrayRef< Instruction * > Instrs)
Build/extend the dependency graph such that it includes Instrs.
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
static LLVM_ABI MemDGNode * getBotMemDGNode(const Interval< Instruction > &Intvl, const DependencyGraph &DAG)
Scans the instruction chain in Intvl bottom-up, returning the bottom-most MemDGNode,...
static LLVM_ABI MemDGNode * getTopMemDGNode(const Interval< Instruction > &Intvl, const DependencyGraph &DAG)
Scans the instruction chain in Intvl top-down, returning the top-most MemDGNode, or nullptr.
static LLVM_ABI Interval< MemDGNode > make(const Interval< Instruction > &Instrs, DependencyGraph &DAG)
Given Instrs it finds their closest mem nodes in the interval and returns the corresponding mem range...
A DependencyGraph Node for instructions that may read/write memory, or have some ordering constraints...
void print(raw_ostream &OS, bool PrintDeps=true) const override
LLVM_ABI value_type operator*()
LLVM_ABI PredIterator & operator++()
LLVM_ABI bool operator==(const PredIterator &Other) const
LLVM_ABI value_type operator*()
LLVM_ABI bool operator==(const SuccIterator &Other) const
LLVM_ABI SuccIterator & operator++()
Represents a Def-use/Use-def edge in SandboxIR.
Definition Use.h:43
OperandUseIterator op_iterator
Definition User.h:98
static ModRefInfo aliasAnalysisGetModRefInfo(BatchAAResults &BatchAA, const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Equivalent to BatchAA::getModRefInfo().
Definition Utils.h:123
static std::optional< llvm::MemoryLocation > memoryLocationGetOrNone(const Instruction *I)
Equivalent to MemoryLocation::getOrNone(I).
Definition Utils.h:85
A SandboxIR Value has users. This is the base class.
Definition Value.h:72
mapped_iterator< sandboxir::UserUseIterator, UseToUser > user_iterator
Definition Value.h:239
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static bool isOrdered(Instruction *I)
template class LLVM_TEMPLATE_ABI Interval< MemDGNode >
Definition Interval.cpp:47
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
template class LLVM_TEMPLATE_ABI Interval< Instruction >
Definition Interval.cpp:46
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
#define N