summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-ir-legalize-composite-select.cpp
blob: cdd37efa305d23b5c1f7700a57e676bc01d15187 (plain)
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
#include "slang-ir-legalize-composite-select.h"

#include "slang-ir-clone.h"
#include "slang-ir-insts.h"
#include "slang-ir-legalize-varying-params.h"
#include "slang-ir-specialize-address-space.h"
#include "slang-ir-util.h"
#include "slang-ir.h"

namespace Slang
{

void legalizeCompositeSelect(IRBuilder& builder, IRSelect* selectInst)
{
    SLANG_ASSERT(selectInst);

    auto resultType = selectInst->getFullType();
    auto trueResult = selectInst->getTrueResult();
    auto falseResult = selectInst->getFalseResult();

    IRBlock* trueBlock;
    IRBlock* falseBlock;
    IRBlock* afterBlock;
    builder.emitIfElseWithBlocks(selectInst->getCondition(), trueBlock, falseBlock, afterBlock);

    // Generate if-select-true and else-select-false clause
    builder.setInsertInto(trueBlock);
    builder.emitBranch(afterBlock, 1, &trueResult);

    builder.setInsertInto(falseBlock);
    builder.emitBranch(afterBlock, 1, &falseResult);

    // Move everything after the OpSelect into the "after" block
    List<IRInst*> instsToMove;
    instsToMove.reserve(15);
    IRInst* nextInst = selectInst;
    while (nextInst)
    {
        instsToMove.add(nextInst);
        nextInst = nextInst->getNextInst();
    }
    for (auto i : instsToMove)
        afterBlock->insertAtEnd(i);

    // Merge result of branches into param
    builder.setInsertInto(afterBlock);
    auto param = builder.emitParam(resultType);
    selectInst->replaceUsesWith(param);

    // Clean up
    selectInst->removeAndDeallocate();
}

void legalizeNonVectorCompositeSelect(IRModule* module)
{
    IRBuilder builder(module);
    for (auto globalInst : module->getModuleInst()->getChildren())
    {
        auto func = as<IRFunc>(globalInst);
        if (!func)
            continue;

        for (auto block : func->getBlocks())
        {
            for (auto inst = block->getFirstInst(); inst; inst = inst->getNextInst())
            {
                if (auto select = as<IRSelect>(inst))
                {
                    // Replace OpSelect with if/else branch (same process as glslang)
                    bool requiresLegalization = !as<IRBasicType>(select->getFullType()) &&
                                                !as<IRVectorType>(select->getFullType()) &&
                                                !as<IRMatrixType>(select->getFullType());

                    if (requiresLegalization)
                        legalizeCompositeSelect(builder, select);
                }
            }
        }
    }
}

} // namespace Slang