LLVM 24.0.0git
SPIRVStructurizer.cpp
Go to the documentation of this file.
1//===-- SPIRVStructurizer.cpp ----------------------*- 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//===----------------------------------------------------------------------===//
10
12#include "SPIRV.h"
14#include "SPIRVSubtarget.h"
15#include "SPIRVUtils.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/IR/CFG.h"
21#include "llvm/IR/Dominators.h"
22#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsSPIRV.h"
31#include <optional>
32#include <stack>
33
34using namespace llvm;
35using namespace SPIRV;
36
38using Edge = std::pair<BasicBlock *, BasicBlock *>;
39
40// Returns the exact convergence region in the tree defined by `Node` for which
41// `BB` is the header, nullptr otherwise.
42static const ConvergenceRegion *
44 if (Node->Entry == BB)
45 return Node;
46
47 for (auto *Child : Node->Children) {
48 const auto *CR = getRegionForHeader(Child, BB);
49 if (CR != nullptr)
50 return CR;
51 }
52 return nullptr;
53}
54
55// Returns the single BasicBlock exiting the convergence region `CR`,
56// nullptr if no such exit exists.
59 for (BasicBlock *Exit : CR->Exits) {
60 for (BasicBlock *Successor : successors(Exit)) {
61 if (CR->Blocks.count(Successor) == 0)
62 ExitTargets.insert(Successor);
63 }
64 }
65
66 assert(ExitTargets.size() <= 1);
67 if (ExitTargets.size() == 0)
68 return nullptr;
69
70 return *ExitTargets.begin();
71}
72
73// Returns the merge block designated by I if I is a merge instruction, nullptr
74// otherwise.
77 if (II == nullptr)
78 return nullptr;
79
80 if (II->getIntrinsicID() != Intrinsic::spv_loop_merge &&
81 II->getIntrinsicID() != Intrinsic::spv_selection_merge)
82 return nullptr;
83
84 BlockAddress *BA = cast<BlockAddress>(II->getOperand(0));
85 return BA->getBasicBlock();
86}
87
88// Returns the continue block designated by I if I is an OpLoopMerge, nullptr
89// otherwise.
92 if (II == nullptr)
93 return nullptr;
94
95 if (II->getIntrinsicID() != Intrinsic::spv_loop_merge)
96 return nullptr;
97
98 BlockAddress *BA = cast<BlockAddress>(II->getOperand(1));
99 return BA->getBasicBlock();
100}
101
102// Returns true if Header has one merge instruction which designated Merge as
103// merge block.
105 for (auto &I : Header) {
107 if (MB == &Merge)
108 return true;
109 }
110 return false;
111}
112
113// Returns true if the BB has one OpLoopMerge instruction.
115 for (auto &I : BB)
117 return true;
118 return false;
119}
120
121// Returns true is I is an OpSelectionMerge or OpLoopMerge instruction, false
122// otherwise.
124 return getDesignatedMergeBlock(I) != nullptr;
125}
126
127// Returns all blocks in F having at least one OpLoopMerge or OpSelectionMerge
128// instruction.
131 for (BasicBlock &BB : F) {
132 for (Instruction &I : BB) {
133 if (getDesignatedMergeBlock(&I) != nullptr)
134 Output.insert(&BB);
135 }
136 }
137 return Output;
138}
139
140// Returns all basic blocks in |F| referenced by at least 1
141// OpSelectionMerge/OpLoopMerge instruction.
144 for (BasicBlock &BB : F) {
145 for (Instruction &I : BB) {
147 if (MB != nullptr)
148 Output.insert(MB);
149 }
150 }
151 return Output;
152}
153
154// Return all the merge instructions contained in BB.
155// Note: the SPIR-V spec doesn't allow a single BB to contain more than 1 merge
156// instruction, but this can happen while we structurize the CFG.
157static std::vector<Instruction *> getMergeInstructions(BasicBlock &BB) {
158 std::vector<Instruction *> Output;
159 for (Instruction &I : BB)
160 if (isMergeInstruction(&I))
161 Output.push_back(&I);
162 return Output;
163}
164
165// Returns all basic blocks in |F| referenced as continue target by at least 1
166// OpLoopMerge instruction.
169 for (BasicBlock &BB : F) {
170 for (Instruction &I : BB) {
172 if (MB != nullptr)
173 Output.insert(MB);
174 }
175 }
176 return Output;
177}
178
179// Do a preorder traversal of the CFG starting from the BB |Start|.
180// point. Calls |op| on each basic block encountered during the traversal.
181static void visit(BasicBlock &Start, std::function<bool(BasicBlock *)> op) {
182 std::stack<BasicBlock *> ToVisit;
184
185 ToVisit.push(&Start);
186 Seen.insert(ToVisit.top());
187 while (ToVisit.size() != 0) {
188 BasicBlock *BB = ToVisit.top();
189 ToVisit.pop();
190
191 if (!op(BB))
192 continue;
193
194 for (auto Succ : successors(BB)) {
195 if (Seen.contains(Succ))
196 continue;
197 ToVisit.push(Succ);
198 Seen.insert(Succ);
199 }
200 }
201}
202
203// Replaces the conditional and unconditional branch targets of |BB| by
204// |NewTarget| if the target was |OldTarget|. This function also makes sure the
205// associated merge instruction gets updated accordingly.
206static void replaceIfBranchTargets(BasicBlock *BB, BasicBlock *OldTarget,
207 BasicBlock *NewTarget) {
208 auto *BI = cast<CondBrInst>(BB->getTerminator());
209
210 // 1. Replace all matching successors.
211 for (size_t i = 0; i < BI->getNumSuccessors(); i++) {
212 if (BI->getSuccessor(i) == OldTarget)
213 BI->setSuccessor(i, NewTarget);
214 }
215
216 // Branch had 2 successors, maybe now both are the same?
217 if (BI->getSuccessor(0) != BI->getSuccessor(1))
218 return;
219
220 // Note: we may end up here because the original IR had such branches.
221 // This means Target is not necessarily equal to NewTarget.
222 IRBuilder<> Builder(BB);
223 Builder.SetInsertPoint(BI);
224 Builder.CreateBr(BI->getSuccessor(0));
225 BI->eraseFromParent();
226
227 // The branch was the only instruction, nothing else to do.
228 if (BB->size() == 1)
229 return;
230
231 // Otherwise, we need to check: was there an OpSelectionMerge before this
232 // branch? If we removed the OpBranchConditional, we must also remove the
233 // OpSelectionMerge. This is not valid for OpLoopMerge:
236 if (!II || II->getIntrinsicID() != Intrinsic::spv_selection_merge)
237 return;
238
239 Constant *C = cast<Constant>(II->getOperand(0));
240 II->eraseFromParent();
241 if (!C->isConstantUsed())
242 C->destroyConstant();
243}
244
245// Replaces the target of branch instruction in |BB| with |NewTarget| if it
246// was |OldTarget|. This function also fixes the associated merge instruction.
247// Note: this function does not simplify branching instructions, it only updates
248// targets. See also: simplifyBranches.
249static void replaceBranchTargets(BasicBlock *BB, BasicBlock *OldTarget,
250 BasicBlock *NewTarget) {
251 auto *T = BB->getTerminator();
252 if (isa<ReturnInst>(T))
253 return;
254 if (auto *BI = dyn_cast<UncondBrInst>(T)) {
255 if (BI->getSuccessor() == OldTarget)
256 BI->setSuccessor(NewTarget);
257 return;
258 }
259
260 if (isa<CondBrInst>(T))
261 return replaceIfBranchTargets(BB, OldTarget, NewTarget);
262
263 if (auto *SI = dyn_cast<SwitchInst>(T)) {
264 for (size_t i = 0; i < SI->getNumSuccessors(); i++) {
265 if (SI->getSuccessor(i) == OldTarget)
266 SI->setSuccessor(i, NewTarget);
267 }
268 return;
269 }
270
271 assert(false && "Unhandled terminator type.");
272}
273
274namespace {
275// Given a reducible CFG, produces a structurized CFG in the SPIR-V sense,
276// adding merge instructions when required.
277class SPIRVStructurizerImpl {
278 LoopInfo &LI;
279 ConvergenceRegionInfo &RegionInfo;
280
281 struct DivergentConstruct;
282 // Represents a list of condition/loops/switch constructs.
283 // See SPIR-V 2.11.2. Structured Control-flow Constructs for the list of
284 // constructs.
285 using ConstructList = std::vector<std::unique_ptr<DivergentConstruct>>;
286
287 // Represents a divergent construct in the SPIR-V sense.
288 // Such constructs are represented by a header (entry), a merge block (exit),
289 // and possibly a continue block (back-edge). A construct can contain other
290 // constructs, but their boundaries do not cross.
291 struct DivergentConstruct {
292 BasicBlock *Header = nullptr;
293 BasicBlock *Merge = nullptr;
294 BasicBlock *Continue = nullptr;
295
296 DivergentConstruct *Parent = nullptr;
297 ConstructList Children;
298 };
299
300 // An helper class to clean the construct boundaries.
301 // It is used to gather the list of blocks that should belong to each
302 // divergent construct, and possibly modify CFG edges when exits would cross
303 // the boundary of multiple constructs.
304 struct Splitter {
305 Function &F;
308 std::optional<PartialOrderingVisitor> POV;
309
310 Splitter(Function &F) : F(F) { invalidate(); }
311
312 void invalidate() {
313 PDT.recalculate(F);
314 POV.emplace(F);
315 }
316
317 const DomTreeBuilder::BBDomTree &getDT() const {
318 return POV->getDominatorTree();
319 }
320
321 // Returns the list of blocks that belong to a SPIR-V loop construct,
322 // including the continue construct.
323 std::vector<BasicBlock *> getLoopConstructBlocks(BasicBlock *Header,
324 BasicBlock *Merge) {
325 const DomTreeBuilder::BBDomTree &DT = getDT();
326 assert(DT.dominates(Header, Merge));
327 std::vector<BasicBlock *> Output;
328 POV->partialOrderVisit(*Header, [&](BasicBlock *BB) {
329 if (BB == Merge)
330 return false;
331 if (DT.dominates(Merge, BB) || !DT.dominates(Header, BB))
332 return false;
333 Output.push_back(BB);
334 return true;
335 });
336 return Output;
337 }
338
339 // Returns the list of blocks that belong to a SPIR-V selection construct.
340 std::vector<BasicBlock *>
341 getSelectionConstructBlocks(DivergentConstruct *Node) {
342 const DomTreeBuilder::BBDomTree &DT = getDT();
343 assert(DT.dominates(Node->Header, Node->Merge));
344 BlockSet OutsideBlocks;
345 OutsideBlocks.insert(Node->Merge);
346
347 for (DivergentConstruct *It = Node->Parent; It != nullptr;
348 It = It->Parent) {
349 OutsideBlocks.insert(It->Merge);
350 if (It->Continue)
351 OutsideBlocks.insert(It->Continue);
352 }
353
354 std::vector<BasicBlock *> Output;
355 POV->partialOrderVisit(*Node->Header, [&](BasicBlock *BB) {
356 if (OutsideBlocks.count(BB) != 0)
357 return false;
358 if (DT.dominates(Node->Merge, BB) || !DT.dominates(Node->Header, BB))
359 return false;
360 Output.push_back(BB);
361 return true;
362 });
363 return Output;
364 }
365
366 // Splits the given edges by recreating proxy nodes so that the destination
367 // has unique incoming edges from this region.
368 //
369 // clang-format off
370 //
371 // In SPIR-V, constructs must have a single exit/merge.
372 // Given nodes A and B in the construct, a node C outside, and the following edges.
373 // A -> C
374 // B -> C
375 //
376 // In such cases, we must create a new exit node D, that belong to the construct to make is viable:
377 // A -> D -> C
378 // B -> D -> C
379 //
380 // This is fine (assuming C has no PHI nodes), but requires handling the merge instruction here.
381 // By adding a proxy node, we create a regular divergent shape which can easily be regularized later on.
382 // A -> D -> D1 -> C
383 // B -> D -> D2 -> C
384 //
385 // A, B, D belongs to the construct. D is the exit. D1 and D2 are empty.
386 //
387 // clang-format on
388 std::vector<Edge>
389 createAliasBlocksForComplexEdges(std::vector<Edge> Edges) {
390 SmallPtrSet<BasicBlock *, 0> Seen;
391 std::vector<Edge> Output;
392 Output.reserve(Edges.size());
393
394 for (auto &[Src, Dst] : Edges) {
395 auto [Iterator, Inserted] = Seen.insert(Src);
396 if (!Inserted) {
397 // Src already a source node. Cannot have 2 edges from A to B.
398 // Creating alias source block.
400 F.getContext(), Src->getName() + ".new.src", &F);
401 replaceBranchTargets(Src, Dst, NewSrc);
402 IRBuilder<> Builder(NewSrc);
403 Builder.CreateBr(Dst);
404 Src = NewSrc;
405 }
406
407 Output.emplace_back(Src, Dst);
408 }
409
410 return Output;
411 }
412
413 // Given a construct defined by |Header|, and a list of exiting edges
414 // |Edges|, creates a new single exit node, fixing up those edges.
415 BasicBlock *createSingleExitNode(BasicBlock *Header,
416 std::vector<Edge> &Edges) {
417
418 std::vector<Edge> FixedEdges = createAliasBlocksForComplexEdges(Edges);
419
420 std::vector<BasicBlock *> Dsts;
421 DenseMap<BasicBlock *, ConstantInt *> DstToIndex;
422 auto NewExit = BasicBlock::Create(F.getContext(),
423 Header->getName() + ".new.exit", &F);
424 IRBuilder<> ExitBuilder(NewExit);
425 for (auto &[Src, Dst] : FixedEdges) {
426 if (DstToIndex.count(Dst) != 0)
427 continue;
428 DstToIndex.try_emplace(Dst, ExitBuilder.getInt32(DstToIndex.size()));
429 Dsts.push_back(Dst);
430 }
431
432 if (Dsts.size() == 1) {
433 for (auto &[Src, Dst] : FixedEdges) {
434 replaceBranchTargets(Src, Dst, NewExit);
435 }
436 ExitBuilder.CreateBr(Dsts[0]);
437 return NewExit;
438 }
439
440 AllocaInst *Variable = createVariable(F, ExitBuilder.getInt32Ty());
441 for (auto &[Src, Dst] : FixedEdges) {
442 IRBuilder<> B2(Src);
443 B2.SetInsertPoint(Src->getFirstInsertionPt());
444 B2.CreateStore(DstToIndex[Dst], Variable);
445 replaceBranchTargets(Src, Dst, NewExit);
446 }
447
448 Value *Load = ExitBuilder.CreateLoad(ExitBuilder.getInt32Ty(), Variable);
449
450 // If we can avoid an OpSwitch, generate an OpBranch. Reason is some
451 // OpBranch are allowed to exist without a new OpSelectionMerge if one of
452 // the branch is the parent's merge node, while OpSwitches are not.
453 if (Dsts.size() == 2) {
454 Value *Condition =
455 ExitBuilder.CreateCmp(CmpInst::ICMP_EQ, DstToIndex[Dsts[0]], Load);
456 ExitBuilder.CreateCondBr(Condition, Dsts[0], Dsts[1]);
457 return NewExit;
458 }
459
460 SwitchInst *Sw = ExitBuilder.CreateSwitch(Load, Dsts[0], Dsts.size() - 1);
461 for (BasicBlock *BB : drop_begin(Dsts))
462 Sw->addCase(DstToIndex[BB], BB);
463 return NewExit;
464 }
465 };
466
467 // Creates a new basic block in F with a single OpUnreachable instruction.
468 BasicBlock *CreateUnreachable(Function &F) {
469 BasicBlock *BB = BasicBlock::Create(F.getContext(), "unreachable", &F);
470 IRBuilder<> Builder(BB);
471 Builder.CreateUnreachable();
472 return BB;
473 }
474
475 // Add OpLoopMerge instruction on cycles.
476 bool addMergeForLoops(Function &F) {
477 auto *TopLevelRegion = RegionInfo.getTopLevelRegion();
478
479 bool Modified = false;
480 for (auto &BB : F) {
481 // Not a loop header. Ignoring for now.
482 if (!LI.isLoopHeader(&BB))
483 continue;
484 auto *L = LI.getLoopFor(&BB);
485
486 // This loop header is not the entrance of a convergence region. Ignoring
487 // this block.
488 auto *CR = getRegionForHeader(TopLevelRegion, &BB);
489 if (CR == nullptr)
490 continue;
491
492 IRBuilder<> Builder(&BB);
493
494 auto *Merge = getExitFor(CR);
495 // We are indeed in a loop, but there are no exits (infinite loop).
496 // This could be caused by a bad shader, but also could be an artifact
497 // from an earlier optimization. It is not always clear if structurally
498 // reachable means runtime reachable, so we cannot error-out. What we must
499 // do however is to make is legal on the SPIR-V point of view, hence
500 // adding an unreachable merge block.
501 if (Merge == nullptr) {
502 UncondBrInst *Br = cast<UncondBrInst>(BB.getTerminator());
503 Merge = CreateUnreachable(F);
504 Builder.SetInsertPoint(Br);
505 Builder.CreateCondBr(Builder.getFalse(), Merge, Br->getSuccessor(0));
506 Br->eraseFromParent();
507 }
508
509 auto *Continue = L->getLoopLatch();
510
511 Builder.SetInsertPoint(BB.getTerminator());
512 auto MergeAddress = BlockAddress::get(Merge->getParent(), Merge);
513 auto ContinueAddress = BlockAddress::get(Continue->getParent(), Continue);
514 SmallVector<Value *, 2> Args = {MergeAddress, ContinueAddress};
515 SmallVector<unsigned, 1> LoopControlImms =
517 for (unsigned Imm : LoopControlImms)
518 Args.emplace_back(ConstantInt::get(Builder.getInt32Ty(), Imm));
519 Builder.CreateIntrinsic(Intrinsic::spv_loop_merge, {Args});
520 Modified = true;
521 }
522
523 return Modified;
524 }
525
526 // Adds an OpSelectionMerge to the immediate dominator or each node with an
527 // in-degree of 2 or more which is not already the merge target of an
528 // OpLoopMerge/OpSelectionMerge.
529 bool addMergeForNodesWithMultiplePredecessors(Function &F) {
531 DT.recalculate(F);
532
533 bool Modified = false;
534 for (auto &BB : F) {
535 if (pred_size(&BB) <= 1)
536 continue;
537
538 if (hasLoopMergeInstruction(BB) && pred_size(&BB) <= 2)
539 continue;
540
541 assert(DT.getNode(&BB)->getIDom());
542 BasicBlock *Header = DT.getNode(&BB)->getIDom()->getBlock();
543
544 if (isDefinedAsSelectionMergeBy(*Header, BB))
545 continue;
546
547 IRBuilder<> Builder(Header);
548 Builder.SetInsertPoint(Header->getTerminator());
549
550 auto MergeAddress = BlockAddress::get(BB.getParent(), &BB);
551 createOpSelectMerge(&Builder, MergeAddress);
552
553 Modified = true;
554 }
555
556 return Modified;
557 }
558
559 // When a block has multiple OpSelectionMerge/OpLoopMerge instructions, sorts
560 // them to put the "largest" first. A merge instruction is defined as larger
561 // than another when its target merge block post-dominates the other target's
562 // merge block. (This ordering should match the nesting ordering of the source
563 // HLSL).
564 bool sortSelectionMerge(PartialOrderingVisitor &Visitor, BasicBlock &Block) {
565 std::vector<Instruction *> MergeInstructions;
566 for (Instruction &I : Block)
567 if (isMergeInstruction(&I))
568 MergeInstructions.push_back(&I);
569
570 if (MergeInstructions.size() <= 1)
571 return false;
572
573 Instruction *InsertionPoint = *MergeInstructions.begin();
574
575 llvm::sort(MergeInstructions,
576 [&Visitor](Instruction *Left, Instruction *Right) {
577 if (Left == Right)
578 return false;
581 return !Visitor.compare(RightMerge, LeftMerge);
582 });
583
584 for (Instruction *I : MergeInstructions) {
585 I->moveBefore(InsertionPoint->getIterator());
586 InsertionPoint = I;
587 }
588
589 return true;
590 }
591
592 // Sorts selection merge headers in |F|.
593 // A is sorted before B if the merge block designated by B is an ancestor of
594 // the one designated by A.
595 bool sortSelectionMergeHeaders(Function &F) {
596 bool Modified = false;
597 PartialOrderingVisitor Visitor(F);
598 for (BasicBlock &BB : F) {
599 Modified |= sortSelectionMerge(Visitor, BB);
600 }
601 return Modified;
602 }
603
604 // Split basic blocks containing multiple OpLoopMerge/OpSelectionMerge
605 // instructions so each basic block contains only a single merge instruction.
606 bool splitBlocksWithMultipleHeaders(Function &F) {
607 std::stack<BasicBlock *> Work;
608 for (auto &BB : F) {
609 std::vector<Instruction *> MergeInstructions = getMergeInstructions(BB);
610 if (MergeInstructions.size() <= 1)
611 continue;
612 Work.push(&BB);
613 }
614
615 const bool Modified = Work.size() > 0;
616 while (Work.size() > 0) {
617 BasicBlock *Header = Work.top();
618 Work.pop();
619
620 std::vector<Instruction *> MergeInstructions =
621 getMergeInstructions(*Header);
622 for (unsigned i = 1; i < MergeInstructions.size(); i++) {
623 BasicBlock *NewBlock =
624 Header->splitBasicBlock(MergeInstructions[i], "new.header");
625
626 if (getDesignatedContinueBlock(MergeInstructions[0]) == nullptr) {
627 BasicBlock *Unreachable = CreateUnreachable(F);
628
629 Instruction *Term = Header->getTerminator();
630 IRBuilder<> Builder(Header);
631 Builder.SetInsertPoint(Term);
632 Builder.CreateCondBr(Builder.getTrue(), NewBlock, Unreachable);
633 Term->eraseFromParent();
634 }
635
636 Header = NewBlock;
637 }
638 }
639
640 return Modified;
641 }
642
643 // Adds an OpSelectionMerge to each block with an out-degree >= 2 which
644 // doesn't already have an OpSelectionMerge.
645 bool addMergeForDivergentBlocks(Function &F) {
647 PDT.recalculate(F);
648 bool Modified = false;
649
650 auto MergeBlocks = getMergeBlocks(F);
651 auto ContinueBlocks = getContinueBlocks(F);
652
653 for (auto &BB : F) {
654 if (getMergeInstructions(BB).size() != 0)
655 continue;
656
657 std::vector<BasicBlock *> Candidates;
658 for (BasicBlock *Successor : successors(&BB)) {
659 if (MergeBlocks.contains(Successor))
660 continue;
661 if (ContinueBlocks.contains(Successor))
662 continue;
663 Candidates.push_back(Successor);
664 }
665
666 if (Candidates.size() <= 1)
667 continue;
668
669 Modified = true;
670 BasicBlock *Merge = Candidates[0];
671
672 auto MergeAddress = BlockAddress::get(Merge->getParent(), Merge);
673 IRBuilder<> Builder(&BB);
674 Builder.SetInsertPoint(BB.getTerminator());
675 createOpSelectMerge(&Builder, MergeAddress);
676 }
677
678 return Modified;
679 }
680
681 // Gather all the exit nodes for the construct header by |Header| and
682 // containing the blocks |Construct|.
683 std::vector<Edge> getExitsFrom(const BlockSet &Construct,
684 BasicBlock &Header) {
685 std::vector<Edge> Output;
686 visit(Header, [&](BasicBlock *Item) {
687 if (Construct.count(Item) == 0)
688 return false;
689
690 for (BasicBlock *Successor : successors(Item)) {
691 if (Construct.count(Successor) == 0)
692 Output.emplace_back(Item, Successor);
693 }
694 return true;
695 });
696
697 return Output;
698 }
699
700 // Build a divergent construct tree searching from |BB|.
701 // If |Parent| is not null, this tree is attached to the parent's tree.
702 void constructDivergentConstruct(BlockSet &Visited, Splitter &S,
703 BasicBlock *BB, DivergentConstruct *Parent) {
704 if (Visited.count(BB) != 0)
705 return;
706 Visited.insert(BB);
707
708 auto MIS = getMergeInstructions(*BB);
709 if (MIS.size() == 0) {
710 for (BasicBlock *Successor : successors(BB))
711 constructDivergentConstruct(Visited, S, Successor, Parent);
712 return;
713 }
714
715 assert(MIS.size() == 1);
716 Instruction *MI = MIS[0];
717
720
721 auto Output = std::make_unique<DivergentConstruct>();
722 Output->Header = BB;
723 Output->Merge = Merge;
724 Output->Continue = Continue;
725 Output->Parent = Parent;
726
727 constructDivergentConstruct(Visited, S, Merge, Parent);
728 if (Continue)
729 constructDivergentConstruct(Visited, S, Continue, Output.get());
730
731 for (BasicBlock *Successor : successors(BB))
732 constructDivergentConstruct(Visited, S, Successor, Output.get());
733
734 if (Parent)
735 Parent->Children.emplace_back(std::move(Output));
736 }
737
738 // Returns the blocks belonging to the divergent construct |Node|.
739 BlockSet getConstructBlocks(Splitter &S, DivergentConstruct *Node) {
740 assert(Node->Header && Node->Merge);
741
742 if (Node->Continue) {
743 auto LoopBlocks = S.getLoopConstructBlocks(Node->Header, Node->Merge);
744 return BlockSet(LoopBlocks.begin(), LoopBlocks.end());
745 }
746
747 auto SelectionBlocks = S.getSelectionConstructBlocks(Node);
748 return BlockSet(SelectionBlocks.begin(), SelectionBlocks.end());
749 }
750
751 // Fixup the construct |Node| to respect a set of rules defined by the SPIR-V
752 // spec.
753 bool fixupConstruct(Splitter &S, DivergentConstruct *Node) {
754 bool Modified = false;
755 for (auto &Child : Node->Children)
756 Modified |= fixupConstruct(S, Child.get());
757
758 // This construct is the root construct. Does not represent any real
759 // construct, just a way to access the first level of the forest.
760 if (Node->Parent == nullptr)
761 return Modified;
762
763 // This node's parent is the root. Meaning this is a top-level construct.
764 // There can be multiple exists, but all are guaranteed to exit at most 1
765 // construct since we are at first level.
766 if (Node->Parent->Header == nullptr)
767 return Modified;
768
769 // Health check for the structure.
770 assert(Node->Header && Node->Merge);
771 assert(Node->Parent->Header && Node->Parent->Merge);
772
773 BlockSet ConstructBlocks = getConstructBlocks(S, Node);
774 auto Edges = getExitsFrom(ConstructBlocks, *Node->Header);
775
776 // No edges exiting the construct.
777 if (Edges.size() < 1)
778 return Modified;
779
780 bool HasBadEdge = Node->Merge == Node->Parent->Merge ||
781 Node->Merge == Node->Parent->Continue;
782 // BasicBlock *Target = Edges[0].second;
783 for (auto &[Src, Dst] : Edges) {
784 // - Breaking from a selection construct: S is a selection construct, S is
785 // the innermost structured
786 // control-flow construct containing A, and B is the merge block for S
787 // - Breaking from the innermost loop: S is the innermost loop construct
788 // containing A,
789 // and B is the merge block for S
790 if (Node->Merge == Dst)
791 continue;
792
793 // Entering the innermost loop’s continue construct: S is the innermost
794 // loop construct containing A, and B is the continue target for S
795 if (Node->Continue == Dst)
796 continue;
797
798 // TODO: what about cases branching to another case in the switch? Seems
799 // to work, but need to double check.
800 HasBadEdge = true;
801 }
802
803 if (!HasBadEdge)
804 return Modified;
805
806 // Create a single exit node gathering all exit edges.
807 BasicBlock *NewExit = S.createSingleExitNode(Node->Header, Edges);
808
809 // Fixup this construct's merge node to point to the new exit.
810 // Note: this algorithm fixes inner-most divergence construct first. So
811 // recursive structures sharing a single merge node are fixed from the
812 // inside toward the outside.
813 auto MergeInstructions = getMergeInstructions(*Node->Header);
814 assert(MergeInstructions.size() == 1);
815 Instruction *I = MergeInstructions[0];
816 BlockAddress *BA = cast<BlockAddress>(I->getOperand(0));
817 if (BA->getBasicBlock() == Node->Merge) {
818 auto MergeAddress = BlockAddress::get(NewExit->getParent(), NewExit);
819 I->setOperand(0, MergeAddress);
820 }
821
822 // Clean up of the possible dangling BockAddr operands to prevent MIR
823 // comments about "address of removed block taken".
824 if (!BA->isConstantUsed())
825 BA->destroyConstant();
826
827 Node->Merge = NewExit;
828 // Regenerate the dom trees.
829 S.invalidate();
830 return true;
831 }
832
833 bool splitCriticalEdges(Function &F) {
834 Splitter S(F);
835
836 DivergentConstruct Root;
837 BlockSet Visited;
838 constructDivergentConstruct(Visited, S, &*F.begin(), &Root);
839 return fixupConstruct(S, &Root);
840 }
841
842 // Simplify branches when possible:
843 // - if the 2 sides of a conditional branch are the same, transforms it to an
844 // unconditional branch.
845 // - if a switch has only 2 distinct successors, converts it to a conditional
846 // branch.
847 bool simplifyBranches(Function &F) {
848 bool Modified = false;
849
850 for (BasicBlock &BB : F) {
851 SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator());
852 if (!SI)
853 continue;
854 if (SI->getNumCases() > 1)
855 continue;
856
857 Modified = true;
858 IRBuilder<> Builder(&BB);
859 Builder.SetInsertPoint(SI);
860
861 if (SI->getNumCases() == 0) {
862 Builder.CreateBr(SI->getDefaultDest());
863 } else {
864 Value *Condition =
865 Builder.CreateCmp(CmpInst::ICMP_EQ, SI->getCondition(),
866 SI->case_begin()->getCaseValue());
867 Builder.CreateCondBr(Condition, SI->case_begin()->getCaseSuccessor(),
868 SI->getDefaultDest());
869 }
870 SI->eraseFromParent();
871 }
872
873 return Modified;
874 }
875
876 // Makes sure every case target in |F| is unique. If 2 cases branch to the
877 // same basic block, one of the targets is updated so it jumps to a new basic
878 // block ending with a single unconditional branch to the original target.
879 bool splitSwitchCases(Function &F) {
880 bool Modified = false;
881
882 for (BasicBlock &BB : F) {
883 SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator());
884 if (!SI)
885 continue;
886
887 BlockSet Seen;
888 Seen.insert(SI->getDefaultDest());
889
890 auto It = SI->case_begin();
891 while (It != SI->case_end()) {
892 BasicBlock *Target = It->getCaseSuccessor();
893
894 // Don't Split. Just remove cases branching to the default destination
895 // to prevent spurious extra successors thus preserving single-exit
896 // convergence regions (i.e. if a merged exit is default & a case).
897 if (Target == SI->getDefaultDest()) {
898 Modified = true;
899 It = SI->removeCase(It);
900 continue;
901 }
902
903 if (Seen.count(Target) == 0) {
904 Seen.insert(Target);
905 ++It;
906 continue;
907 }
908
909 Modified = true;
910 BasicBlock *NewTarget =
911 BasicBlock::Create(F.getContext(), "new.sw.case", &F);
912 IRBuilder<> Builder(NewTarget);
913 Builder.CreateBr(Target);
914 SI->addCase(It->getCaseValue(), NewTarget);
915 It = SI->removeCase(It);
916 }
917 }
918
919 return Modified;
920 }
921
922 // Removes blocks not contributing to any structured CFG. This assumes there
923 // is no PHI nodes.
924 bool removeUselessBlocks(Function &F) {
925 std::vector<BasicBlock *> ToRemove;
926
927 auto MergeBlocks = getMergeBlocks(F);
928 auto ContinueBlocks = getContinueBlocks(F);
929
930 for (BasicBlock &BB : F) {
931 if (BB.size() != 1)
932 continue;
933
935 continue;
936
937 if (MergeBlocks.count(&BB) != 0 || ContinueBlocks.count(&BB) != 0)
938 continue;
939
940 if (BB.getUniqueSuccessor() == nullptr)
941 continue;
942
944 std::vector<BasicBlock *> Predecessors(predecessors(&BB).begin(),
945 predecessors(&BB).end());
946 for (BasicBlock *Predecessor : Predecessors)
947 replaceBranchTargets(Predecessor, &BB, Successor);
948 ToRemove.push_back(&BB);
949 }
950
951 for (BasicBlock *BB : ToRemove)
952 BB->eraseFromParent();
953
954 return ToRemove.size() != 0;
955 }
956
957 bool addHeaderToRemainingDivergentDAG(Function &F) {
958 bool Modified = false;
959
960 auto MergeBlocks = getMergeBlocks(F);
961 auto ContinueBlocks = getContinueBlocks(F);
962 auto HeaderBlocks = getHeaderBlocks(F);
963
966 PDT.recalculate(F);
967 DT.recalculate(F);
968
969 for (BasicBlock &BB : F) {
970 if (HeaderBlocks.count(&BB) != 0)
971 continue;
972 if (succ_size(&BB) < 2)
973 continue;
974
975 size_t CandidateEdges = 0;
976 for (BasicBlock *Successor : successors(&BB)) {
977 if (MergeBlocks.count(Successor) != 0 ||
978 ContinueBlocks.count(Successor) != 0)
979 continue;
980 if (HeaderBlocks.count(Successor) != 0)
981 continue;
982 CandidateEdges += 1;
983 }
984
985 if (CandidateEdges <= 1)
986 continue;
987
988 BasicBlock *Header = &BB;
989 BasicBlock *Merge = PDT.getNode(&BB)->getIDom()->getBlock();
990
991 bool HasBadBlock = false;
992 visit(*Header, [&](const BasicBlock *Node) {
993 if (DT.dominates(Header, Node))
994 return false;
995 if (PDT.dominates(Merge, Node))
996 return false;
997 if (Node == Header || Node == Merge)
998 return true;
999
1000 HasBadBlock |= MergeBlocks.count(Node) != 0 ||
1001 ContinueBlocks.count(Node) != 0 ||
1002 HeaderBlocks.count(Node) != 0;
1003 return !HasBadBlock;
1004 });
1005
1006 if (HasBadBlock)
1007 continue;
1008
1009 Modified = true;
1010
1011 if (Merge == nullptr) {
1012 Merge = *successors(Header).begin();
1013 IRBuilder<> Builder(Header);
1014 Builder.SetInsertPoint(Header->getTerminator());
1015
1016 auto MergeAddress = BlockAddress::get(Merge->getParent(), Merge);
1017 createOpSelectMerge(&Builder, MergeAddress);
1018 continue;
1019 }
1020
1021 Instruction *SplitInstruction = Merge->getTerminator();
1022 if (isMergeInstruction(SplitInstruction->getPrevNode()))
1023 SplitInstruction = SplitInstruction->getPrevNode();
1024 BasicBlock *NewMerge =
1025 Merge->splitBasicBlockBefore(SplitInstruction, "new.merge");
1026
1027 IRBuilder<> Builder(Header);
1028 Builder.SetInsertPoint(Header->getTerminator());
1029
1030 auto MergeAddress = BlockAddress::get(NewMerge->getParent(), NewMerge);
1031 createOpSelectMerge(&Builder, MergeAddress);
1032 }
1033
1034 return Modified;
1035 }
1036
1037public:
1038 SPIRVStructurizerImpl(LoopInfo &LI, ConvergenceRegionInfo &RegionInfo)
1039 : LI(LI), RegionInfo(RegionInfo) {}
1040
1041 bool run(Function &F) {
1042 bool Modified = false;
1043
1044 // In LLVM, Switches are allowed to have several cases branching to the same
1045 // basic block. This is allowed in SPIR-V, but can make structurizing SPIR-V
1046 // harder, so first remove edge cases.
1047 Modified |= splitSwitchCases(F);
1048
1049 // LLVM allows conditional branches to have both side jumping to the same
1050 // block. It also allows switched to have a single default, or just one
1051 // case. Cleaning this up now.
1052 Modified |= simplifyBranches(F);
1053
1054 // At this state, we should have a reducible CFG with cycles.
1055 // STEP 1: Adding OpLoopMerge instructions to loop headers.
1056 Modified |= addMergeForLoops(F);
1057
1058 // STEP 2: adding OpSelectionMerge to each node with an in-degree >= 2.
1059 Modified |= addMergeForNodesWithMultiplePredecessors(F);
1060
1061 // STEP 3:
1062 // Sort selection merge, the largest construct goes first.
1063 // This simplifies the next step.
1064 Modified |= sortSelectionMergeHeaders(F);
1065
1066 // STEP 4: As this stage, we can have a single basic block with multiple
1067 // OpLoopMerge/OpSelectionMerge instructions. Splitting this block so each
1068 // BB has a single merge instruction.
1069 Modified |= splitBlocksWithMultipleHeaders(F);
1070
1071 // STEP 5: In the previous steps, we added merge blocks the loops and
1072 // natural merge blocks (in-degree >= 2). What remains are conditions with
1073 // an exiting branch (return, unreachable). In such case, we must start from
1074 // the header, and add headers to divergent construct with no headers.
1075 Modified |= addMergeForDivergentBlocks(F);
1076
1077 // STEP 6: At this stage, we have several divergent construct defines by a
1078 // header and a merge block. But their boundaries have no constraints: a
1079 // construct exit could be outside of the parents' construct exit. Such
1080 // edges are called critical edges. What we need is to split those edges
1081 // into several parts. Each part exiting the parent's construct by its merge
1082 // block.
1084
1085 // STEP 7: The previous steps possibly created a lot of "proxy" blocks.
1086 // Blocks with a single unconditional branch, used to create a valid
1087 // divergent construct tree. Some nodes are still requires (e.g: nodes
1088 // allowing a valid exit through the parent's merge block). But some are
1089 // left-overs of past transformations, and could cause actual validation
1090 // issues. E.g: the SPIR-V spec allows a construct to break to the parents
1091 // loop construct without an OpSelectionMerge, but this requires a straight
1092 // jump. If a proxy block lies between the conditional branch and the
1093 // parent's merge, the CFG is not valid.
1094 Modified |= removeUselessBlocks(F);
1095
1096 // STEP 8: Final fix-up steps: our tree boundaries are correct, but some
1097 // blocks are branching with no header. Those are often simple conditional
1098 // branches with 1 or 2 returning edges. Adding a header for those.
1099 Modified |= addHeaderToRemainingDivergentDAG(F);
1100
1101 // STEP 9: sort basic blocks to match both the LLVM & SPIR-V requirements.
1102 Modified |= sortBlocks(F);
1103
1104 return Modified;
1105 }
1106
1107 void createOpSelectMerge(IRBuilder<> *Builder, BlockAddress *MergeAddress) {
1108 Instruction *BBTerminatorInst = Builder->GetInsertBlock()->getTerminator();
1109
1110 MDNode *MDNode = BBTerminatorInst->getMetadata("hlsl.controlflow.hint");
1111
1112 ConstantInt *BranchHint = ConstantInt::get(Builder->getInt32Ty(), 0);
1113
1114 if (MDNode) {
1115 assert(MDNode->getNumOperands() == 2 &&
1116 "invalid metadata hlsl.controlflow.hint");
1117 BranchHint = mdconst::extract<ConstantInt>(MDNode->getOperand(1));
1118 }
1119
1120 SmallVector<Value *, 2> Args = {MergeAddress, BranchHint};
1121
1122 Builder->CreateIntrinsic(Intrinsic::spv_selection_merge,
1123 {MergeAddress->getType()}, Args);
1124 }
1125};
1126
1127class SPIRVStructurizer : public FunctionPass {
1128public:
1129 static char ID;
1130
1131 SPIRVStructurizer() : FunctionPass(ID) {}
1132
1133 bool runOnFunction(Function &F) override {
1134 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1135 ConvergenceRegionInfo &RegionInfo =
1136 getAnalysis<SPIRVConvergenceRegionAnalysisWrapperPass>()
1137 .getRegionInfo();
1138 return SPIRVStructurizerImpl(LI, RegionInfo).run(F);
1139 }
1140
1141 void getAnalysisUsage(AnalysisUsage &AU) const override {
1142 AU.addRequired<LoopInfoWrapperPass>();
1143 AU.addRequired<SPIRVConvergenceRegionAnalysisWrapperPass>();
1144
1145 AU.addPreserved<SPIRVConvergenceRegionAnalysisWrapperPass>();
1146 FunctionPass::getAnalysisUsage(AU);
1147 }
1148};
1149} // anonymous namespace
1150
1151char SPIRVStructurizer::ID = 0;
1152
1153INITIALIZE_PASS_BEGIN(SPIRVStructurizer, "spirv-structurizer",
1154 "structurize SPIRV", false, false)
1155INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1158
1159INITIALIZE_PASS_END(SPIRVStructurizer, "spirv-structurizer",
1160 "structurize SPIRV", false, false)
1161
1163 return new SPIRVStructurizer();
1164}
1165
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define op(i)
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool splitCriticalEdges(CallBrInst *CBR, DominatorTree *DT)
#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 INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
R600 Clause Merge
static BasicBlock * getDesignatedMergeBlock(Instruction *I)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static std::vector< Instruction * > getMergeInstructions(BasicBlock &BB)
SmallPtrSet< BasicBlock *, 0 > BlockSet
static BasicBlock * getDesignatedContinueBlock(Instruction *I)
static const ConvergenceRegion * getRegionForHeader(const ConvergenceRegion *Node, BasicBlock *BB)
static bool hasLoopMergeInstruction(BasicBlock &BB)
static SmallPtrSet< BasicBlock *, 2 > getContinueBlocks(Function &F)
static SmallPtrSet< BasicBlock *, 2 > getMergeBlocks(Function &F)
static SmallPtrSet< BasicBlock *, 2 > getHeaderBlocks(Function &F)
static bool isDefinedAsSelectionMergeBy(BasicBlock &Header, BasicBlock &Merge)
static void replaceBranchTargets(BasicBlock *BB, BasicBlock *OldTarget, BasicBlock *NewTarget)
static bool isMergeInstruction(Instruction *I)
static BasicBlock * getExitFor(const ConvergenceRegion *CR)
static void replaceIfBranchTargets(BasicBlock *BB, BasicBlock *OldTarget, BasicBlock *NewTarget)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
size_t size() const
Definition BasicBlock.h:467
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
The address of a basic block.
Definition Constants.h:1088
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things.
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
unsigned size() const
Definition DenseMap.h:172
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:219
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:175
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2893
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
A wrapper class for inspecting calls to intrinsic functions.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:587
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:612
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1432
bool compare(const BasicBlock *LHS, const BasicBlock *RHS) const
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Result run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(Function &M, FunctionAnalysisManager &AM)
size_type size() const
Definition SmallPtrSet.h:99
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.
iterator begin() const
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
BasicBlock * getSuccessor(unsigned i=0) const
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
self_iterator getIterator()
Definition ilist_node.h:123
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PostDomTreeBase< BasicBlock > BBPostDomTree
Definition Dominators.h:56
DomTreeBase< BasicBlock > BBDomTree
Definition Dominators.h:55
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
DXILDebugInfoMap run(Module &M)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
FunctionPass * createSPIRVStructurizerPass()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
bool sortBlocks(Function &F)
auto pred_size(const MachineBasicBlock *BB)
AllocaInst * createVariable(Function &F, Type *Type)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
SmallVector< unsigned, 1 > getSpirvLoopControlOperandsFromLoopMetadata(MDNode *LoopMD)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
auto succ_size(const MachineBasicBlock *BB)
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
@ Continue
Definition DWP.h:26
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.