LLVM 24.0.0git
GenericUniformityImpl.h
Go to the documentation of this file.
1//===- GenericUniformityImpl.h -----------------------*- 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//
9// This template implementation resides in a separate file so that it
10// does not get injected into every .cpp file that includes the
11// generic header.
12//
13// DO NOT INCLUDE THIS FILE WHEN MERELY USING UNIFORMITYINFO.
14//
15// This file should only be included by files that implement a
16// specialization of the relvant templates. Currently these are:
17// - UniformityAnalysis.cpp
18// - MachineUniformityAnalysis.cpp
19//
20// Note: The DEBUG_TYPE macro should be defined before using this
21// file so that any use of LLVM_DEBUG is associated with the
22// including file rather than this file.
23//
24//===----------------------------------------------------------------------===//
25///
26/// \file
27/// \brief Implementation of uniformity analysis.
28///
29/// The algorithm is a fixed point iteration that starts with the assumption
30/// that all control flow and all values are uniform. Starting from sources of
31/// divergence (whose discovery must be implemented by a CFG- or even
32/// target-specific derived class), divergence of values is propagated from
33/// definition to uses in a straight-forward way. The main complexity lies in
34/// the propagation of the impact of divergent control flow on the divergence of
35/// values (sync dependencies).
36///
37/// NOTE: In general, no interface exists for a transform to update
38/// (Machine)UniformityInfo. Additionally, (Machine)CycleAnalysis is a
39/// transitive dependence, but it also does not provide an interface for
40/// updating itself. Given that, transforms should not preserve uniformity in
41/// their getAnalysisUsage() callback.
42///
43//===----------------------------------------------------------------------===//
44
45#ifndef LLVM_ADT_GENERICUNIFORMITYIMPL_H
46#define LLVM_ADT_GENERICUNIFORMITYIMPL_H
47
49
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/SetVector.h"
57
58#define DEBUG_TYPE "uniformity"
59
60namespace llvm {
61
62// Forward decl from llvm/CodeGen/MachineInstr.h
63class MachineInstr;
64
65/// Construct a specially modified post-order traversal of cycles.
66///
67/// The ModifiedPO is contructed using a virtually modified CFG as follows:
68///
69/// 1. The successors of pre-entry nodes (predecessors of an cycle
70/// entry that are outside the cycle) are replaced by the
71/// successors of the successors of the header.
72/// 2. Successors of the cycle header are replaced by the exit blocks
73/// of the cycle.
74///
75/// Effectively, we produce a depth-first numbering with the following
76/// properties:
77///
78/// 1. Nodes after a cycle are numbered earlier than the cycle header.
79/// 2. The header is numbered earlier than the nodes in the cycle.
80/// 3. The numbering of the nodes within the cycle forms an interval
81/// starting with the header.
82///
83/// Effectively, the virtual modification arranges the nodes in a
84/// cycle as a DAG with the header as the sole leaf, and successors of
85/// the header as the roots. A reverse traversal of this numbering has
86/// the following invariant on the unmodified original CFG:
87///
88/// Each node is visited after all its predecessors, except if that
89/// predecessor is the cycle header.
90///
91template <typename ContextT> class ModifiedPostOrder {
92public:
93 using BlockT = typename ContextT::BlockT;
94 using FunctionT = typename ContextT::FunctionT;
95 using DominatorTreeT = typename ContextT::DominatorTreeT;
96
98 using const_iterator = typename std::vector<BlockT *>::const_iterator;
99
100 ModifiedPostOrder(const ContextT &C) : Context(C) {}
101
102 bool empty() const { return Order.empty(); }
103 size_t size() const { return Order.size(); }
104
105 void clear() { Order.clear(); }
106 void compute(const CycleInfoT &CI);
107
108 unsigned count(BlockT *BB) const {
109 unsigned Num = GraphTraits<BlockT *>::getNumber(BB);
110 return Num < POIndex.size() && POIndex[Num] != InvalidIndex;
111 }
112 const BlockT *operator[](size_t Idx) const { return Order[Idx]; }
113
114 void appendBlock(const BlockT &BB, bool IsReducibleCycleHeader = false) {
115 unsigned Num = GraphTraits<const BlockT *>::getNumber(&BB);
116 POIndex[Num] = Order.size();
117 Order.push_back(&BB);
118 LLVM_DEBUG(dbgs() << "ModifiedPO(" << POIndex[Num]
119 << "): " << Context.print(&BB) << "\n");
120 if (IsReducibleCycleHeader)
121 ReducibleCycleHeaders.insert(&BB);
122 }
123
124 unsigned getIndex(const BlockT *BB) const {
126 assert(Num < POIndex.size() && POIndex[Num] != InvalidIndex);
127 return POIndex[Num];
128 }
129
130 bool isReducibleCycleHeader(const BlockT *BB) const {
131 return ReducibleCycleHeaders.contains(BB);
132 }
133
134private:
135 static constexpr unsigned InvalidIndex = -1u;
136
138 SmallVector<unsigned> POIndex;
139 SmallPtrSet<const BlockT *, 32> ReducibleCycleHeaders;
140 const ContextT &Context;
141
142 void computeCyclePO(const CycleInfoT &CI, CycleRef C,
144
145 void computeStackPO(SmallVectorImpl<const BlockT *> &Stack,
146 const CycleInfoT &CI, CycleRef C,
148};
149
150template <typename> class DivergencePropagator;
151
152/// \class GenericSyncDependenceAnalysis
153///
154/// \brief Locate join blocks for disjoint paths starting at a divergent branch.
155///
156/// An analysis per divergent branch that returns the set of basic
157/// blocks whose phi nodes become divergent due to divergent control.
158/// These are the blocks that are reachable by two disjoint paths from
159/// the branch, or cycle exits reachable along a path that is disjoint
160/// from a path to the cycle latch.
161
162// --- Above line is not a doxygen comment; intentionally left blank ---
163//
164// Originally implemented in SyncDependenceAnalysis.cpp for DivergenceAnalysis.
165//
166// The SyncDependenceAnalysis is used in the UniformityAnalysis to model
167// control-induced divergence in phi nodes.
168//
169// -- Reference --
170// The algorithm is an extension of Section 5 of
171//
172// An abstract interpretation for SPMD divergence
173// on reducible control flow graphs.
174// Julian Rosemann, Simon Moll and Sebastian Hack
175// POPL '21
176//
177//
178// -- Sync dependence --
179// Sync dependence characterizes the control flow aspect of the
180// propagation of branch divergence. For example,
181//
182// %cond = icmp slt i32 %tid, 10
183// br i1 %cond, label %then, label %else
184// then:
185// br label %merge
186// else:
187// br label %merge
188// merge:
189// %a = phi i32 [ 0, %then ], [ 1, %else ]
190//
191// Suppose %tid holds the thread ID. Although %a is not data dependent on %tid
192// because %tid is not on its use-def chains, %a is sync dependent on %tid
193// because the branch "br i1 %cond" depends on %tid and affects which value %a
194// is assigned to.
195//
196//
197// -- Reduction to SSA construction --
198// There are two disjoint paths from A to X, if a certain variant of SSA
199// construction places a phi node in X under the following set-up scheme.
200//
201// This variant of SSA construction ignores incoming undef values.
202// That is paths from the entry without a definition do not result in
203// phi nodes.
204//
205// entry
206// / \
207// A \
208// / \ Y
209// B C /
210// \ / \ /
211// D E
212// \ /
213// F
214//
215// Assume that A contains a divergent branch. We are interested
216// in the set of all blocks where each block is reachable from A
217// via two disjoint paths. This would be the set {D, F} in this
218// case.
219// To generally reduce this query to SSA construction we introduce
220// a virtual variable x and assign to x different values in each
221// successor block of A.
222//
223// entry
224// / \
225// A \
226// / \ Y
227// x = 0 x = 1 /
228// \ / \ /
229// D E
230// \ /
231// F
232//
233// Our flavor of SSA construction for x will construct the following
234//
235// entry
236// / \
237// A \
238// / \ Y
239// x0 = 0 x1 = 1 /
240// \ / \ /
241// x2 = phi E
242// \ /
243// x3 = phi
244//
245// The blocks D and F contain phi nodes and are thus each reachable
246// by two disjoint paths from A.
247//
248// -- Remarks --
249// * In case of cycle exits we need to check for temporal divergence.
250// To this end, we check whether the definition of x differs between the
251// cycle exit and the cycle header (_after_ SSA construction).
252//
253// * In the presence of irreducible control flow, the fixed point is
254// reached only after multiple iterations. This is because labels
255// reaching the header of a cycle must be repropagated through the
256// cycle. This is true even in a reducible cycle, since the labels
257// may have been produced by a nested irreducible cycle.
258//
259// * Note that SyncDependenceAnalysis is not concerned with the points
260// of convergence in an irreducible cycle. Its only purpose is to
261// identify join blocks. The "diverged entry" criterion is
262// separately applied on join blocks to determine if an entire
263// irreducible cycle is assumed to be divergent.
264//
265// * Relevant related work:
266// A simple algorithm for global data flow analysis problems.
267// Matthew S. Hecht and Jeffrey D. Ullman.
268// SIAM Journal on Computing, 4(4):519–532, December 1975.
269//
270template <typename ContextT> class GenericSyncDependenceAnalysis {
271public:
272 using BlockT = typename ContextT::BlockT;
273 using DominatorTreeT = typename ContextT::DominatorTreeT;
274 using FunctionT = typename ContextT::FunctionT;
275 using ValueRefT = typename ContextT::ValueRefT;
276 using InstructionT = typename ContextT::InstructionT;
277
279
282
283 /// Information discovered by the sync dependence analysis for each
284 /// divergent branch.
286 // Join points of diverged paths.
288 // Divergent cycle exits
290 };
291
293
295 const DominatorTreeT &DT, const CycleInfoT &CI);
296
297 /// \brief Computes divergent join points and cycle exits caused by branch
298 /// divergence in \p Term.
299 ///
300 /// This returns a pair of sets:
301 /// * The set of blocks which are reachable by disjoint paths from
302 /// \p Term.
303 /// * The set also contains cycle exits if there two disjoint paths:
304 /// one from \p Term to the cycle exit and another from \p Term to
305 /// the cycle header.
306 const DivergenceDescriptor &getJoinBlocks(const BlockT *DivTermBlock);
307
308private:
309 static inline DivergenceDescriptor EmptyDivergenceDesc;
310
311 ModifiedPO CyclePO;
312
313 const DominatorTreeT &DT;
314 const CycleInfoT &CI;
315
317 CachedControlDivDescs;
318};
319
320/// \brief Analysis that identifies uniform values in a data-parallel
321/// execution.
322///
323/// This analysis propagates divergence in a data-parallel context
324/// from sources of divergence to all users. It can be instantiated
325/// for an IR that provides a suitable SSAContext.
326template <typename ContextT> class GenericUniformityAnalysisImpl {
327public:
328 using BlockT = typename ContextT::BlockT;
329 using FunctionT = typename ContextT::FunctionT;
330 using ValueRefT = typename ContextT::ValueRefT;
331 using ConstValueRefT = typename ContextT::ConstValueRefT;
332 using UseT = typename ContextT::UseT;
333 using InstructionT = typename ContextT::InstructionT;
334 using DominatorTreeT = typename ContextT::DominatorTreeT;
335
337
340 typename SyncDependenceAnalysisT::DivergenceDescriptor;
341
343 std::tuple<ConstValueRefT, InstructionT *, CycleRef>;
344
347 : Context(CI.getSSAContext()), F(*Context.getFunction()), CI(CI),
348 TTI(TTI), DT(DT), SDA(Context, DT, CI) {}
349
351
352 const FunctionT &getFunction() const { return F; }
353
354 const CycleInfoT &getCycleInfo() const { return CI; }
355
356 /// \brief Mark \p UniVal as a value that is always uniform.
357 void addUniformOverride(const InstructionT &Instr);
358
359 /// \brief Examine \p I for divergent outputs and add to the worklist.
360 void markDivergent(const InstructionT &I);
361
362 /// \brief Mark \p DivVal as a divergent value by removing it from
363 /// UniformValues. \returns Whether the tracked divergence state of
364 /// \p DivVal changed.
365 bool markDivergent(ConstValueRefT DivVal);
366
367 /// \brief Mark outputs of \p Instr as divergent.
368 /// \returns Whether the tracked divergence state of any output has changed.
369 bool markDefsDivergent(const InstructionT &Instr);
370
371 /// \brief Propagate divergence to all instructions in the region.
372 /// Divergence is seeded by calls to \p markDivergent.
373 void compute();
374
375 /// \brief Whether \p Val will always return a uniform value regardless of its
376 /// operands
377 bool isAlwaysUniform(const InstructionT &Instr) const;
378
379 bool hasDivergentDefs(const InstructionT &I) const;
380
382 assert(I.isTerminator() && "Expected a terminator instruction!");
383 return DivergentTermBlocks.contains(I.getParent());
384 };
385
386 /// \brief Whether \p Val is divergent at its definition.
387 /// When the target has no branch divergence, compute() is never called
388 /// and everything is uniform. Otherwise, values not in UniformValues
389 /// (e.g. newly created) are conservatively treated as divergent.
392 return false;
393 // Only values that were present during analysis are tracked in
394 // UniformValues (Instructions/Arguments for IR, Registers for MIR).
395 // Other values (e.g. constants, globals) are always uniform but are
396 // not added to UniformValues; this check avoids false divergence.
397 if (ContextT::isAlwaysUniform(V))
398 return false;
399 return !UniformValues.contains(V);
400 }
401
402 bool isDivergentUse(const UseT &U) const;
403
404 bool hasDivergentTerminator(const BlockT &B) const {
405 return DivergentTermBlocks.contains(&B);
406 }
407
408 /// Call before erasing \p V, or a later instruction reusing its address
409 /// may be misclassified as uniform.
411
412 void print(raw_ostream &Out) const;
413
414 /// Print divergent arguments and return true if any were found.
415 /// IR specialization iterates F.args(); default is a no-op.
416 bool printDivergentArgs(raw_ostream &Out) const;
417
419
421
422 /// Check if an instruction with Custom uniformity can be proven uniform
423 /// based on its operands. This queries the target-specific callback.
424 bool isCustomUniform(const InstructionT &I) const;
425
426 /// \brief Add an instruction that requires custom uniformity analysis.
428
429protected:
430 const ContextT &Context;
431 const FunctionT &F;
433 const TargetTransformInfo *TTI = nullptr;
434
435 // Whether the target has branch divergence. Set at the start of compute(),
436 // which is only called when the target has branch divergence. When false,
437 // isDivergent() returns false for all values.
439
441
442 // Values known to be uniform. Populated in initialize() with all values,
443 // then values are removed as divergence is propagated. After analysis,
444 // values not in this set are conservatively treated as divergent.
446
447 // Internal worklist for divergence propagation.
448 std::vector<const InstructionT *> Worklist;
449
450 // Set of instructions that require custom uniformity analysis based on
451 // operand uniformity.
453
454 /// \brief Mark \p Term as divergent and push all Instructions that become
455 /// divergent as a result on the worklist.
456 void analyzeControlDivergence(const InstructionT &Term);
457
458private:
459 const DominatorTreeT &DT;
460
461 // Recognized cycles with divergent exits.
462 SmallSetVector<CycleRef, 8> DivergentExitCycles;
463
464 // Cycles assumed to be divergent.
465 //
466 // We don't use a set here because every insertion needs an explicit
467 // traversal of all existing members.
468 SmallVector<CycleRef> AssumedDivergent;
469
470 // The SDA links divergent branches to divergent control-flow joins.
472
473 // Set of known-uniform values.
475
476 /// \brief Mark all nodes in \p JoinBlock as divergent and push them on
477 /// the worklist.
478 void taintAndPushAllDefs(const BlockT &JoinBlock);
479
480 /// \brief Mark all phi nodes in \p JoinBlock as divergent and push them on
481 /// the worklist.
482 void taintAndPushPhiNodes(const BlockT &JoinBlock);
483
484 /// \brief Identify all Instructions that become divergent because \p DivExit
485 /// is a divergent cycle exit of \p DivCycle. Mark those instructions as
486 /// divergent and push them on the worklist.
487 void propagateCycleExitDivergence(const BlockT &DivExit, CycleRef DivCycle);
488
489 /// Mark as divergent all external uses of values defined in \p DefCycle.
490 void analyzeCycleExitDivergence(CycleRef DefCycle);
491
492 /// \brief Mark as divergent all uses of \p I that are outside \p DefCycle.
493 void propagateTemporalDivergence(const InstructionT &I, CycleRef DefCycle);
494
495 /// \brief Push all users of \p Val (in the region) to the worklist.
496 void pushUsers(const InstructionT &I);
497 void pushUsers(ConstValueRefT V);
498
499 bool usesValueFromCycle(const InstructionT &I, CycleRef DefCycle) const;
500
501 /// \brief Whether \p Def is divergent when read in \p ObservingBlock.
502 bool isTemporalDivergent(const BlockT &ObservingBlock,
503 const InstructionT &Def) const;
504};
505
506template <typename ImplT>
508 delete Impl;
509}
510
511/// Compute divergence starting with a divergent branch.
512template <typename ContextT> class DivergencePropagator {
513public:
514 using BlockT = typename ContextT::BlockT;
515 using DominatorTreeT = typename ContextT::DominatorTreeT;
516 using FunctionT = typename ContextT::FunctionT;
517 using ValueRefT = typename ContextT::ValueRefT;
518
520
524 typename SyncDependenceAnalysisT::DivergenceDescriptor;
525
530 const ContextT &Context;
531
532 // Track blocks that receive a new label. Every time we relabel a
533 // cycle header, we make another pass over the modified post-order in
534 // order to propagate the header label. The bit vector also allows
535 // us to skip labels that have not changed.
537
538 // divergent join and cycle exit descriptor.
539 std::unique_ptr<DivergenceDescriptorT> DivDesc;
540
541 // Dominating definition at each block on diverged paths, indexed by block
542 // number. Transient to this propagation; not stored in the descriptor.
543 // * label(B) == C : C is the dominating definition at B
544 // * label(B) == nullptr : we haven't seen B yet
545 // * label(B) == B : B is a join of disjoint paths, an immediate
546 // successor of the divergent term, or the term
547 // itself
549
550 const BlockT *&label(const BlockT *BB) {
552 }
553
555 const CycleInfoT &CI, const BlockT &DivTermBlock)
557 Context(CI.getSSAContext()), DivDesc(new DivergenceDescriptorT),
559 GraphTraits<const FunctionT *>::getMaxNumber(CI.getFunction()),
560 nullptr) {}
561
563 Out << "Propagator::BlockLabels {\n";
564 for (int BlockIdx = (int)CyclePOT.size() - 1; BlockIdx >= 0; --BlockIdx) {
565 const auto *Block = CyclePOT[BlockIdx];
566 const auto *Label = label(Block);
567 Out << Context.print(Block) << "(" << BlockIdx << ") : ";
568 if (!Label) {
569 Out << "<null>\n";
570 } else {
571 Out << Context.print(Label) << "\n";
572 }
573 }
574 Out << "}\n";
575 }
576
577 // Push a definition (\p PushedLabel) to \p SuccBlock and return whether this
578 // causes a divergent join.
579 bool computeJoin(const BlockT &SuccBlock, const BlockT &PushedLabel) {
580 const auto *OldLabel = label(&SuccBlock);
581
582 LLVM_DEBUG(dbgs() << "labeling " << Context.print(&SuccBlock) << ":\n"
583 << "\tpushed label: " << Context.print(&PushedLabel)
584 << "\n"
585 << "\told label: " << Context.print(OldLabel) << "\n");
586
587 // Early exit if there is no change in the label.
588 if (OldLabel == &PushedLabel)
589 return false;
590
591 if (OldLabel != &SuccBlock) {
592 auto SuccIdx = CyclePOT.getIndex(&SuccBlock);
593 // Assigning a new label, mark this in FreshLabels.
594 LLVM_DEBUG(dbgs() << "\tfresh label: " << SuccIdx << "\n");
595 FreshLabels.set(SuccIdx);
596 }
597
598 // This is not a join if the succ was previously unlabeled.
599 if (!OldLabel) {
600 LLVM_DEBUG(dbgs() << "\tnew label: " << Context.print(&PushedLabel)
601 << "\n");
602 label(&SuccBlock) = &PushedLabel;
603 return false;
604 }
605
606 // This is a new join. Label the join block as itself, and not as
607 // the pushed label.
608 LLVM_DEBUG(dbgs() << "\tnew label: " << Context.print(&SuccBlock) << "\n");
609 label(&SuccBlock) = &SuccBlock;
610
611 return true;
612 }
613
614 // visiting a virtual cycle exit edge from the cycle header --> temporal
615 // divergence on join
616 bool visitCycleExitEdge(const BlockT &ExitBlock, const BlockT &Label) {
617 if (!computeJoin(ExitBlock, Label))
618 return false;
619
620 // Identified a divergent cycle exit
621 DivDesc->CycleDivBlocks.insert(&ExitBlock);
622 LLVM_DEBUG(dbgs() << "\tDivergent cycle exit: " << Context.print(&ExitBlock)
623 << "\n");
624 return true;
625 }
626
627 // process \p SuccBlock with reaching definition \p Label
628 bool visitEdge(const BlockT &SuccBlock, const BlockT &Label) {
629 if (!computeJoin(SuccBlock, Label))
630 return false;
631
632 // Divergent, disjoint paths join.
633 DivDesc->JoinDivBlocks.insert(&SuccBlock);
634 LLVM_DEBUG(dbgs() << "\tDivergent join: " << Context.print(&SuccBlock)
635 << "\n");
636 return true;
637 }
638
639 std::unique_ptr<DivergenceDescriptorT> computeJoinPoints() {
641
642 LLVM_DEBUG(dbgs() << "SDA:computeJoinPoints: "
643 << Context.print(&DivTermBlock) << "\n");
644
645 int DivTermIdx = CyclePOT.getIndex(&DivTermBlock);
646 CycleRef DivTermCycle = CI.getCycle(&DivTermBlock);
647
648 // Locate the largest ancestor cycle that is not reducible and does not
649 // contain a reducible ancestor. This is done with a lambda that is defined
650 // and invoked in the same statement.
651 CycleRef IrreducibleAncestor = [this](CycleRef C) -> CycleRef {
652 if (!C)
653 return CycleRef();
654 if (CI.isReducible(C))
655 return CycleRef();
656 while (CycleRef P = CI.getParentCycle(C)) {
657 if (CI.isReducible(P))
658 return C;
659 C = P;
660 }
661 assert(!CI.getParentCycle(C));
662 assert(!CI.isReducible(C));
663 return C;
664 }(DivTermCycle);
665
666 // Bootstrap with branch targets
667 for (const auto *SuccBlock : successors(&DivTermBlock)) {
668 if (DivTermCycle && !CI.contains(DivTermCycle, SuccBlock)) {
669 // If DivTerm exits the cycle immediately, computeJoin() might
670 // not reach SuccBlock with a different label. We need to
671 // check for this exit now.
672 DivDesc->CycleDivBlocks.insert(SuccBlock);
673 LLVM_DEBUG(dbgs() << "\tImmediate divergent cycle exit: "
674 << Context.print(SuccBlock) << "\n");
675 }
676 visitEdge(*SuccBlock, *SuccBlock);
677 }
678
679 // Technically propagation can continue until it reaches the last node.
680 //
681 // For efficiency, propagation can stop if FreshLabels.count()==1. But
682 // For irreducible cycles, let propagation continue until it reaches
683 // out of irreducible cycles (see code for details.)
684 while (true) {
685 auto BlockIdx = FreshLabels.find_last();
686 if (BlockIdx == -1)
687 break;
688
689 const auto *Block = CyclePOT[BlockIdx];
690 // If no irreducible cycle, stop if freshLabels.count() == 1 and Block
691 // is the IPD. If it is in any irreducible cycle, continue propagation.
692 if (FreshLabels.count() == 1 &&
693 (!IrreducibleAncestor || !CI.contains(IrreducibleAncestor, Block)))
694 break;
695
696 LLVM_DEBUG(dbgs() << "Current labels:\n"; printDefs(dbgs()));
697
698 FreshLabels.reset(BlockIdx);
699 // DivTermBlock must not push its label to its successors, but the header
700 // of a reducible cycle pushes its label only to the cycle exits.
701 if (BlockIdx == DivTermIdx && !CyclePOT.isReducibleCycleHeader(Block)) {
702 LLVM_DEBUG(dbgs() << "Skipping DivTermBlock, which is not a reducible "
703 "cycle header\n");
704 continue;
705 }
706
707 LLVM_DEBUG(dbgs() << "visiting " << Context.print(Block) << " at index "
708 << BlockIdx << "\n");
709
710 const auto *Label = label(Block);
711 assert(Label);
712
713 // If the current block is the header of a reducible cycle, then the label
714 // should be propagated to the cycle exits. If this cycle contains the
715 // branch, then those exits are divergent exits. This is true for any DFS.
716 //
717 // If some DFS has a reducible cycle C with header H, then for
718 // any other DFS, H is the header of a cycle C' that is a
719 // superset of C.
720 //
721 // - For a divergent branch inside the subgraph C, any join node inside
722 // C is either H, or some node encountered by paths within C, without
723 // passing through H.
724 //
725 // - For a divergent branch outside the subgraph C, H is the only node
726 // in C reachable from multiple paths since it is the only entry to C.
727 LLVM_DEBUG(dbgs() << "Check for reducible cycle: " << Context.print(Block)
728 << '\n');
729 if (CyclePOT.isReducibleCycleHeader(Block)) {
730 CycleRef BlockCycle = CI.getCycle(Block);
731 LLVM_DEBUG(dbgs() << CI.print(BlockCycle) << '\n');
732 SmallVector<BlockT *, 4> BlockCycleExits;
733 CI.getExitBlocks(BlockCycle, BlockCycleExits);
734 bool BranchIsInside = CI.contains(BlockCycle, &DivTermBlock);
735 for (auto *BlockCycleExit : BlockCycleExits) {
736 // Exits that DivTermBlock branches to directly are recorded as
737 // divergent cycle exits during the bootstrap. Leaving through the
738 // same edge in different iterations does not make them joins.
739 if (Block == &DivTermBlock &&
740 llvm::is_contained(successors(&DivTermBlock), BlockCycleExit))
741 continue;
742 if (BranchIsInside)
743 visitCycleExitEdge(*BlockCycleExit, *Label);
744 // Propagate the label to the exit block.
745 visitEdge(*BlockCycleExit, *Label);
746 }
747 } else {
748 for (const auto *SuccBlock : successors(Block))
749 visitEdge(*SuccBlock, *Label);
750 }
751 }
752
753 LLVM_DEBUG(dbgs() << "Final labeling:\n"; printDefs(dbgs()));
754
755 // Check every cycle containing DivTermBlock for exit divergence.
756 // A cycle has exit divergence if the label of an exit block does
757 // not match the label of its header.
758 for (auto C = CI.getCycle(&DivTermBlock); C; C = CI.getParentCycle(C)) {
759 if (CI.isReducible(C)) {
760 // The exit divergence of a reducible cycle is recorded while
761 // propagating labels.
762 continue;
763 }
765 CI.getExitBlocks(C, Exits);
766 auto *Header = CI.getHeader(C);
767 auto *HeaderLabel = label(Header);
768 for (const auto *Exit : Exits) {
769 if (label(Exit) != HeaderLabel) {
770 // Identified a divergent cycle exit
771 DivDesc->CycleDivBlocks.insert(Exit);
772 LLVM_DEBUG(dbgs() << "\tDivergent cycle exit: " << Context.print(Exit)
773 << "\n");
774 }
775 }
776 }
777
778 return std::move(DivDesc);
779 }
780};
781
782template <typename ContextT>
784 const ContextT &Context, const DominatorTreeT &DT, const CycleInfoT &CI)
785 : CyclePO(Context), DT(DT), CI(CI) {
786 CyclePO.compute(CI);
787}
788
789template <typename ContextT>
791 const BlockT *DivTermBlock) -> const DivergenceDescriptor & {
792 // trivial case
793 if (succ_size(DivTermBlock) <= 1) {
794 return EmptyDivergenceDesc;
795 }
796
797 // already available in cache?
798 auto ItCached = CachedControlDivDescs.find(DivTermBlock);
799 if (ItCached != CachedControlDivDescs.end())
800 return *ItCached->second;
801
802 // compute all join points
803 DivergencePropagatorT Propagator(CyclePO, DT, CI, *DivTermBlock);
804 auto DivDesc = Propagator.computeJoinPoints();
805
806 auto PrintBlockSet = [&](ConstBlockSet &Blocks) {
807 return Printable([&](raw_ostream &Out) {
808 Out << "[";
809 ListSeparator LS;
810 for (const auto *BB : Blocks) {
811 Out << LS << CI.getSSAContext().print(BB);
812 }
813 Out << "]\n";
814 });
815 };
816
818 dbgs() << "\nResult (" << CI.getSSAContext().print(DivTermBlock)
819 << "):\n JoinDivBlocks: " << PrintBlockSet(DivDesc->JoinDivBlocks)
820 << " CycleDivBlocks: " << PrintBlockSet(DivDesc->CycleDivBlocks)
821 << "\n");
822 (void)PrintBlockSet;
823
824 auto ItInserted =
825 CachedControlDivDescs.try_emplace(DivTermBlock, std::move(DivDesc));
826 assert(ItInserted.second);
827 return *ItInserted.first->second;
828}
829
830template <typename ContextT>
832 const InstructionT &I) {
833 if (isAlwaysUniform(I))
834 return;
835 // For custom uniformity candidates, check if the instruction can be
836 // proven uniform based on which operands are uniform/divergent.
837 // The candidate will be re-evaluated as operands become divergent.
838 if (CustomUniformityCandidates.contains(&I)) {
839 if (isCustomUniform(I))
840 return;
841 }
842 bool Marked = false;
843 if (I.isTerminator()) {
844 Marked = DivergentTermBlocks.insert(I.getParent()).second;
845 if (Marked) {
846 LLVM_DEBUG(dbgs() << "marked divergent term block: "
847 << Context.print(I.getParent()) << "\n");
848 }
849 } else {
850 Marked = markDefsDivergent(I);
851 }
852
853 if (Marked)
854 Worklist.push_back(&I);
855}
856
857template <typename ContextT>
859 ConstValueRefT Val) {
860 if (UniformValues.erase(Val)) {
861 LLVM_DEBUG(dbgs() << "marked divergent: " << Context.print(Val) << "\n");
862 return true;
863 }
864 return false;
865}
866
867template <typename ContextT>
869 const InstructionT &Instr) {
870 UniformOverrides.insert(&Instr);
871}
872
873template <typename ContextT>
878
879// Mark as divergent all external uses of values defined in \p DefCycle.
880//
881// A value V defined by a block B inside \p DefCycle may be used outside the
882// cycle only if the use is a PHI in some exit block, or B dominates some exit
883// block. Thus, we check uses as follows:
884//
885// - Check all PHIs in all exit blocks for inputs defined inside \p DefCycle.
886// - For every block B inside \p DefCycle that dominates at least one exit
887// block, check all uses outside \p DefCycle.
888//
889// FIXME: This function does not distinguish between divergent and uniform
890// exits. For each divergent exit, only the values that are live at that exit
891// need to be propagated as divergent at their use outside the cycle.
892template <typename ContextT>
893void GenericUniformityAnalysisImpl<ContextT>::analyzeCycleExitDivergence(
894 CycleRef DefCycle) {
896 CI.getExitBlocks(DefCycle, Exits);
897 for (auto *Exit : Exits) {
898 for (auto &Phi : Exit->phis()) {
899 if (usesValueFromCycle(Phi, DefCycle)) {
900 markDivergent(Phi);
901 }
902 }
903 }
904
905 for (auto *BB : CI.getBlocks(DefCycle)) {
906 if (!llvm::any_of(Exits,
907 [&](BlockT *Exit) { return DT.dominates(BB, Exit); }))
908 continue;
909 for (auto &II : *BB) {
910 propagateTemporalDivergence(II, DefCycle);
911 }
912 }
913}
914
915template <typename ContextT>
916void GenericUniformityAnalysisImpl<ContextT>::propagateCycleExitDivergence(
917 const BlockT &DivExit, CycleRef InnerDivCycle) {
918 LLVM_DEBUG(dbgs() << "\tpropCycleExitDiv " << Context.print(&DivExit)
919 << "\n");
920 CycleRef DivCycle = InnerDivCycle;
921 CycleRef OuterDivCycle = DivCycle;
922
923 // Find outer-most cycle that does not contain \p DivExit
924 while (DivCycle && !CI.contains(DivCycle, &DivExit)) {
925 LLVM_DEBUG(dbgs() << " Found exiting cycle: "
926 << Context.print(CI.getHeader(DivCycle)) << "\n");
927 OuterDivCycle = DivCycle;
928 DivCycle = CI.getParentCycle(DivCycle);
929 }
930 LLVM_DEBUG(dbgs() << "\tOuter-most exiting cycle: "
931 << Context.print(CI.getHeader(OuterDivCycle)) << "\n");
932
933 if (!DivergentExitCycles.insert(OuterDivCycle))
934 return;
935
936 // Exit divergence does not matter if the cycle itself is assumed to
937 // be divergent.
938 for (auto C : AssumedDivergent) {
939 if (CI.contains(C, OuterDivCycle))
940 return;
941 }
942
943 analyzeCycleExitDivergence(OuterDivCycle);
944}
945
946template <typename ContextT>
947void GenericUniformityAnalysisImpl<ContextT>::taintAndPushAllDefs(
948 const BlockT &BB) {
949 LLVM_DEBUG(dbgs() << "taintAndPushAllDefs " << Context.print(&BB) << "\n");
950 for (const auto &I : instrs(BB)) {
951 // Terminators do not produce values; they are divergent only if
952 // the condition is divergent. That is handled when the divergent
953 // condition is placed in the worklist.
954 if (I.isTerminator())
955 break;
956
957 markDivergent(I);
958 }
959}
960
961/// Mark divergent phi nodes in a join block
962template <typename ContextT>
963void GenericUniformityAnalysisImpl<ContextT>::taintAndPushPhiNodes(
964 const BlockT &JoinBlock) {
965 LLVM_DEBUG(dbgs() << "taintAndPushPhiNodes in " << Context.print(&JoinBlock)
966 << "\n");
967 for (const auto &Phi : JoinBlock.phis()) {
968 // FIXME: The non-undef value is not constant per se; it just happens to be
969 // uniform and may not dominate this PHI. So assuming that the same value
970 // reaches along all incoming edges may itself be undefined behaviour. This
971 // particular interpretation of the undef value was added to
972 // DivergenceAnalysis in the following review:
973 //
974 // https://reviews.llvm.org/D19013
975 if (ContextT::isConstantOrUndefValuePhi(Phi))
976 continue;
977 markDivergent(Phi);
978 }
979}
980
981/// Add \p Candidate to \p Cycles if it is not already contained in \p Cycles.
982///
983/// \return true iff \p Candidate was added to \p Cycles.
984template <typename CycleInfoT>
985bool insertIfNotContained(const CycleInfoT &CI, SmallVector<CycleRef> &Cycles,
986 CycleRef Candidate) {
987 if (llvm::any_of(Cycles,
988 [&](CycleRef C) { return CI.contains(C, Candidate); }))
989 return false;
990 Cycles.push_back(Candidate);
991 return true;
992}
993
994/// Return the outermost cycle made divergent by branch outside it.
995///
996/// If two paths that diverged outside an irreducible cycle join
997/// inside that cycle, then that whole cycle is assumed to be
998/// divergent. This does not apply if the cycle is reducible.
999template <typename CycleInfoT, typename BlockT>
1000CycleRef getExtDivCycle(const CycleInfoT &CI, CycleRef Cycle,
1001 const BlockT *DivTermBlock, const BlockT *JoinBlock) {
1002 assert(Cycle);
1003 assert(CI.contains(Cycle, JoinBlock));
1004
1005 if (CI.contains(Cycle, DivTermBlock))
1006 return CycleRef();
1007
1008 CycleRef OriginalCycle = Cycle;
1009 CycleRef Parent = CI.getParentCycle(Cycle);
1010 while (Parent && !CI.contains(Parent, DivTermBlock)) {
1011 Cycle = Parent;
1012 Parent = CI.getParentCycle(Cycle);
1013 }
1014
1015 // If the original cycle is not the outermost cycle, then the outermost cycle
1016 // is irreducible. If the outermost cycle were reducible, then external
1017 // diverged paths would not reach the original inner cycle.
1018 (void)OriginalCycle;
1019 assert(Cycle == OriginalCycle || !CI.isReducible(Cycle));
1020
1021 if (CI.isReducible(Cycle)) {
1022 assert(CI.getHeader(Cycle) == JoinBlock);
1023 return CycleRef();
1024 }
1025
1026 LLVM_DEBUG(dbgs() << "cycle made divergent by external branch\n");
1027 return Cycle;
1028}
1029
1030/// Return the outermost cycle made divergent by branch inside it.
1031///
1032/// This checks the "diverged entry" criterion defined in the
1033/// docs/ConvergenceAnalysis.html.
1034template <typename ContextT, typename CycleInfoT, typename BlockT,
1035 typename DominatorTreeT>
1036CycleRef getIntDivCycle(const CycleInfoT &CI, CycleRef Cycle,
1037 const BlockT *DivTermBlock, const BlockT *JoinBlock,
1038 const DominatorTreeT &DT, ContextT &Context) {
1039 LLVM_DEBUG(dbgs() << "examine join " << Context.print(JoinBlock)
1040 << " for internal branch " << Context.print(DivTermBlock)
1041 << "\n");
1042 if (DT.properlyDominates(DivTermBlock, JoinBlock))
1043 return CycleRef();
1044
1045 // Find the smallest common cycle, if one exists.
1046 assert(Cycle && CI.contains(Cycle, JoinBlock));
1047 while (Cycle && !CI.contains(Cycle, DivTermBlock)) {
1048 Cycle = CI.getParentCycle(Cycle);
1049 }
1050 if (!Cycle || CI.isReducible(Cycle))
1051 return CycleRef();
1052
1053 if (DT.properlyDominates(CI.getHeader(Cycle), JoinBlock))
1054 return CycleRef();
1055
1056 LLVM_DEBUG(dbgs() << " header " << Context.print(CI.getHeader(Cycle))
1057 << " does not dominate join\n");
1058
1059 CycleRef Parent = CI.getParentCycle(Cycle);
1060 while (Parent && !DT.properlyDominates(CI.getHeader(Parent), JoinBlock)) {
1061 LLVM_DEBUG(dbgs() << " header " << Context.print(CI.getHeader(Parent))
1062 << " does not dominate join\n");
1063 Cycle = Parent;
1064 Parent = CI.getParentCycle(Parent);
1065 }
1066
1067 LLVM_DEBUG(dbgs() << " cycle made divergent by internal branch\n");
1068 return Cycle;
1069}
1070
1071template <typename ContextT, typename CycleInfoT, typename BlockT,
1072 typename DominatorTreeT>
1073CycleRef
1074getOutermostDivergentCycle(const CycleInfoT &CI, CycleRef Cycle,
1075 const BlockT *DivTermBlock, const BlockT *JoinBlock,
1076 const DominatorTreeT &DT, ContextT &Context) {
1077 if (!Cycle)
1078 return CycleRef();
1079
1080 // First try to expand Cycle to the largest that contains JoinBlock
1081 // but not DivTermBlock.
1082 CycleRef Ext = getExtDivCycle(CI, Cycle, DivTermBlock, JoinBlock);
1083
1084 // Continue expanding to the largest cycle that contains both.
1085 CycleRef Int =
1086 getIntDivCycle(CI, Cycle, DivTermBlock, JoinBlock, DT, Context);
1087
1088 if (Int)
1089 return Int;
1090 return Ext;
1091}
1092
1093template <typename ContextT>
1094bool GenericUniformityAnalysisImpl<ContextT>::isTemporalDivergent(
1095 const BlockT &ObservingBlock, const InstructionT &Def) const {
1096 const BlockT *DefBlock = Def.getParent();
1097 for (auto C = CI.getCycle(DefBlock); C && !CI.contains(C, &ObservingBlock);
1098 C = CI.getParentCycle(C)) {
1099 if (DivergentExitCycles.contains(C)) {
1100 return true;
1101 }
1102 }
1103 return false;
1104}
1105
1106template <typename ContextT>
1108 const InstructionT &Term) {
1109 const auto *DivTermBlock = Term.getParent();
1110 DivergentTermBlocks.insert(DivTermBlock);
1111 LLVM_DEBUG(dbgs() << "analyzeControlDiv " << Context.print(DivTermBlock)
1112 << "\n");
1113
1114 // Don't propagate divergence from unreachable blocks.
1115 if (!DT.isReachableFromEntry(DivTermBlock))
1116 return;
1117
1118 const auto &DivDesc = SDA.getJoinBlocks(DivTermBlock);
1119 SmallVector<CycleRef> DivCycles;
1120
1121 // Iterate over all blocks now reachable by a disjoint path join
1122 for (const auto *JoinBlock : DivDesc.JoinDivBlocks) {
1123 CycleRef C = CI.getCycle(JoinBlock);
1124 LLVM_DEBUG(dbgs() << "visiting join block " << Context.print(JoinBlock)
1125 << "\n");
1126 if (CycleRef Outermost = getOutermostDivergentCycle(
1127 CI, C, DivTermBlock, JoinBlock, DT, Context)) {
1128 LLVM_DEBUG(dbgs() << "found divergent cycle\n");
1129 DivCycles.push_back(Outermost);
1130 continue;
1131 }
1132 taintAndPushPhiNodes(*JoinBlock);
1133 }
1134
1135 // Sort by order of decreasing depth. This allows later cycles to be skipped
1136 // because they are already contained in earlier ones.
1137 llvm::sort(DivCycles, [this](CycleRef A, CycleRef B) {
1138 return CI.getDepth(A) > CI.getDepth(B);
1139 });
1140
1141 // Cycles that are assumed divergent due to the diverged entry
1142 // criterion potentially contain temporal divergence depending on
1143 // the DFS chosen. Conservatively, all values produced in such a
1144 // cycle are assumed divergent. "Cycle invariant" values may be
1145 // assumed uniform, but that requires further analysis.
1146 for (auto C : DivCycles) {
1147 if (!insertIfNotContained(CI, AssumedDivergent, C))
1148 continue;
1149 LLVM_DEBUG(dbgs() << "process divergent cycle\n");
1150 for (const BlockT *BB : CI.getBlocks(C)) {
1151 taintAndPushAllDefs(*BB);
1152 }
1153 }
1154
1155 CycleRef BranchCycle = CI.getCycle(DivTermBlock);
1156 assert(DivDesc.CycleDivBlocks.empty() || BranchCycle);
1157 for (const auto *DivExitBlock : DivDesc.CycleDivBlocks) {
1158 propagateCycleExitDivergence(*DivExitBlock, BranchCycle);
1159 }
1160}
1161
1162template <typename ContextT>
1164 HasBranchDivergence = true;
1165
1166 // All values on the Worklist are divergent.
1167 // Their users may not have been updated yet.
1168 while (!Worklist.empty()) {
1169 const InstructionT *I = Worklist.back();
1170 Worklist.pop_back();
1171
1172 LLVM_DEBUG(dbgs() << "worklist pop: " << Context.print(I) << "\n");
1173
1174 if (I->isTerminator()) {
1176 continue;
1177 }
1178
1179 // propagate value divergence to users
1180 assert(hasDivergentDefs(*I) && "Worklist invariant violated!");
1181 pushUsers(*I);
1182 }
1183}
1184
1185template <typename ContextT>
1190
1191template <typename ContextT>
1193 const InstructionT &Instr) const {
1194 return UniformOverrides.contains(&Instr);
1195}
1196
1197template <typename ContextT>
1202
1203template <typename ContextT>
1205 const DominatorTreeT &DT, const CycleInfoT &CI,
1206 const TargetTransformInfo *TTI) {
1207 DA.reset(new ImplT{DT, CI, TTI});
1208}
1209
1210template <typename ContextT>
1212 // When we print Value, LLVM IR instruction, we want to print extra new line.
1213 // In LLVM IR print function for Value does not print new line at the end.
1214 // In MIR print for MachineInstr prints new line at the end.
1215 constexpr bool IsMIR = std::is_same<InstructionT, MachineInstr>::value;
1216 std::string NewLine = IsMIR ? "" : "\n";
1217
1218 bool FoundDivergence = false;
1219
1220 FoundDivergence |= printDivergentArgs(OS);
1221
1222 if (!AssumedDivergent.empty()) {
1223 FoundDivergence = true;
1224 OS << "CYCLES ASSUMED DIVERGENT:\n";
1225 for (auto C : AssumedDivergent) {
1226 OS << " " << CI.print(C) << '\n';
1227 }
1228 }
1229
1230 if (!DivergentExitCycles.empty()) {
1231 FoundDivergence = true;
1232 OS << "CYCLES WITH DIVERGENT EXIT:\n";
1233 for (auto C : DivergentExitCycles) {
1234 OS << " " << CI.print(C) << '\n';
1235 }
1236 }
1237
1238 if (!TemporalDivergenceList.empty()) {
1239 FoundDivergence = true;
1240 OS << "\nTEMPORAL DIVERGENCE LIST:\n";
1241
1242 for (auto [Val, UseInst, C] : TemporalDivergenceList) {
1243 OS << "Value :" << Context.print(Val) << NewLine
1244 << "Used by :" << Context.print(UseInst) << NewLine
1245 << "Outside cycle :" << CI.print(C) << "\n\n";
1246 }
1247 }
1248
1249 for (auto &Block : F) {
1250 OS << "\nBLOCK " << Context.print(&Block) << '\n';
1251
1252 OS << "DEFINITIONS\n";
1254 Context.appendBlockDefs(Defs, Block);
1255 for (auto Value : Defs) {
1256 if (isDivergent(Value)) {
1257 FoundDivergence = true;
1258 OS << " DIVERGENT: ";
1259 } else {
1260 OS << " ";
1261 }
1262 OS << Context.print(Value) << NewLine;
1263 }
1264
1265 OS << "TERMINATORS\n";
1267 Context.appendBlockTerms(Terms, Block);
1268 bool DivergentTerminators = hasDivergentTerminator(Block);
1269 if (DivergentTerminators)
1270 FoundDivergence = true;
1271 for (auto *T : Terms) {
1272 if (DivergentTerminators)
1273 OS << " DIVERGENT: ";
1274 else
1275 OS << " ";
1276 OS << Context.print(T) << NewLine;
1277 }
1278
1279 OS << "END BLOCK\n";
1280 }
1281
1282 if (!FoundDivergence)
1283 OS << "ALL VALUES UNIFORM\n";
1284}
1285
1286template <typename ContextT>
1290 return make_range(DA->TemporalDivergenceList.begin(),
1291 DA->TemporalDivergenceList.end());
1292}
1293
1294template <typename ContextT>
1295const typename ContextT::FunctionT &
1297 return DA->getFunction();
1298}
1299
1300template <typename ContextT>
1303 return DA->getCycleInfo();
1304}
1305
1306/// Whether \p V is divergent at its definition.
1307/// A default-constructed instance (no analysis computed) reports everything
1308/// as uniform, which is conservatively correct for non-divergent targets.
1309template <typename ContextT>
1311 return DA && DA->isDivergent(V);
1312}
1313
1314template <typename ContextT>
1316 const InstructionT *I) const {
1317 assert(I->isTerminator() && "Expected a terminator instruction!");
1318 return DA && DA->isDivergentTerminator(*I);
1319}
1320
1321template <typename ContextT>
1323 return DA && DA->isDivergentUse(U);
1324}
1325
1326template <typename ContextT>
1328 return DA && DA->hasDivergentTerminator(B);
1329}
1330
1331template <typename ContextT>
1333 if (DA)
1334 DA->forgetValue(V);
1335}
1336
1337/// \brief T helper function for printing.
1338template <typename ContextT>
1340 if (!DA) {
1341 Out << " Uniformity analysis not computed (no branch divergence).\n";
1342 return;
1343 }
1344 DA->print(Out);
1345}
1346
1347template <typename ContextT>
1348void llvm::ModifiedPostOrder<ContextT>::computeStackPO(
1349 SmallVectorImpl<const BlockT *> &Stack, const CycleInfoT &CI, CycleRef C,
1351 LLVM_DEBUG(dbgs() << "inside computeStackPO\n");
1352 while (!Stack.empty()) {
1353 auto *NextBB = Stack.back();
1354 if (Finalized.count(NextBB)) {
1355 Stack.pop_back();
1356 continue;
1357 }
1358 LLVM_DEBUG(dbgs() << " visiting " << CI.getSSAContext().print(NextBB)
1359 << "\n");
1360 CycleRef NestedCycle = CI.getCycle(NextBB);
1361 if (C != NestedCycle &&
1362 (!C || (NestedCycle && CI.contains(C, NestedCycle)))) {
1363 LLVM_DEBUG(dbgs() << " found a cycle\n");
1364 while (CI.getParentCycle(NestedCycle) != C)
1365 NestedCycle = CI.getParentCycle(NestedCycle);
1366
1367 SmallVector<BlockT *, 3> NestedExits;
1368 CI.getExitBlocks(NestedCycle, NestedExits);
1369 bool PushedNodes = false;
1370 for (auto *NestedExitBB : NestedExits) {
1371 LLVM_DEBUG(dbgs() << " examine exit: "
1372 << CI.getSSAContext().print(NestedExitBB) << "\n");
1373 if (C && !CI.contains(C, NestedExitBB))
1374 continue;
1375 if (Finalized.count(NestedExitBB))
1376 continue;
1377 PushedNodes = true;
1378 Stack.push_back(NestedExitBB);
1379 LLVM_DEBUG(dbgs() << " pushed exit: "
1380 << CI.getSSAContext().print(NestedExitBB) << "\n");
1381 }
1382 if (!PushedNodes) {
1383 // All loop exits finalized -> finish this node
1384 Stack.pop_back();
1385 computeCyclePO(CI, NestedCycle, Finalized);
1386 }
1387 continue;
1388 }
1389
1390 LLVM_DEBUG(dbgs() << " no nested cycle, going into DAG\n");
1391 // DAG-style
1392 bool PushedNodes = false;
1393 for (auto *SuccBB : successors(NextBB)) {
1394 LLVM_DEBUG(dbgs() << " examine succ: "
1395 << CI.getSSAContext().print(SuccBB) << "\n");
1396 if (C && !CI.contains(C, SuccBB))
1397 continue;
1398 if (Finalized.count(SuccBB))
1399 continue;
1400 PushedNodes = true;
1401 Stack.push_back(SuccBB);
1402 LLVM_DEBUG(dbgs() << " pushed succ: " << CI.getSSAContext().print(SuccBB)
1403 << "\n");
1404 }
1405 if (!PushedNodes) {
1406 // Never push nodes twice
1407 LLVM_DEBUG(dbgs() << " finishing node: "
1408 << CI.getSSAContext().print(NextBB) << "\n");
1409 Stack.pop_back();
1410 Finalized.insert(NextBB);
1411 appendBlock(*NextBB);
1412 }
1413 }
1414 LLVM_DEBUG(dbgs() << "exited computeStackPO\n");
1415}
1416
1417template <typename ContextT>
1418void ModifiedPostOrder<ContextT>::computeCyclePO(
1419 const CycleInfoT &CI, CycleRef C,
1421 LLVM_DEBUG(dbgs() << "inside computeCyclePO\n");
1423 auto *CycleHeader = CI.getHeader(C);
1424
1425 LLVM_DEBUG(dbgs() << " noted header: "
1426 << CI.getSSAContext().print(CycleHeader) << "\n");
1427 assert(!Finalized.count(CycleHeader));
1428 Finalized.insert(CycleHeader);
1429
1430 // Visit the header last
1431 LLVM_DEBUG(dbgs() << " finishing header: "
1432 << CI.getSSAContext().print(CycleHeader) << "\n");
1433 appendBlock(*CycleHeader, CI.isReducible(C));
1434
1435 // Initialize with immediate successors
1436 for (auto *BB : successors(CycleHeader)) {
1437 LLVM_DEBUG(dbgs() << " examine succ: " << CI.getSSAContext().print(BB)
1438 << "\n");
1439 if (!CI.contains(C, BB))
1440 continue;
1441 if (BB == CycleHeader)
1442 continue;
1443 if (!Finalized.count(BB)) {
1444 LLVM_DEBUG(dbgs() << " pushed succ: " << CI.getSSAContext().print(BB)
1445 << "\n");
1446 Stack.push_back(BB);
1447 }
1448 }
1449
1450 // Compute PO inside region
1451 computeStackPO(Stack, CI, C, Finalized);
1452
1453 LLVM_DEBUG(dbgs() << "exited computeCyclePO\n");
1454}
1455
1456/// \brief Generically compute the modified post order.
1457template <typename ContextT>
1461 auto *F = CI.getFunction();
1462 POIndex.assign(GraphTraits<const FunctionT *>::getMaxNumber(F), InvalidIndex);
1463 Stack.reserve(24); // FIXME made-up number
1464 Stack.push_back(&F->front());
1465 computeStackPO(Stack, CI, CycleRef(), Finalized);
1466}
1467
1468} // namespace llvm
1469
1470#undef DEBUG_TYPE
1471
1472#endif // LLVM_ADT_GENERICUNIFORMITYIMPL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SparseBitVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const unsigned InvalidIndex
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Compute divergence starting with a divergent branch.
GenericSyncDependenceAnalysis< ContextT > SyncDependenceAnalysisT
const BlockT *& label(const BlockT *BB)
typename ContextT::DominatorTreeT DominatorTreeT
bool computeJoin(const BlockT &SuccBlock, const BlockT &PushedLabel)
std::unique_ptr< DivergenceDescriptorT > DivDesc
void printDefs(raw_ostream &Out)
typename ContextT::FunctionT FunctionT
GenericCycleInfo< ContextT > CycleInfoT
SmallVector< const BlockT * > BlockLabels
ModifiedPostOrder< ContextT > ModifiedPO
std::unique_ptr< DivergenceDescriptorT > computeJoinPoints()
bool visitCycleExitEdge(const BlockT &ExitBlock, const BlockT &Label)
typename ContextT::ValueRefT ValueRefT
typename ContextT::BlockT BlockT
DivergencePropagator(const ModifiedPO &CyclePOT, const DominatorTreeT &DT, const CycleInfoT &CI, const BlockT &DivTermBlock)
bool visitEdge(const BlockT &SuccBlock, const BlockT &Label)
typename SyncDependenceAnalysisT::DivergenceDescriptor DivergenceDescriptorT
Cycle information for a function.
Locate join blocks for disjoint paths starting at a divergent branch.
GenericSyncDependenceAnalysis(const ContextT &Context, const DominatorTreeT &DT, const CycleInfoT &CI)
ModifiedPostOrder< ContextT > ModifiedPO
DivergencePropagator< ContextT > DivergencePropagatorT
SmallPtrSet< const BlockT *, 4 > ConstBlockSet
typename ContextT::DominatorTreeT DominatorTreeT
GenericCycleInfo< ContextT > CycleInfoT
typename ContextT::FunctionT FunctionT
typename ContextT::InstructionT InstructionT
typename ContextT::ValueRefT ValueRefT
const DivergenceDescriptor & getJoinBlocks(const BlockT *DivTermBlock)
Computes divergent join points and cycle exits caused by branch divergence in Term.
SmallVector< TemporalDivergenceTuple, 8 > TemporalDivergenceList
bool isAlwaysUniform(const InstructionT &Instr) const
Whether Val will always return a uniform value regardless of its operands.
bool isCustomUniform(const InstructionT &I) const
Check if an instruction with Custom uniformity can be proven uniform based on its operands.
typename ContextT::ValueRefT ValueRefT
void analyzeControlDivergence(const InstructionT &Term)
Mark Term as divergent and push all Instructions that become divergent as a result on the worklist.
void addCustomUniformityCandidate(const InstructionT *I)
Add an instruction that requires custom uniformity analysis.
bool isDivergent(ConstValueRefT V) const
Whether Val is divergent at its definition.
void recordTemporalDivergence(ConstValueRefT, const InstructionT *, CycleRef)
bool isDivergentUse(const UseT &U) const
bool hasDivergentDefs(const InstructionT &I) const
SmallPtrSet< const InstructionT *, 8 > CustomUniformityCandidates
typename ContextT::InstructionT InstructionT
bool printDivergentArgs(raw_ostream &Out) const
Print divergent arguments and return true if any were found.
void forgetValue(ConstValueRefT V)
Call before erasing V, or a later instruction reusing its address may be misclassified as uniform.
typename ContextT::ConstValueRefT ConstValueRefT
typename ContextT::DominatorTreeT DominatorTreeT
void compute()
Propagate divergence to all instructions in the region.
bool hasDivergentTerminator(const BlockT &B) const
GenericUniformityAnalysisImpl(const DominatorTreeT &DT, const CycleInfoT &CI, const TargetTransformInfo *TTI)
bool markDefsDivergent(const InstructionT &Instr)
Mark outputs of Instr as divergent.
typename ContextT::FunctionT FunctionT
std::vector< const InstructionT * > Worklist
void markDivergent(const InstructionT &I)
Examine I for divergent outputs and add to the worklist.
SmallPtrSet< const BlockT *, 32 > DivergentTermBlocks
bool isDivergentTerminator(const InstructionT &I) const
GenericCycleInfo< ContextT > CycleInfoT
void addUniformOverride(const InstructionT &Instr)
Mark UniVal as a value that is always uniform.
std::tuple< ConstValueRefT, InstructionT *, CycleRef > TemporalDivergenceTuple
typename SyncDependenceAnalysisT::DivergenceDescriptor DivergenceDescriptorT
GenericSyncDependenceAnalysis< ContextT > SyncDependenceAnalysisT
bool hasDivergentTerminator(const BlockT &B)
void print(raw_ostream &Out) const
T helper function for printing.
bool isDivergentAtDef(ConstValueRefT V) const
Whether V is divergent at its definition.
std::tuple< ConstValueRefT, InstructionT *, CycleRef > TemporalDivergenceTuple
typename ContextT::ConstValueRefT ConstValueRefT
typename ContextT::BlockT BlockT
bool isDivergentAtUse(const UseT &U) const
Whether U is divergent at its use.
const CycleInfoT & getCycleInfo() const
The cycle info this analysis was computed with.
typename ContextT::InstructionT InstructionT
const FunctionT & getFunction() const
The GPU kernel this analysis result is for.
bool isDivergentTerminator(const InstructionT *I) const
void forgetValue(ConstValueRefT V)
Call before erasing V, or a later instruction reusing its address may be misclassified as uniform.
GenericCycleInfo< ContextT > CycleInfoT
typename ContextT::DominatorTreeT DominatorTreeT
iterator_range< TemporalDivergenceTuple * > getTemporalDivergenceList() const
A helper class to return the specified delimiter string after the first invocation of operator String...
Construct a specially modified post-order traversal of cycles.
typename ContextT::FunctionT FunctionT
bool isReducibleCycleHeader(const BlockT *BB) const
void appendBlock(const BlockT &BB, bool IsReducibleCycleHeader=false)
const BlockT * operator[](size_t Idx) const
ModifiedPostOrder(const ContextT &C)
unsigned count(BlockT *BB) const
void compute(const CycleInfoT &CI)
Generically compute the modified post order.
GenericCycleInfo< ContextT > CycleInfoT
unsigned getIndex(const BlockT *BB) const
typename std::vector< BlockT * >::const_iterator const_iterator
typename ContextT::DominatorTreeT DominatorTreeT
typename ContextT::BlockT BlockT
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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 pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
bool insertIfNotContained(const CycleInfoT &CI, SmallVector< CycleRef > &Cycles, CycleRef Candidate)
Add Candidate to Cycles if it is not already contained in Cycles.
CycleRef getExtDivCycle(const CycleInfoT &CI, CycleRef Cycle, const BlockT *DivTermBlock, const BlockT *JoinBlock)
Return the outermost cycle made divergent by branch outside it.
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
CycleRef getOutermostDivergentCycle(const CycleInfoT &CI, CycleRef Cycle, const BlockT *DivTermBlock, const BlockT *JoinBlock, const DominatorTreeT &DT, ContextT &Context)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto succ_size(const MachineBasicBlock *BB)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
TargetTransformInfo TTI
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
auto instrs(const MachineBasicBlock &BB)
CycleRef getIntDivCycle(const CycleInfoT &CI, CycleRef Cycle, const BlockT *DivTermBlock, const BlockT *JoinBlock, const DominatorTreeT &DT, ContextT &Context)
Return the outermost cycle made divergent by branch inside it.
Information discovered by the sync dependence analysis for each divergent branch.