summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-ir-lower-l-value-cast.cpp
blob: 058589862ff58ea268513a1212a67f20046211df (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
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
#include "slang-ir-lower-l-value-cast.h"

#include "slang-ir-clone.h"
#include "slang-ir-insts.h"
#include "slang-ir-util.h"
#include "slang-ir.h"

namespace Slang
{

struct LValueCastLoweringContext
{
    void _addToWorkList(IRInst* inst)
    {
        if (!findOuterGeneric(inst) && !m_workList.contains(inst))
        {
            m_workList.add(inst);
        }
    }

    void _processInst(IRInst* inst)
    {
        switch (inst->getOp())
        {
        case kIROp_InOutImplicitCast:
        case kIROp_OutImplicitCast:
            _processLValueCast(inst);
            break;
        default:
            break;
        }
    }

    void processModule()
    {
        _addToWorkList(m_module->getModuleInst());

        while (m_workList.getCount() != 0)
        {
            IRInst* inst = m_workList.getLast();
            m_workList.removeLast();

            _processInst(inst);

            for (auto child = inst->getLastChild(); child; child = child->getPrevInst())
            {
                _addToWorkList(child);
            }
        }
    }

    /// True if the conversion from a to b, can be achieved
    /// via a reinterpret cast/bitcast
    /// Only some targets can allow such conversions
    bool _canReinterpretCast(IRType* a, IRType* b)
    {
        auto ptrA = as<IRPtrTypeBase>(a);
        auto ptrB = as<IRPtrTypeBase>(b);

        // They must both be pointers...
        SLANG_ASSERT(ptrA && ptrB);

        a = ptrA->getValueType();
        b = ptrB->getValueType();

        if (a->m_op == b->m_op)
        {
            if (auto matA = as<IRMatrixType>(a))
            {
                auto matB = static_cast<IRMatrixType*>(b);

                if (getIntVal(matA->getColumnCount()) != getIntVal(matB->getColumnCount()))
                {
                    return false;
                }

                a = matA->getElementType();
                b = matB->getElementType();
            }
            else if (auto vecA = as<IRVectorType>(a))
            {
                auto vecB = static_cast<IRVectorType*>(b);

                if (getIntVal(vecA->getElementCount()) != getIntVal(vecB->getElementCount()))
                {
                    return false;
                }

                a = vecA->getElementType();
                b = vecB->getElementType();
            }
        }

        auto basicA = as<IRBasicType>(a);
        auto basicB = as<IRBasicType>(b);

        if (basicA && basicB)
        {
            auto baseA = basicA->getBaseType();
            auto baseB = basicB->getBaseType();

            const auto& infoA = BaseTypeInfo::getInfo(baseA);
            const auto& infoB = BaseTypeInfo::getInfo(baseB);

            // We allow reinterpret case for int type conversions of the same bit size for now
            if (infoA.sizeInBytes == infoB.sizeInBytes &&
                (infoA.flags & infoB.flags & BaseTypeInfo::Flag::Integer))
            {
                return true;
            }
        }

        return false;
    }

    /// True if for HLSL the cast can be removed entirely
    bool _canRemoveCastForHLSL(IRType* a, IRType* b)
    {
        // Currently _canReinterpret is exactly the same class of types that we can just ignore the
        // cast totally for HLSL If _canReinterpretCast changes, this will need to be updated
        return _canReinterpretCast(a, b);
    }

    void _processLValueCast(IRInst* castInst)
    {
        auto castOperand = castInst->getOperand(0);
        auto fromType = castOperand->getDataType();
        auto toType = castInst->getDataType();

        switch (m_intermediateSourceLanguage)
        {
        case SourceLanguage::HLSL:
            {
                // If the conversion can just be ignored for HLSL, just remove it
                if (_canRemoveCastForHLSL(fromType, toType))
                {
                    castInst->replaceUsesWith(castOperand);
                    castInst->removeAndDeallocate();
                    return;
                }
                break;
            }
        case SourceLanguage::C:
        case SourceLanguage::CPP:
        case SourceLanguage::CUDA:
            {
                // For languages with pointers, out parameter differences can *sometimes* just be
                // sidestepped with a reinterpret cast.
                if (_canReinterpretCast(fromType, toType))
                {
                    return;
                }
                break;
            }
        default:
            break;
        }

        // If we can't use the other mechanisms we are going to do a conversion
        // via a cast into a temporary of the approprite time before the useSite,
        // then immediately after converting back into the original location.
        //
        // With a special case for uses which are just out - where we don't need to
        // convert in.

        // Okay we are going to replace the implicit casts with temporaries around call sites/uses.
        List<IRUse*> useSites;
        for (auto use = castInst->firstUse; use; use = use->nextUse)
        {
            useSites.add(use);
        }

        // If there is a name hint on the source, we'll copy it over to the temporaries
        auto nameHintDecoration = castOperand->findDecoration<IRNameHintDecoration>();

        IRBuilder builder(m_module);

        auto toPtrType = as<IRPtrTypeBase>(toType);
        auto fromPtrType = as<IRPtrTypeBase>(fromType);

        if (!toPtrType || !fromPtrType)
        {
            // If either type is not a pointer type, we cannot process this L-value cast
            return;
        }

        IRType* toValueType = toPtrType->getValueType();
        IRType* fromValueType = fromPtrType->getValueType();

        for (auto useSite : useSites)
        {
            auto user = useSite->getUser();
            builder.setInsertBefore(user);
            auto tmpVar = builder.emitVar(toValueType);

            if (nameHintDecoration)
            {
                cloneDecoration(nameHintDecoration, tmpVar);
            }

            // If it's inout we convert via cast whats in the castOperand
            if (castInst->getOp() == kIROp_InOutImplicitCast && user->getOp() != kIROp_Store)
            {
                builder.emitStore(
                    tmpVar,
                    builder.emitCast(toValueType, builder.emitLoad(castOperand)));
            }

            // Convert the temporary back to the original location
            builder.setInsertAfter(user);
            builder.emitStore(
                castOperand,
                builder.emitCast(fromValueType, builder.emitLoad(tmpVar)));

            // Go through all of the operands of the use inst relacing, with the temporary
            builder.replaceOperand(useSite, tmpVar);
        }

        // When we are done we can destroy the inst
        castInst->removeAndDeallocate();
    }

    LValueCastLoweringContext(TargetProgram* target, IRModule* module)
        : m_targetProgram(target), m_module(module)
    {
        m_intermediateSourceLanguage = getIntermediateSourceLanguageForTarget(target);
    }

    // The intermediate source language used to produce code for the target.
    // If no intermediate source language is used will be SourceLanguage::Unknown.
    SourceLanguage m_intermediateSourceLanguage = SourceLanguage::Unknown;
    TargetProgram* m_targetProgram;
    IRModule* m_module;
    OrderedHashSet<IRInst*> m_workList;
};

void lowerLValueCast(TargetProgram* target, IRModule* module)
{
    LValueCastLoweringContext context(target, module);
    context.processModule();
}

} // namespace Slang