1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
|
// slang-ir-eliminate-multilevel-break.cpp
#include "slang-ir-eliminate-multilevel-break.h"
#include "slang-ir-clone.h"
#include "slang-ir-dominators.h"
#include "slang-ir-eliminate-phis.h"
#include "slang-ir-insts.h"
#include "slang-ir-loop-unroll.h"
#include "slang-ir-util.h"
#include "slang-ir.h"
namespace Slang
{
bool isUnreachableRootBlock(IRBlock* block)
{
return block->getPredecessors().getCount() == 0;
}
struct EliminateMultiLevelBreakContext
{
IRModule* irModule;
struct BreakableRegionInfo : RefObject
{
BreakableRegionInfo* parent = nullptr;
int level = 0;
IRInst* headerInst;
List<IRBlock*> blocks;
HashSet<IRBlock*> blockSet;
List<RefPtr<BreakableRegionInfo>> childRegions;
// Track exit blocks for this region (break block and continue block for loops)
List<IRBlock*> exitBlocks;
IRBlock* getBreakBlock()
{
switch (headerInst->getOp())
{
case kIROp_Loop:
return as<IRLoop>(headerInst)->getBreakBlock();
case kIROp_Switch:
return as<IRSwitch>(headerInst)->getBreakLabel();
default:
SLANG_UNREACHABLE("Unknown breakable inst");
}
}
IRBlock* getContinueBlock()
{
switch (headerInst->getOp())
{
case kIROp_Loop:
return as<IRLoop>(headerInst)->getContinueBlock();
case kIROp_Switch:
return nullptr; // Switches don't have continue blocks
default:
SLANG_UNREACHABLE("Unknown breakable inst");
}
}
void populateExitBlocks()
{
exitBlocks.clear();
exitBlocks.add(getBreakBlock());
// If this is a loop, add any non-trivial continue block to the exit blocks
if (auto loop = as<IRLoop>(headerInst))
if (auto continueBlock = getContinueBlock())
if (continueBlock != loop->getTargetBlock())
exitBlocks.add(continueBlock);
}
void replaceBreakBlock(IRBuilder* builder, IRBlock* block)
{
switch (headerInst->getOp())
{
case kIROp_Loop:
builder->replaceOperand(&(as<IRLoop>(headerInst)->breakBlock), block);
break;
case kIROp_Switch:
builder->replaceOperand(&(as<IRSwitch>(headerInst)->breakLabel), block);
break;
default:
SLANG_UNREACHABLE("Unknown breakable inst");
}
}
template<typename Func>
void forEach(const Func& f)
{
f(this);
for (auto child : childRegions)
child->forEach(f);
}
};
struct MultiLevelBranchInfo
{
IRUnconditionalBranch* branchInst;
BreakableRegionInfo* currentRegion;
BreakableRegionInfo* branchTargetRegion;
};
struct FuncContext
{
List<RefPtr<BreakableRegionInfo>> regions;
HashSet<IRBlock*> exitBlocks;
Dictionary<IRBlock*, BreakableRegionInfo*> mapExitBlockToRegion;
Dictionary<IRBlock*, BreakableRegionInfo*> mapBlockToRegion;
HashSet<IRBlock*> processedBlocks;
List<MultiLevelBranchInfo> multiLevelBranches;
// Track how many multi-level branches target each exit block
Dictionary<IRBlock*, Count> exitBlockMultiLevelBranchCount;
void collectBreakableRegionBlocks(BreakableRegionInfo& info)
{
// Push all exit blocks to a stack so we can easily check if a block is an exit block in
// its parent regions.
for (auto exitBlock : info.exitBlocks)
exitBlocks.add(exitBlock);
auto successors = as<IRBlock>(info.headerInst->getParent())->getSuccessors();
for (auto successor : successors)
{
if (exitBlocks.contains(successor))
continue;
if (info.blockSet.add(successor))
info.blocks.add(successor);
}
for (Index i = 0; i < info.blocks.getCount(); i++)
{
auto block = info.blocks[i];
if (!processedBlocks.add(block))
continue;
switch (block->getTerminator()->getOp())
{
case kIROp_Loop:
case kIROp_Switch:
{
// Both region and switch insts mark the start a breakable region.
RefPtr<BreakableRegionInfo> childRegion = new BreakableRegionInfo();
childRegion->headerInst = block->getTerminator();
childRegion->parent = &info;
childRegion->level = info.level + 1;
childRegion->populateExitBlocks();
collectBreakableRegionBlocks(*childRegion);
info.childRegions.add(childRegion);
block = childRegion->getBreakBlock();
if (!isUnreachableRootBlock(block) && info.blockSet.add(block))
{
info.blocks.add(block);
}
continue;
}
default:
break;
}
for (auto succ : block->getSuccessors())
{
if (!exitBlocks.contains(succ))
{
if (info.blockSet.add(succ))
info.blocks.add(succ);
}
}
}
// Pop the exit blocks.
for (auto exitBlock : info.exitBlocks)
exitBlocks.remove(exitBlock);
}
void gatherInfo(IRGlobalValueWithCode* func)
{
for (auto block : func->getBlocks())
{
if (processedBlocks.contains(block))
continue;
auto terminator = block->getTerminator();
switch (terminator->getOp())
{
case kIROp_Loop:
case kIROp_Switch:
{
RefPtr<BreakableRegionInfo> regionInfo = new BreakableRegionInfo();
regionInfo->headerInst = terminator;
regionInfo->populateExitBlocks();
collectBreakableRegionBlocks(*regionInfo);
regions.add(regionInfo);
}
break;
default:
break;
}
}
for (auto& l : regions)
{
l->forEach(
[&](BreakableRegionInfo* region)
{
for (auto exitBlock : region->exitBlocks)
if (!isUnreachableRootBlock(exitBlock))
mapExitBlockToRegion.add(exitBlock, region);
for (auto block : region->blocks)
mapBlockToRegion.add(block, region);
});
}
// Initialize exit block multi-level branch counts
for (auto& l : regions)
{
l->forEach(
[&](BreakableRegionInfo* region)
{
for (auto exitBlock : region->exitBlocks)
{
if (!isUnreachableRootBlock(exitBlock))
exitBlockMultiLevelBranchCount[exitBlock] = 0;
}
});
}
for (auto block : func->getBlocks())
{
auto terminator = block->getTerminator();
if (auto branch = as<IRUnconditionalBranch>(terminator))
{
if (as<IRLoop>(terminator))
continue;
BreakableRegionInfo* targetRegion = nullptr;
BreakableRegionInfo* currentRegion = nullptr;
// Check if the target is an exit block of any region
if (!mapExitBlockToRegion.tryGetValue(branch->getTargetBlock(), targetRegion))
continue;
if (mapBlockToRegion.tryGetValue(block, currentRegion))
{
if (currentRegion != targetRegion)
{
MultiLevelBranchInfo branchInfo;
branchInfo.branchInst = branch;
branchInfo.branchTargetRegion = targetRegion;
branchInfo.currentRegion = currentRegion;
multiLevelBranches.add(branchInfo);
// Increment the count for this exit block
exitBlockMultiLevelBranchCount[branch->getTargetBlock()]++;
}
}
}
}
}
ShortList<IRBlock*, 2> getMultiLevelExitBlocks(BreakableRegionInfo* region)
{
ShortList<IRBlock*, 2> result;
for (auto exitBlock : region->exitBlocks)
{
Count branchCount = 0;
if (exitBlockMultiLevelBranchCount.tryGetValue(exitBlock, branchCount) &&
branchCount > 0)
{
result.add(exitBlock);
}
}
return result;
}
};
void insertBlockBetween(IRBlock* block, IRBlock* successor)
{
IRBuilder builder(block->getModule());
List<IRUse*> relevantUses;
for (auto use = successor->firstUse; use; use = use->nextUse)
{
if (auto terminator = as<IRTerminatorInst>(use->getUser()))
{
if (as<IRBlock>(terminator->getParent()) == block)
{
// Don't double count instructions like
// ifElse(cond, true, after, after)
if (const auto ifElse = as<IRIfElse>(terminator))
{
if (&ifElse->afterBlock == use)
continue;
}
relevantUses.add(use);
}
}
}
SLANG_RELEASE_ASSERT(relevantUses.getCount() == 1);
builder.insertBlockAlongEdge(block->getModule(), IREdge(relevantUses[0]));
}
bool normalizeBranchesIntoBreakBlocks(IRGlobalValueWithCode* func)
{
bool changed = false;
List<IRBlock*> workList;
for (auto block : func->getBlocks())
workList.add(block);
for (auto block : workList)
{
if (auto loop = as<IRLoop>(block->getTerminator()))
{
auto breakBlock = loop->getBreakBlock();
for (auto predecessor : breakBlock->getPredecessors())
{
if (!as<IRUnconditionalBranch>(predecessor->getTerminator()))
{
insertBlockBetween(predecessor, breakBlock);
changed = true;
}
}
}
}
return changed;
}
void duplicateUnreachableBreakBlocks(FuncContext* context)
{
Dictionary<IRBlock*, BreakableRegionInfo*> mapBreakBlocksToRegion;
// If we already have a region mapped for a break block, and the break block
// is unreachable, create a new unreachable block and map it.
//
for (auto& l : context->regions)
{
l->forEach(
[&](BreakableRegionInfo* region)
{
if (isUnreachableRootBlock(region->getBreakBlock()))
{
if (mapBreakBlocksToRegion.containsKey(region->getBreakBlock()))
{
if (mapBreakBlocksToRegion[region->getBreakBlock()] != region)
{
// We have a break block that is unreachable, and we have already
// mapped it to a region, and that region is not the current region.
//
// We need to create a new unreachable block, and map it to the
// current region.
//
IRBuilder builder(irModule);
builder.setInsertInto(region->getBreakBlock()->getParent());
auto newBreakBlock = builder.createBlock();
newBreakBlock->insertAfter(region->getBreakBlock());
builder.setInsertInto(newBreakBlock);
builder.emitUnreachable();
mapBreakBlocksToRegion.add(newBreakBlock, region);
region->replaceBreakBlock(&builder, newBreakBlock);
return;
}
}
else
mapBreakBlocksToRegion.add(region->getBreakBlock(), region);
}
else
mapBreakBlocksToRegion.add(region->getBreakBlock(), region);
});
}
}
void processFunc(IRGlobalValueWithCode* func)
{
normalizeBranchesIntoBreakBlocks(func);
// If func does not have any multi-level breaks, return.
{
FuncContext funcInfo;
funcInfo.gatherInfo(func);
if (funcInfo.multiLevelBranches.getCount() == 0)
return;
// Check if each region has a single exit block with multi-level branches
// and if it is the break block. If not, eliminate continue blocks first.
bool needsContinueElimination = false;
for (auto& region : funcInfo.regions)
region->forEach(
[&](BreakableRegionInfo* region)
{
// Ensure that each region has a unique exit block with multi-level branches
ShortList<IRBlock*, 2> multiLevelExitBlocks =
funcInfo.getMultiLevelExitBlocks(region);
if (multiLevelExitBlocks.getCount() == 0)
return;
if (multiLevelExitBlocks.getCount() == 1 &&
multiLevelExitBlocks[0] == region->getBreakBlock())
return;
needsContinueElimination = true;
});
if (needsContinueElimination)
eliminateContinueBlocksInFunc(irModule, func);
}
// To make things easy, eliminate Phis before perform transformations.
eliminatePhisInFunc(
LivenessMode::Disabled,
irModule,
func,
PhiEliminationOptions::getFast());
// Before modifying the cfg, we gather all required info from the existing cfg.
FuncContext funcInfo;
funcInfo.gatherInfo(func);
if (funcInfo.multiLevelBranches.getCount() == 0)
return;
// Verify that the only multi-level branches we have to handle are into break blocks.
for (auto& region : funcInfo.regions)
region->forEach(
[&](BreakableRegionInfo* region)
{
// Ensure that each region has a unique exit block with multi-level branches
ShortList<IRBlock*, 2> multiLevelExitBlocks =
funcInfo.getMultiLevelExitBlocks(region);
if (multiLevelExitBlocks.getCount() == 0)
return;
if (multiLevelExitBlocks.getCount() == 1 &&
multiLevelExitBlocks[0] == region->getBreakBlock())
return;
SLANG_UNEXPECTED(
"Multi-level break elimination failed: unique exit block is not the break "
"block");
});
// Duplicate unreachable break blocks so that each break block is only mapped to a single
duplicateUnreachableBreakBlocks(&funcInfo);
IRBuilder builder(irModule);
builder.setInsertInto(func);
OrderedHashSet<BreakableRegionInfo*> skippedOverRegions;
auto unreachableBlock = builder.emitBlock();
builder.setInsertInto(unreachableBlock);
builder.emitUnreachable();
builder.setInsertInto(func);
// Rewrite multi-level branches with single level "break" + target-level argument.
for (auto branchInfo : funcInfo.multiLevelBranches)
{
auto region = branchInfo.currentRegion;
while (region)
{
skippedOverRegions.add(region);
region = region->parent;
if (region == branchInfo.branchTargetRegion)
break;
}
builder.setInsertBefore(branchInfo.branchInst);
auto targetLevelInst =
builder.getIntValue(builder.getIntType(), branchInfo.branchTargetRegion->level);
builder.emitBranch(branchInfo.currentRegion->getBreakBlock(), 1, &targetLevelInst);
branchInfo.branchInst->removeAndDeallocate();
}
// Rewrite skipped-over break blocks to accept a target level argument.
builder.setInsertInto(func);
OrderedDictionary<IRBlock*, int> mapNewBreakBlockToRegionLevel;
for (auto skippedRegion : skippedOverRegions)
{
auto breakBlock = skippedRegion->getBreakBlock();
// The existing break block cannot have parameters. We assume that PHI-elimination is
// run before this pass.
SLANG_RELEASE_ASSERT(breakBlock->getFirstParam() == nullptr);
// The new CFG structure will be: newBreakBlock --> newBreakBodyBlock { IfElse
// (-->oldBreakBlock, -->outerBreakBlock) } `newBreakBlock` defines the `IRParam` for
// the break target, then immediately jumps to `newBreakBodyBlock` for the actual
// branch. We need this separation to avoid introducing critical edge to the CFG (blocks
// cannot have more than 1 predecessors and more than 1 successors at the same time).
auto jumpToOuterBlock = builder.createBlock();
auto newBreakBlock = builder.createBlock();
newBreakBlock->insertBefore(breakBlock);
jumpToOuterBlock->insertAfter(newBreakBlock);
mapNewBreakBlockToRegionLevel[newBreakBlock] = skippedRegion->level;
breakBlock->replaceUsesWith(newBreakBlock);
builder.setInsertInto(newBreakBlock);
auto targetLevelParam = builder.emitParam(builder.getIntType());
if (as<IRUnreachable>(breakBlock->getTerminator()))
{
builder.setInsertInto(newBreakBlock);
builder.emitBranch(jumpToOuterBlock);
}
else
{
auto newBreakBodyBlock = builder.createBlock();
newBreakBodyBlock->insertAfter(breakBlock);
builder.emitBranch(newBreakBodyBlock);
builder.setInsertInto(newBreakBodyBlock);
auto levelNeq = builder.emitNeq(
targetLevelParam,
builder.getIntValue(builder.getIntType(), skippedRegion->level));
builder.emitIfElse(levelNeq, jumpToOuterBlock, breakBlock, breakBlock);
}
builder.setInsertInto(jumpToOuterBlock);
if (skippedOverRegions.contains(skippedRegion->parent))
{
builder.emitBranch(
skippedRegion->parent->getBreakBlock(),
1,
(IRInst**)&targetLevelParam);
}
else
{
builder.emitBranch(skippedRegion->parent->getBreakBlock());
}
}
// Once we have rewritten regions' break blocks with additional targetLevel parameter, all
// original branches into that block without a parameter will now need to provide a default
// value equal to the level of its corresponding region.
for (auto [breakBlock, level] : mapNewBreakBlockToRegionLevel)
{
IRInst* levelInst = nullptr;
List<IRUse*> uses;
for (auto use = breakBlock->firstUse; use; use = use->nextUse)
{
uses.add(use);
}
for (auto use : uses)
{
auto user = use->getUser();
switch (user->getOp())
{
case kIROp_ConditionalBranch:
case kIROp_IfElse:
case kIROp_Switch:
// For complex branches, insert an intermediate block so we can specify the
// target index argument.
{
if (user->getOp() == kIROp_Switch &&
&(as<IRSwitch>(user)->breakLabel) == use)
{
// If this is the "breakLabel" operand of the original switch inst,
// don't do anything since it is not an actual branch.
continue;
}
builder.setInsertInto(func);
auto tmpBlock = builder.createBlock();
tmpBlock->insertAfter(user->getParent());
builder.setInsertInto(tmpBlock);
if (!levelInst)
levelInst = builder.getIntValue(builder.getIntType(), level);
builder.emitBranch(breakBlock, 1, &levelInst);
use->set(tmpBlock);
}
break;
case kIROp_Loop:
// Ignore.
continue;
case kIROp_UnconditionalBranch:
{
auto originalBranch = as<IRUnconditionalBranch>(user);
if (originalBranch->getOperandCount() == 1)
{
builder.setInsertBefore(originalBranch);
if (!levelInst)
levelInst = builder.getIntValue(builder.getIntType(), level);
builder.emitBranch(breakBlock, 1, &levelInst);
originalBranch->removeAndDeallocate();
}
}
break;
}
}
}
legalizeDefUse(func);
}
};
void eliminateMultiLevelBreak(IRModule* irModule)
{
EliminateMultiLevelBreakContext context;
context.irModule = irModule;
for (auto globalInst : irModule->getGlobalInsts())
{
if (auto codeInst = as<IRGlobalValueWithCode>(globalInst))
{
context.processFunc(codeInst);
}
}
}
void eliminateMultiLevelBreakForFunc(IRModule* irModule, IRGlobalValueWithCode* func)
{
EliminateMultiLevelBreakContext context;
context.irModule = irModule;
context.processFunc(func);
}
} // namespace Slang
|