Coverage Report

Created: 2026-10-28 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/shaderc/third_party/spirv-tools/source/opt/fold.cpp
Line
Count
Source
1
// Copyright (c) 2017 Google Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include "source/opt/fold.h"
16
17
#include <cassert>
18
#include <cstdint>
19
#include <vector>
20
21
#include "source/opt/const_folding_rules.h"
22
#include "source/opt/def_use_manager.h"
23
#include "source/opt/folding_rules.h"
24
#include "source/opt/ir_context.h"
25
26
namespace spvtools {
27
namespace opt {
28
namespace {
29
30
#ifndef INT32_MIN
31
#define INT32_MIN (-2147483648)
32
#endif
33
34
#ifndef INT32_MAX
35
#define INT32_MAX 2147483647
36
#endif
37
38
#ifndef UINT32_MAX
39
#define UINT32_MAX 0xffffffff /* 4294967295U */
40
#endif
41
42
}  // namespace
43
44
uint32_t InstructionFolder::UnaryOperate(spv::Op opcode,
45
4
                                         uint32_t operand) const {
46
4
  switch (opcode) {
47
    // Arthimetics
48
0
    case spv::Op::OpSNegate: {
49
0
      int32_t s_operand = static_cast<int32_t>(operand);
50
0
      if (s_operand == std::numeric_limits<int32_t>::min()) {
51
0
        return s_operand;
52
0
      }
53
0
      return static_cast<uint32_t>(-s_operand);
54
0
    }
55
4
    case spv::Op::OpNot:
56
4
      return ~operand;
57
0
    case spv::Op::OpLogicalNot:
58
0
      return !static_cast<bool>(operand);
59
0
    case spv::Op::OpUConvert:
60
0
      return operand;
61
0
    case spv::Op::OpSConvert:
62
0
      return operand;
63
0
    default:
64
0
      assert(false &&
65
0
             "Unsupported unary operation for OpSpecConstantOp instruction");
66
0
      return 0u;
67
4
  }
68
4
}
69
70
uint32_t InstructionFolder::BinaryOperate(spv::Op opcode, uint32_t a,
71
864
                                          uint32_t b) const {
72
864
  switch (opcode) {
73
    // Shifting
74
0
    case spv::Op::OpShiftRightLogical:
75
0
      if (b >= 32) {
76
        // This is undefined behaviour when |b| > 32.  Choose 0 for consistency.
77
        // When |b| == 32, doing the shift in C++ in undefined, but the result
78
        // will be 0, so just return that value.
79
0
        return 0;
80
0
      }
81
0
      return a >> b;
82
0
    case spv::Op::OpShiftRightArithmetic:
83
0
      if (b > 32) {
84
        // This is undefined behaviour.  Choose 0 for consistency.
85
0
        return 0;
86
0
      }
87
0
      if (b == 32) {
88
        // Doing the shift in C++ is undefined, but the result is defined in the
89
        // spir-v spec.  Find that value another way.
90
0
        if (static_cast<int32_t>(a) >= 0) {
91
0
          return 0;
92
0
        } else {
93
0
          return static_cast<uint32_t>(-1);
94
0
        }
95
0
      }
96
0
      return (static_cast<int32_t>(a)) >> b;
97
0
    case spv::Op::OpShiftLeftLogical:
98
0
      if (b >= 32) {
99
        // This is undefined behaviour when |b| > 32.  Choose 0 for consistency.
100
        // When |b| == 32, doing the shift in C++ in undefined, but the result
101
        // will be 0, so just return that value.
102
0
        return 0;
103
0
      }
104
0
      return a << b;
105
106
    // Bitwise operations
107
0
    case spv::Op::OpBitwiseOr:
108
0
      return a | b;
109
0
    case spv::Op::OpBitwiseAnd:
110
0
      return a & b;
111
0
    case spv::Op::OpBitwiseXor:
112
0
      return a ^ b;
113
114
    // Logical
115
0
    case spv::Op::OpLogicalEqual:
116
0
      return (static_cast<bool>(a)) == (static_cast<bool>(b));
117
0
    case spv::Op::OpLogicalNotEqual:
118
0
      return (static_cast<bool>(a)) != (static_cast<bool>(b));
119
0
    case spv::Op::OpLogicalOr:
120
0
      return (static_cast<bool>(a)) || (static_cast<bool>(b));
121
0
    case spv::Op::OpLogicalAnd:
122
0
      return (static_cast<bool>(a)) && (static_cast<bool>(b));
123
124
    // Comparison
125
0
    case spv::Op::OpIEqual:
126
0
      return a == b;
127
0
    case spv::Op::OpINotEqual:
128
0
      return a != b;
129
0
    case spv::Op::OpULessThan:
130
0
      return a < b;
131
400
    case spv::Op::OpSLessThan:
132
400
      return (static_cast<int32_t>(a)) < (static_cast<int32_t>(b));
133
0
    case spv::Op::OpUGreaterThan:
134
0
      return a > b;
135
0
    case spv::Op::OpSGreaterThan:
136
0
      return (static_cast<int32_t>(a)) > (static_cast<int32_t>(b));
137
0
    case spv::Op::OpULessThanEqual:
138
0
      return a <= b;
139
464
    case spv::Op::OpSLessThanEqual:
140
464
      return (static_cast<int32_t>(a)) <= (static_cast<int32_t>(b));
141
0
    case spv::Op::OpUGreaterThanEqual:
142
0
      return a >= b;
143
0
    case spv::Op::OpSGreaterThanEqual:
144
0
      return (static_cast<int32_t>(a)) >= (static_cast<int32_t>(b));
145
0
    default:
146
0
      assert(false &&
147
0
             "Unsupported binary operation for OpSpecConstantOp instruction");
148
0
      return 0u;
149
864
  }
150
864
}
151
152
uint32_t InstructionFolder::TernaryOperate(spv::Op opcode, uint32_t a,
153
0
                                           uint32_t b, uint32_t c) const {
154
0
  switch (opcode) {
155
0
    case spv::Op::OpSelect:
156
0
      return (static_cast<bool>(a)) ? b : c;
157
0
    default:
158
0
      assert(false &&
159
0
             "Unsupported ternary operation for OpSpecConstantOp instruction");
160
0
      return 0u;
161
0
  }
162
0
}
163
164
uint32_t InstructionFolder::OperateWords(
165
868
    spv::Op opcode, const std::vector<uint32_t>& operand_words) const {
166
868
  switch (operand_words.size()) {
167
4
    case 1:
168
4
      return UnaryOperate(opcode, operand_words.front());
169
864
    case 2:
170
864
      return BinaryOperate(opcode, operand_words.front(), operand_words.back());
171
0
    case 3:
172
0
      return TernaryOperate(opcode, operand_words[0], operand_words[1],
173
0
                            operand_words[2]);
174
0
    default:
175
0
      assert(false && "Invalid number of operands");
176
0
      return 0;
177
868
  }
178
868
}
179
180
166k
bool InstructionFolder::FoldInstructionInternal(Instruction* inst) const {
181
166k
  auto identity_map = [](uint32_t id) { return id; };
182
166k
  Instruction* folded_inst = FoldInstructionToConstant(inst, identity_map);
183
166k
  if (folded_inst != nullptr) {
184
112
    inst->SetOpcode(spv::Op::OpCopyObject);
185
112
    inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {folded_inst->result_id()}}});
186
112
    return true;
187
112
  }
188
189
166k
  analysis::ConstantManager* const_manager = context_->get_constant_mgr();
190
166k
  std::vector<const analysis::Constant*> constants =
191
166k
      const_manager->GetOperandConstants(inst);
192
193
166k
  for (const FoldingRule& rule :
194
284k
       GetFoldingRules().GetRulesForInstruction(inst)) {
195
284k
    if (rule(context_, inst, constants)) {
196
4.23k
      return true;
197
4.23k
    }
198
284k
  }
199
162k
  return false;
200
166k
}
201
202
// Returns the result of performing an operation on scalar constant operands.
203
// This function extracts the operand values as 32 bit words and returns the
204
// result in 32 bit word. Scalar constants with longer than 32-bit width are
205
// not accepted in this function.
206
uint32_t InstructionFolder::FoldScalars(
207
    spv::Op opcode,
208
868
    const std::vector<const analysis::Constant*>& operands) const {
209
868
  assert(IsFoldableOpcode(opcode) &&
210
868
         "Unhandled instruction opcode in FoldScalars");
211
868
  std::vector<uint32_t> operand_values_in_raw_words;
212
1.73k
  for (const auto& operand : operands) {
213
1.73k
    if (const analysis::ScalarConstant* scalar = operand->AsScalarConstant()) {
214
1.73k
      const auto& scalar_words = scalar->words();
215
1.73k
      assert(scalar_words.size() == 1 &&
216
1.73k
             "Scalar constants with longer than 32-bit width are not allowed "
217
1.73k
             "in FoldScalars()");
218
1.73k
      operand_values_in_raw_words.push_back(scalar_words.front());
219
1.73k
    } else if (operand->AsNullConstant()) {
220
0
      operand_values_in_raw_words.push_back(0u);
221
0
    } else {
222
0
      assert(false &&
223
0
             "FoldScalars() only accepts ScalarConst or NullConst type of "
224
0
             "constant");
225
0
    }
226
1.73k
  }
227
868
  return OperateWords(opcode, operand_values_in_raw_words);
228
868
}
229
230
bool InstructionFolder::FoldBinaryIntegerOpToConstant(
231
    Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
232
9.58k
    uint32_t* result) const {
233
9.58k
  spv::Op opcode = inst->opcode();
234
9.58k
  analysis::ConstantManager* const_manger = context_->get_constant_mgr();
235
236
9.58k
  uint32_t ids[2];
237
9.58k
  const analysis::IntConstant* constants[2];
238
28.7k
  for (uint32_t i = 0; i < 2; i++) {
239
19.1k
    const Operand* operand = &inst->GetInOperand(i);
240
19.1k
    if (operand->type != SPV_OPERAND_TYPE_ID) {
241
0
      return false;
242
0
    }
243
19.1k
    ids[i] = id_map(operand->words[0]);
244
19.1k
    const analysis::Constant* constant =
245
19.1k
        const_manger->FindDeclaredConstant(ids[i]);
246
19.1k
    constants[i] = (constant != nullptr ? constant->AsIntConstant() : nullptr);
247
19.1k
  }
248
249
9.58k
  switch (opcode) {
250
    // Arthimetics
251
0
    case spv::Op::OpIMul:
252
0
      for (uint32_t i = 0; i < 2; i++) {
253
0
        if (constants[i] != nullptr && constants[i]->IsZero()) {
254
0
          *result = 0;
255
0
          return true;
256
0
        }
257
0
      }
258
0
      break;
259
0
    case spv::Op::OpUDiv:
260
0
    case spv::Op::OpSDiv:
261
0
    case spv::Op::OpSRem:
262
0
    case spv::Op::OpSMod:
263
0
    case spv::Op::OpUMod:
264
      // This changes undefined behaviour (ie divide by 0) into a 0.
265
0
      for (uint32_t i = 0; i < 2; i++) {
266
0
        if (constants[i] != nullptr && constants[i]->IsZero()) {
267
0
          *result = 0;
268
0
          return true;
269
0
        }
270
0
      }
271
0
      break;
272
273
    // Shifting
274
0
    case spv::Op::OpShiftRightLogical:
275
0
    case spv::Op::OpShiftLeftLogical:
276
0
      if (constants[1] != nullptr) {
277
        // When shifting by a value larger than the size of the result, the
278
        // result is undefined.  We are setting the undefined behaviour to a
279
        // result of 0.  If the shift amount is the same as the size of the
280
        // result, then the result is defined, and it 0.
281
0
        uint32_t shift_amount = constants[1]->GetU32BitValue();
282
0
        if (shift_amount >= 32) {
283
0
          *result = 0;
284
0
          return true;
285
0
        }
286
0
      }
287
0
      break;
288
289
    // Bitwise operations
290
0
    case spv::Op::OpBitwiseOr:
291
0
      for (uint32_t i = 0; i < 2; i++) {
292
0
        if (constants[i] != nullptr) {
293
          // TODO: Change the mask against a value based on the bit width of the
294
          // instruction result type.  This way we can handle say 16-bit values
295
          // as well.
296
0
          uint32_t mask = constants[i]->GetU32BitValue();
297
0
          if (mask == 0xFFFFFFFF) {
298
0
            *result = 0xFFFFFFFF;
299
0
            return true;
300
0
          }
301
0
        }
302
0
      }
303
0
      break;
304
0
    case spv::Op::OpBitwiseAnd:
305
0
      for (uint32_t i = 0; i < 2; i++) {
306
0
        if (constants[i] != nullptr) {
307
0
          if (constants[i]->IsZero()) {
308
0
            *result = 0;
309
0
            return true;
310
0
          }
311
0
        }
312
0
      }
313
0
      break;
314
315
    // Comparison
316
0
    case spv::Op::OpULessThan:
317
0
      if (constants[0] != nullptr &&
318
0
          constants[0]->GetU32BitValue() == UINT32_MAX) {
319
0
        *result = false;
320
0
        return true;
321
0
      }
322
0
      if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
323
0
        *result = false;
324
0
        return true;
325
0
      }
326
0
      break;
327
1.57k
    case spv::Op::OpSLessThan:
328
1.57k
      if (constants[0] != nullptr &&
329
0
          constants[0]->GetS32BitValue() == INT32_MAX) {
330
0
        *result = false;
331
0
        return true;
332
0
      }
333
1.57k
      if (constants[1] != nullptr &&
334
1.57k
          constants[1]->GetS32BitValue() == INT32_MIN) {
335
0
        *result = false;
336
0
        return true;
337
0
      }
338
1.57k
      break;
339
1.57k
    case spv::Op::OpUGreaterThan:
340
272
      if (constants[0] != nullptr && constants[0]->IsZero()) {
341
0
        *result = false;
342
0
        return true;
343
0
      }
344
272
      if (constants[1] != nullptr &&
345
272
          constants[1]->GetU32BitValue() == UINT32_MAX) {
346
0
        *result = false;
347
0
        return true;
348
0
      }
349
272
      break;
350
1.98k
    case spv::Op::OpSGreaterThan:
351
1.98k
      if (constants[0] != nullptr &&
352
0
          constants[0]->GetS32BitValue() == INT32_MIN) {
353
0
        *result = false;
354
0
        return true;
355
0
      }
356
1.98k
      if (constants[1] != nullptr &&
357
1.98k
          constants[1]->GetS32BitValue() == INT32_MAX) {
358
0
        *result = false;
359
0
        return true;
360
0
      }
361
1.98k
      break;
362
1.98k
    case spv::Op::OpULessThanEqual:
363
0
      if (constants[0] != nullptr && constants[0]->IsZero()) {
364
0
        *result = true;
365
0
        return true;
366
0
      }
367
0
      if (constants[1] != nullptr &&
368
0
          constants[1]->GetU32BitValue() == UINT32_MAX) {
369
0
        *result = true;
370
0
        return true;
371
0
      }
372
0
      break;
373
1.65k
    case spv::Op::OpSLessThanEqual:
374
1.65k
      if (constants[0] != nullptr &&
375
0
          constants[0]->GetS32BitValue() == INT32_MIN) {
376
0
        *result = true;
377
0
        return true;
378
0
      }
379
1.65k
      if (constants[1] != nullptr &&
380
1.65k
          constants[1]->GetS32BitValue() == INT32_MAX) {
381
0
        *result = true;
382
0
        return true;
383
0
      }
384
1.65k
      break;
385
1.65k
    case spv::Op::OpUGreaterThanEqual:
386
0
      if (constants[0] != nullptr &&
387
0
          constants[0]->GetU32BitValue() == UINT32_MAX) {
388
0
        *result = true;
389
0
        return true;
390
0
      }
391
0
      if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
392
0
        *result = true;
393
0
        return true;
394
0
      }
395
0
      break;
396
0
    case spv::Op::OpSGreaterThanEqual:
397
0
      if (constants[0] != nullptr &&
398
0
          constants[0]->GetS32BitValue() == INT32_MAX) {
399
0
        *result = true;
400
0
        return true;
401
0
      }
402
0
      if (constants[1] != nullptr &&
403
0
          constants[1]->GetS32BitValue() == INT32_MIN) {
404
0
        *result = true;
405
0
        return true;
406
0
      }
407
0
      break;
408
4.08k
    default:
409
4.08k
      break;
410
9.58k
  }
411
9.58k
  return false;
412
9.58k
}
413
414
bool InstructionFolder::FoldBinaryBooleanOpToConstant(
415
    Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
416
9.58k
    uint32_t* result) const {
417
9.58k
  spv::Op opcode = inst->opcode();
418
9.58k
  analysis::ConstantManager* const_manger = context_->get_constant_mgr();
419
420
9.58k
  uint32_t ids[2];
421
9.58k
  const analysis::BoolConstant* constants[2];
422
28.7k
  for (uint32_t i = 0; i < 2; i++) {
423
19.1k
    const Operand* operand = &inst->GetInOperand(i);
424
19.1k
    if (operand->type != SPV_OPERAND_TYPE_ID) {
425
0
      return false;
426
0
    }
427
19.1k
    ids[i] = id_map(operand->words[0]);
428
19.1k
    const analysis::Constant* constant =
429
19.1k
        const_manger->FindDeclaredConstant(ids[i]);
430
19.1k
    constants[i] = (constant != nullptr ? constant->AsBoolConstant() : nullptr);
431
19.1k
  }
432
433
9.58k
  switch (opcode) {
434
    // Logical
435
0
    case spv::Op::OpLogicalOr:
436
0
      for (uint32_t i = 0; i < 2; i++) {
437
0
        if (constants[i] != nullptr) {
438
0
          if (constants[i]->value()) {
439
0
            *result = true;
440
0
            return true;
441
0
          }
442
0
        }
443
0
      }
444
0
      break;
445
0
    case spv::Op::OpLogicalAnd:
446
0
      for (uint32_t i = 0; i < 2; i++) {
447
0
        if (constants[i] != nullptr) {
448
0
          if (!constants[i]->value()) {
449
0
            *result = false;
450
0
            return true;
451
0
          }
452
0
        }
453
0
      }
454
0
      break;
455
456
9.58k
    default:
457
9.58k
      break;
458
9.58k
  }
459
9.58k
  return false;
460
9.58k
}
461
462
bool InstructionFolder::FoldIntegerOpToConstant(
463
    Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
464
9.58k
    uint32_t* result) const {
465
9.58k
  assert(IsFoldableOpcode(inst->opcode()) &&
466
9.58k
         "Unhandled instruction opcode in FoldScalars");
467
9.58k
  switch (inst->NumInOperands()) {
468
9.58k
    case 2:
469
9.58k
      return FoldBinaryIntegerOpToConstant(inst, id_map, result) ||
470
9.58k
             FoldBinaryBooleanOpToConstant(inst, id_map, result);
471
0
    default:
472
0
      return false;
473
9.58k
  }
474
9.58k
}
475
476
std::vector<uint32_t> InstructionFolder::FoldVectors(
477
    spv::Op opcode, uint32_t num_dims,
478
0
    const std::vector<const analysis::Constant*>& operands) const {
479
0
  assert(IsFoldableOpcode(opcode) &&
480
0
         "Unhandled instruction opcode in FoldVectors");
481
0
  std::vector<uint32_t> result;
482
0
  for (uint32_t d = 0; d < num_dims; d++) {
483
0
    std::vector<uint32_t> operand_values_for_one_dimension;
484
0
    for (const auto& operand : operands) {
485
0
      if (const analysis::VectorConstant* vector_operand =
486
0
              operand->AsVectorConstant()) {
487
        // Extract the raw value of the scalar component constants
488
        // in 32-bit words here. The reason of not using FoldScalars() here
489
        // is that we do not create temporary null constants as components
490
        // when the vector operand is a NullConstant because Constant creation
491
        // may need extra checks for the validity and that is not managed in
492
        // here.
493
0
        if (const analysis::ScalarConstant* scalar_component =
494
0
                vector_operand->GetComponents().at(d)->AsScalarConstant()) {
495
0
          const auto& scalar_words = scalar_component->words();
496
0
          assert(
497
0
              scalar_words.size() == 1 &&
498
0
              "Vector components with longer than 32-bit width are not allowed "
499
0
              "in FoldVectors()");
500
0
          operand_values_for_one_dimension.push_back(scalar_words.front());
501
0
        } else if (operand->AsNullConstant()) {
502
0
          operand_values_for_one_dimension.push_back(0u);
503
0
        } else {
504
0
          assert(false &&
505
0
                 "VectorConst should only has ScalarConst or NullConst as "
506
0
                 "components");
507
0
        }
508
0
      } else if (operand->AsNullConstant()) {
509
0
        operand_values_for_one_dimension.push_back(0u);
510
0
      } else {
511
0
        assert(false &&
512
0
               "FoldVectors() only accepts VectorConst or NullConst type of "
513
0
               "constant");
514
0
      }
515
0
    }
516
0
    result.push_back(OperateWords(opcode, operand_values_for_one_dimension));
517
0
  }
518
0
  return result;
519
0
}
520
521
642k
bool InstructionFolder::IsFoldableOpcode(spv::Op opcode) const {
522
  // NOTE: Extend to more opcodes as new cases are handled in the folder
523
  // functions.
524
642k
  switch (opcode) {
525
0
    case spv::Op::OpBitwiseAnd:
526
0
    case spv::Op::OpBitwiseOr:
527
0
    case spv::Op::OpBitwiseXor:
528
12.7k
    case spv::Op::OpIAdd:
529
12.7k
    case spv::Op::OpIEqual:
530
13.0k
    case spv::Op::OpIMul:
531
13.0k
    case spv::Op::OpINotEqual:
532
13.2k
    case spv::Op::OpISub:
533
13.2k
    case spv::Op::OpLogicalAnd:
534
13.2k
    case spv::Op::OpLogicalEqual:
535
13.2k
    case spv::Op::OpLogicalNot:
536
13.2k
    case spv::Op::OpLogicalNotEqual:
537
13.2k
    case spv::Op::OpLogicalOr:
538
13.2k
    case spv::Op::OpNot:
539
13.2k
    case spv::Op::OpSDiv:
540
14.3k
    case spv::Op::OpSelect:
541
18.7k
    case spv::Op::OpSGreaterThan:
542
18.7k
    case spv::Op::OpSGreaterThanEqual:
543
18.7k
    case spv::Op::OpShiftLeftLogical:
544
18.7k
    case spv::Op::OpShiftRightArithmetic:
545
18.7k
    case spv::Op::OpShiftRightLogical:
546
23.5k
    case spv::Op::OpSLessThan:
547
28.6k
    case spv::Op::OpSLessThanEqual:
548
28.6k
    case spv::Op::OpSMod:
549
29.6k
    case spv::Op::OpSNegate:
550
29.6k
    case spv::Op::OpSRem:
551
29.9k
    case spv::Op::OpSConvert:
552
29.9k
    case spv::Op::OpUConvert:
553
29.9k
    case spv::Op::OpUDiv:
554
30.5k
    case spv::Op::OpUGreaterThan:
555
30.5k
    case spv::Op::OpUGreaterThanEqual:
556
30.5k
    case spv::Op::OpULessThan:
557
30.5k
    case spv::Op::OpULessThanEqual:
558
30.5k
    case spv::Op::OpUMod:
559
30.5k
      return true;
560
611k
    default:
561
611k
      return false;
562
642k
  }
563
642k
}
564
565
bool InstructionFolder::IsFoldableConstant(
566
0
    const analysis::Constant* cst) const {
567
  // Currently supported constants are 32-bit values or null constants.
568
0
  if (const analysis::ScalarConstant* scalar = cst->AsScalarConstant())
569
0
    return scalar->words().size() == 1;
570
0
  else
571
0
    return cst->AsNullConstant() != nullptr;
572
0
}
573
574
Instruction* InstructionFolder::FoldInstructionToConstant(
575
193k
    Instruction* inst, std::function<uint32_t(uint32_t)> id_map) const {
576
193k
  analysis::ConstantManager* const_mgr = context_->get_constant_mgr();
577
578
193k
  if (!inst->IsFoldableByFoldScalar() && !inst->IsFoldableByFoldVector() &&
579
181k
      !GetConstantFoldingRules().HasFoldingRule(inst)) {
580
102k
    return nullptr;
581
102k
  }
582
  // Collect the values of the constant parameters.
583
91.4k
  std::vector<const analysis::Constant*> constants;
584
91.4k
  bool missing_constants = false;
585
91.4k
  inst->ForEachInId([&constants, &missing_constants, const_mgr,
586
158k
                     &id_map](uint32_t* op_id) {
587
158k
    uint32_t id = id_map(*op_id);
588
158k
    const analysis::Constant* const_op = const_mgr->FindDeclaredConstant(id);
589
158k
    if (!const_op) {
590
127k
      constants.push_back(nullptr);
591
127k
      missing_constants = true;
592
127k
    } else {
593
30.7k
      constants.push_back(const_op);
594
30.7k
    }
595
158k
  });
596
597
91.4k
  const analysis::Constant* folded_const = nullptr;
598
95.0k
  for (auto rule : GetConstantFoldingRules().GetRulesForInstruction(inst)) {
599
95.0k
    folded_const = rule(context_, inst, constants);
600
95.0k
    if (folded_const == nullptr && inst->context()->id_overflow()) {
601
0
      return nullptr;
602
0
    }
603
95.0k
    if (folded_const != nullptr) {
604
3.34k
      Instruction* const_inst =
605
3.34k
          const_mgr->GetDefiningInstruction(folded_const, inst->type_id());
606
3.34k
      if (const_inst == nullptr) {
607
0
        return nullptr;
608
0
      }
609
3.34k
      assert(const_inst->type_id() == inst->type_id());
610
      // May be a new instruction that needs to be analysed.
611
3.34k
      context_->UpdateDefUse(const_inst);
612
3.34k
      return const_inst;
613
3.34k
    }
614
95.0k
  }
615
616
88.1k
  bool successful = false;
617
618
  // If all parameters are constant, fold the instruction to a constant.
619
88.1k
  if (inst->IsFoldableByFoldScalar()) {
620
10.4k
    uint32_t result_val = 0;
621
622
10.4k
    if (!missing_constants) {
623
868
      result_val = FoldScalars(inst->opcode(), constants);
624
868
      successful = true;
625
868
    }
626
627
10.4k
    if (!successful) {
628
9.58k
      successful = FoldIntegerOpToConstant(inst, id_map, &result_val);
629
9.58k
    }
630
631
10.4k
    if (successful) {
632
868
      const analysis::Constant* result_const =
633
868
          const_mgr->GetConstant(const_mgr->GetType(inst), {result_val});
634
868
      if (!result_const) {
635
0
        return nullptr;
636
0
      }
637
868
      Instruction* folded_inst =
638
868
          const_mgr->GetDefiningInstruction(result_const, inst->type_id());
639
868
      return folded_inst;
640
868
    }
641
77.7k
  } else if (inst->IsFoldableByFoldVector()) {
642
0
    std::vector<uint32_t> result_val;
643
644
0
    if (!missing_constants) {
645
0
      if (Instruction* inst_type =
646
0
              context_->get_def_use_mgr()->GetDef(inst->type_id())) {
647
0
        result_val = FoldVectors(
648
0
            inst->opcode(), inst_type->GetSingleWordInOperand(1), constants);
649
0
        successful = true;
650
0
      }
651
0
    }
652
653
0
    if (successful) {
654
0
      const analysis::Constant* result_const =
655
0
          const_mgr->GetNumericVectorConstantWithWords(
656
0
              const_mgr->GetType(inst)->AsVector(), result_val);
657
0
      if (!result_const) {
658
0
        return nullptr;
659
0
      }
660
0
      Instruction* folded_inst =
661
0
          const_mgr->GetDefiningInstruction(result_const, inst->type_id());
662
0
      return folded_inst;
663
0
    }
664
0
  }
665
666
87.2k
  return nullptr;
667
88.1k
}
668
669
0
bool InstructionFolder::IsFoldableType(Instruction* type_inst) const {
670
0
  return IsFoldableScalarType(type_inst) || IsFoldableVectorType(type_inst);
671
0
}
672
673
82.8k
bool InstructionFolder::IsFoldableScalarType(Instruction* type_inst) const {
674
  // Support 32-bit integers.
675
82.8k
  if (type_inst->opcode() == spv::Op::OpTypeInt) {
676
67.1k
    return type_inst->GetSingleWordInOperand(0) == 32;
677
67.1k
  }
678
  // Support booleans.
679
15.6k
  if (type_inst->opcode() == spv::Op::OpTypeBool) {
680
15.0k
    return true;
681
15.0k
  }
682
  // Nothing else yet.
683
626
  return false;
684
15.6k
}
685
686
1.61k
bool InstructionFolder::IsFoldableVectorType(Instruction* type_inst) const {
687
  // Support vectors with foldable components
688
1.61k
  if (type_inst->opcode() == spv::Op::OpTypeVector) {
689
122
    uint32_t component_type_id = type_inst->GetSingleWordInOperand(0);
690
122
    Instruction* def_component_type =
691
122
        context_->get_def_use_mgr()->GetDef(component_type_id);
692
122
    return def_component_type != nullptr &&
693
122
           IsFoldableScalarType(def_component_type);
694
122
  }
695
  // Nothing else yet.
696
1.49k
  return false;
697
1.61k
}
698
699
163k
bool InstructionFolder::FoldInstruction(Instruction* inst) const {
700
163k
  bool modified = false;
701
163k
  Instruction* folded_inst(inst);
702
167k
  while (folded_inst->opcode() != spv::Op::OpCopyObject &&
703
166k
         FoldInstructionInternal(&*folded_inst)) {
704
4.34k
    modified = true;
705
4.34k
  }
706
163k
  return modified;
707
163k
}
708
709
}  // namespace opt
710
}  // namespace spvtools