summaryrefslogtreecommitdiff
path: root/test/val/val_layout_test.cpp
blob: b7ddbb58e710529df4958a640add570534f7aedd (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
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Validation tests for Logical Layout

#include <functional>
#include <sstream>
#include <string>
#include <utility>

#include "gmock/gmock.h"
#include "source/diagnostic.h"
#include "unit_spirv.h"
#include "val_fixtures.h"

namespace spvtools {
namespace val {
namespace {

using std::function;
using std::ostream;
using std::ostream_iterator;
using std::pair;
using std::string;
using std::stringstream;
using std::tie;
using std::tuple;
using std::vector;

using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::StrEq;

using pred_type = function<spv_result_t(int)>;
using ValidateLayout =
    spvtest::ValidateBase<tuple<int, tuple<string, pred_type, pred_type>>>;

// returns true if order is equal to VAL
template <int VAL, spv_result_t RET = SPV_ERROR_INVALID_LAYOUT>
spv_result_t Equals(int order) {
  return order == VAL ? SPV_SUCCESS : RET;
}

// returns true if order is between MIN and MAX(inclusive)
template <int MIN, int MAX, spv_result_t RET = SPV_ERROR_INVALID_LAYOUT>
struct Range {
  explicit Range(bool inverse = false) : inverse_(inverse) {}
  spv_result_t operator()(int order) {
    return (inverse_ ^ (order >= MIN && order <= MAX)) ? SPV_SUCCESS : RET;
  }

 private:
  bool inverse_;
};

template <typename... T>
spv_result_t InvalidSet(int order) {
  for (spv_result_t val : {T(true)(order)...})
    if (val != SPV_SUCCESS) return val;
  return SPV_SUCCESS;
}

// SPIRV source used to test the logical layout
const vector<string>& getInstructions() {
  // clang-format off
  static const vector<string> instructions = {
    "OpCapability Shader",
    "OpExtension \"TestExtension\"",
    "%inst = OpExtInstImport \"GLSL.std.450\"",
    "OpMemoryModel Logical GLSL450",
    "OpEntryPoint GLCompute %func \"\"",
    "OpExecutionMode %func LocalSize 1 1 1",
    "OpExecutionModeId %func LocalSizeId %one %one %one",
    "%str = OpString \"Test String\"",
    "%str2 = OpString \"blabla\"",
    "OpSource GLSL 450 %str \"uniform vec3 var = vec3(4.0);\"",
    "OpSourceContinued \"void main(){return;}\"",
    "OpSourceExtension \"Test extension\"",
    "OpName %func \"MyFunction\"",
    "OpMemberName %struct 1 \"my_member\"",
    "OpDecorate %dgrp RowMajor",
    "OpMemberDecorate %struct 1 RowMajor",
    "%dgrp   = OpDecorationGroup",
    "OpGroupDecorate %dgrp %mat33 %mat44",
    "%intt     = OpTypeInt 32 1",
    "%floatt   = OpTypeFloat 32",
    "%voidt    = OpTypeVoid",
    "%boolt    = OpTypeBool",
    "%vec4     = OpTypeVector %floatt 4",
    "%vec3     = OpTypeVector %floatt 3",
    "%mat33    = OpTypeMatrix %vec3 3",
    "%mat44    = OpTypeMatrix %vec4 4",
    "%struct   = OpTypeStruct %intt %mat33",
    "%vfunct   = OpTypeFunction %voidt",
    "%viifunct = OpTypeFunction %voidt %intt %intt",
    "%one      = OpConstant %intt 1",
    // TODO(umar): OpConstant fails because the type is not defined
    // TODO(umar): OpGroupMemberDecorate
    "OpLine %str 3 4",
    "OpNoLine",
    "%func     = OpFunction %voidt None %vfunct",
    "%l = OpLabel",
    "OpReturn ; %func return",
    "OpFunctionEnd ; %func end",
    "%func2    = OpFunction %voidt None %viifunct",
    "%funcp1   = OpFunctionParameter %intt",
    "%funcp2   = OpFunctionParameter %intt",
    "%fLabel   = OpLabel",
    "OpNop",
    "OpReturn ; %func2 return",
    "OpFunctionEnd"
  };
  return instructions;
}

static const int kRangeEnd = 1000;
pred_type All = Range<0, kRangeEnd>();

INSTANTIATE_TEST_CASE_P(InstructionsOrder,
    ValidateLayout,
    ::testing::Combine(::testing::Range((int)0, (int)getInstructions().size()),
    // Note: Because of ID dependencies between instructions, some instructions
    // are not free to be placed anywhere without triggering an non-layout
    // validation error. Therefore, "Lines to compile" for some instructions
    // are not "All" in the below.
    //
    //                                  | Instruction                | Line(s) valid          | Lines to compile
    ::testing::Values(make_tuple(string("OpCapability")              , Equals<0>              , Range<0, 2>())
                    , make_tuple(string("OpExtension")               , Equals<1>              , All)
                    , make_tuple(string("OpExtInstImport")           , Equals<2>              , All)
                    , make_tuple(string("OpMemoryModel")             , Equals<3>              , Range<1, kRangeEnd>())
                    , make_tuple(string("OpEntryPoint")              , Equals<4>              , All)
                    , make_tuple(string("OpExecutionMode ")          , Range<5, 6>()          , All)
                    , make_tuple(string("OpExecutionModeId")         , Range<5, 6>()          , All)
                    , make_tuple(string("OpSource ")                 , Range<7, 11>()         , Range<8, kRangeEnd>())
                    , make_tuple(string("OpSourceContinued ")        , Range<7, 11>()         , All)
                    , make_tuple(string("OpSourceExtension ")        , Range<7, 11>()         , All)
                    , make_tuple(string("%str2 = OpString ")         , Range<7, 11>()         , All)
                    , make_tuple(string("OpName ")                   , Range<12, 13>()        , All)
                    , make_tuple(string("OpMemberName ")             , Range<12, 13>()        , All)
                    , make_tuple(string("OpDecorate ")               , Range<14, 17>()        , All)
                    , make_tuple(string("OpMemberDecorate ")         , Range<14, 17>()        , All)
                    , make_tuple(string("OpGroupDecorate ")          , Range<14, 17>()        , Range<17, kRangeEnd>())
                    , make_tuple(string("OpDecorationGroup")         , Range<14, 17>()        , Range<0, 16>())
                    , make_tuple(string("OpTypeBool")                , Range<18, 31>()        , All)
                    , make_tuple(string("OpTypeVoid")                , Range<18, 31>()        , Range<0, 26>())
                    , make_tuple(string("OpTypeFloat")               , Range<18, 31>()        , Range<0,21>())
                    , make_tuple(string("OpTypeInt")                 , Range<18, 31>()        , Range<0, 21>())
                    , make_tuple(string("OpTypeVector %floatt 4")    , Range<18, 31>()        , Range<20, 24>())
                    , make_tuple(string("OpTypeMatrix %vec4 4")      , Range<18, 31>()        , Range<23, kRangeEnd>())
                    , make_tuple(string("OpTypeStruct")              , Range<18, 31>()        , Range<25, kRangeEnd>())
                    , make_tuple(string("%vfunct   = OpTypeFunction"), Range<18, 31>()        , Range<21, 31>())
                    , make_tuple(string("OpConstant")                , Range<18, 31>()        , Range<21, kRangeEnd>())
                    , make_tuple(string("OpLine ")                   , Range<18, kRangeEnd>() , Range<8, kRangeEnd>())
                    , make_tuple(string("OpNoLine")                  , Range<18, kRangeEnd>() , All)
                    , make_tuple(string("%fLabel   = OpLabel")       , Equals<39>             , All)
                    , make_tuple(string("OpNop")                     , Equals<40>             , Range<40,kRangeEnd>())
                    , make_tuple(string("OpReturn ; %func2 return")  , Equals<41>             , All)
    )),);
// clang-format on

// Creates a new vector which removes the string if the substr is found in the
// instructions vector and reinserts it in the location specified by order.
// NOTE: This will not work correctly if there are two instances of substr in
// instructions
vector<string> GenerateCode(string substr, int order) {
  vector<string> code(getInstructions().size());
  vector<string> inst(1);
  partition_copy(begin(getInstructions()), end(getInstructions()), begin(code),
                 begin(inst), [=](const string& str) {
                   return string::npos == str.find(substr);
                 });

  code.insert(begin(code) + order, inst.front());
  return code;
}

// This test will check the logical layout of a binary by removing each
// instruction in the pair of the INSTANTIATE_TEST_CASE_P call and moving it in
// the SPIRV source formed by combining the vector "instructions".
TEST_P(ValidateLayout, Layout) {
  int order;
  string instruction;
  pred_type pred;
  pred_type test_pred;  // Predicate to determine if the test should be build
  tuple<string, pred_type, pred_type> testCase;

  tie(order, testCase) = GetParam();
  tie(instruction, pred, test_pred) = testCase;

  // Skip test which break the code generation
  if (test_pred(order)) return;

  vector<string> code = GenerateCode(instruction, order);

  stringstream ss;
  copy(begin(code), end(code), ostream_iterator<string>(ss, "\n"));

  const auto env = SPV_ENV_UNIVERSAL_1_3;
  // printf("code: \n%s\n", ss.str().c_str());
  CompileSuccessfully(ss.str(), env);
  spv_result_t result;
  // clang-format off
  ASSERT_EQ(pred(order), result = ValidateInstructions(env))
    << "Actual: "        << spvResultToString(result)
    << "\nExpected: "    << spvResultToString(pred(order))
    << "\nOrder: "       << order
    << "\nInstruction: " << instruction
    << "\nCode: \n"      << ss.str();
  // clang-format on
}

TEST_F(ValidateLayout, MemoryModelMissingBeforeEntryPoint) {
  string str = R"(
    OpCapability Matrix
    OpExtension "TestExtension"
    %inst = OpExtInstImport "GLSL.std.450"
    OpEntryPoint GLCompute %func ""
    OpExecutionMode %func LocalSize 1 1 1
    )";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr(
          "EntryPoint cannot appear before the memory model instruction"));
}

TEST_F(ValidateLayout, MemoryModelMissing) {
  char str[] = R"(OpCapability Linkage)";
  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("Missing required OpMemoryModel instruction"));
}

TEST_F(ValidateLayout, MemoryModelSpecifiedTwice) {
  char str[] = R"(
    OpCapability Linkage
    OpCapability Shader
    OpMemoryModel Logical Simple
    OpMemoryModel Logical Simple
    )";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("OpMemoryModel should only be provided once"));
}

TEST_F(ValidateLayout, FunctionDefinitionBeforeDeclarationBad) {
  char str[] = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpDecorate %var Restrict
%intt    = OpTypeInt 32 1
%voidt   = OpTypeVoid
%vfunct  = OpTypeFunction %voidt
%vifunct = OpTypeFunction %voidt %intt
%ptrt    = OpTypePointer Function %intt
%func    = OpFunction %voidt None %vfunct
%funcl   = OpLabel
           OpNop
           OpReturn
           OpFunctionEnd
%func2   = OpFunction %voidt None %vifunct ; must appear before definition
%func2p  = OpFunctionParameter %intt
           OpFunctionEnd
)";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr(
          "Function declarations must appear before function definitions."));
}

// TODO(umar): Passes but gives incorrect error message. Should be fixed after
// type checking
TEST_F(ValidateLayout, LabelBeforeFunctionParameterBad) {
  char str[] = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpDecorate %var Restrict
%intt    = OpTypeInt 32 1
%voidt   = OpTypeVoid
%vfunct  = OpTypeFunction %voidt
%vifunct = OpTypeFunction %voidt %intt
%ptrt    = OpTypePointer Function %intt
%func    = OpFunction %voidt None %vifunct
%funcl   = OpLabel                    ; Label appears before function parameter
%func2p  = OpFunctionParameter %intt
           OpNop
           OpReturn
           OpFunctionEnd
)";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("Function parameters must only appear immediately "
                        "after the function definition"));
}

TEST_F(ValidateLayout, FuncParameterNotImmediatlyAfterFuncBad) {
  char str[] = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpDecorate %var Restrict
%intt    = OpTypeInt 32 1
%voidt   = OpTypeVoid
%vfunct  = OpTypeFunction %voidt
%vifunct = OpTypeFunction %voidt %intt
%ptrt    = OpTypePointer Function %intt
%func    = OpFunction %voidt None %vifunct
%funcl   = OpLabel
           OpNop
           OpBranch %next
%func2p  = OpFunctionParameter %intt        ;FunctionParameter appears in a function but not immediately afterwards
%next    = OpLabel
           OpNop
           OpReturn
           OpFunctionEnd
)";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("Function parameters must only appear immediately "
                        "after the function definition"));
}

TEST_F(ValidateLayout, OpUndefCanAppearInTypeDeclarationSection) {
  string str = R"(
         OpCapability Kernel
         OpCapability Linkage
         OpMemoryModel Logical OpenCL
%voidt = OpTypeVoid
%uintt = OpTypeInt 32 0
%funct = OpTypeFunction %voidt
%udef  = OpUndef %uintt
%func  = OpFunction %voidt None %funct
%entry = OpLabel
         OpReturn
         OpFunctionEnd
)";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_SUCCESS, ValidateInstructions());
}

TEST_F(ValidateLayout, OpUndefCanAppearInBlock) {
  string str = R"(
         OpCapability Kernel
         OpCapability Linkage
         OpMemoryModel Logical OpenCL
%voidt = OpTypeVoid
%uintt = OpTypeInt 32 0
%funct = OpTypeFunction %voidt
%func  = OpFunction %voidt None %funct
%entry = OpLabel
%udef  = OpUndef %uintt
         OpReturn
         OpFunctionEnd
)";

  CompileSuccessfully(str);
  ASSERT_EQ(SPV_SUCCESS, ValidateInstructions());
}

TEST_F(ValidateLayout, MissingFunctionEndForFunctionWithBody) {
  const auto s = R"(
OpCapability Shader
OpCapability Linkage
OpMemoryModel Logical GLSL450
%void = OpTypeVoid
%tf = OpTypeFunction %void
%f = OpFunction %void None %tf
%l = OpLabel
OpReturn
)";

  CompileSuccessfully(s);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(getDiagnosticString(),
              StrEq("Missing OpFunctionEnd at end of module."));
}

TEST_F(ValidateLayout, MissingFunctionEndForFunctionPrototype) {
  const auto s = R"(
OpCapability Shader
OpCapability Linkage
OpMemoryModel Logical GLSL450
%void = OpTypeVoid
%tf = OpTypeFunction %void
%f = OpFunction %void None %tf
)";

  CompileSuccessfully(s);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT, ValidateInstructions());
  EXPECT_THAT(getDiagnosticString(),
              StrEq("Missing OpFunctionEnd at end of module."));
}

using ValidateOpFunctionParameter = spvtest::ValidateBase<int>;

TEST_F(ValidateOpFunctionParameter, OpLineBetweenParameters) {
  const auto s = R"(
OpCapability Shader
OpCapability Linkage
OpMemoryModel Logical GLSL450
%foo_frag = OpString "foo.frag"
%i32 = OpTypeInt 32 1
%tf = OpTypeFunction %i32 %i32 %i32
%c = OpConstant %i32 123
%f = OpFunction %i32 None %tf
OpLine %foo_frag 1 1
%p1 = OpFunctionParameter %i32
OpNoLine
%p2 = OpFunctionParameter %i32
%l = OpLabel
OpReturnValue %c
OpFunctionEnd
)";
  CompileSuccessfully(s);
  ASSERT_EQ(SPV_SUCCESS, ValidateInstructions());
}

TEST_F(ValidateOpFunctionParameter, TooManyParameters) {
  const auto s = R"(
OpCapability Shader
OpCapability Linkage
OpMemoryModel Logical GLSL450
%i32 = OpTypeInt 32 1
%tf = OpTypeFunction %i32 %i32 %i32
%c = OpConstant %i32 123
%f = OpFunction %i32 None %tf
%p1 = OpFunctionParameter %i32
%p2 = OpFunctionParameter %i32
%xp3 = OpFunctionParameter %i32
%xp4 = OpFunctionParameter %i32
%xp5 = OpFunctionParameter %i32
%xp6 = OpFunctionParameter %i32
%xp7 = OpFunctionParameter %i32
%l = OpLabel
OpReturnValue %c
OpFunctionEnd
)";
  CompileSuccessfully(s);
  ASSERT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
}

using ValidateEntryPoint = spvtest::ValidateBase<bool>;

// Tests that not having OpEntryPoint causes an error.
TEST_F(ValidateEntryPoint, NoEntryPointBad) {
  std::string spirv = R"(
      OpCapability Shader
      OpMemoryModel Logical GLSL450)";
  CompileSuccessfully(spirv);
  EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions());
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("No OpEntryPoint instruction was found. This is only "
                        "allowed if the Linkage capability is being used."));
}

// Invalid. A function may not be a target of both OpEntryPoint and
// OpFunctionCall.
TEST_F(ValidateEntryPoint, FunctionIsTargetOfEntryPointAndFunctionCallBad) {
  std::string spirv = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpEntryPoint Fragment %foo "foo"
%voidt   = OpTypeVoid
%funct   = OpTypeFunction %voidt
%foo     = OpFunction %voidt None %funct
%entry   = OpLabel
%recurse = OpFunctionCall %voidt %foo
           OpReturn
           OpFunctionEnd
      )";
  CompileSuccessfully(spirv);
  EXPECT_EQ(SPV_ERROR_INVALID_BINARY, ValidateInstructions());
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr("A function (1) may not be targeted by both an OpEntryPoint "
                "instruction and an OpFunctionCall instruction."));
}

// Valid. Module with a function but no entry point is valid when Linkage
// Capability is used.
TEST_F(ValidateEntryPoint, NoEntryPointWithLinkageCapGood) {
  std::string spirv = R"(
           OpCapability Shader
           OpCapability Linkage
           OpMemoryModel Logical GLSL450
%voidt   = OpTypeVoid
%funct   = OpTypeFunction %voidt
%foo     = OpFunction %voidt None %funct
%entry   = OpLabel
           OpReturn
           OpFunctionEnd
  )";
  CompileSuccessfully(spirv);
  EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
}

TEST_F(ValidateLayout, ModuleProcessedInvalidIn10) {
  char str[] = R"(
           OpCapability Shader
           OpCapability Linkage
           OpMemoryModel Logical GLSL450
           OpName %void "void"
           OpModuleProcessed "this is ok in 1.1 and later"
           OpDecorate %void Volatile ; bogus, but makes the example short
%void    = OpTypeVoid
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_WRONG_VERSION,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_0));
  // In a 1.0 environment the version check fails.
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("Invalid SPIR-V binary version 1.1 for target "
                        "environment SPIR-V 1.0."));
}

TEST_F(ValidateLayout, ModuleProcessedValidIn11) {
  char str[] = R"(
           OpCapability Shader
           OpCapability Linkage
           OpMemoryModel Logical GLSL450
           OpName %void "void"
           OpModuleProcessed "this is ok in 1.1 and later"
           OpDecorate %void Volatile ; bogus, but makes the example short
%void    = OpTypeVoid
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_SUCCESS, ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(getDiagnosticString(), Eq(""));
}

TEST_F(ValidateLayout, ModuleProcessedBeforeLastNameIsTooEarly) {
  char str[] = R"(
           OpCapability Shader
           OpCapability Linkage
           OpMemoryModel Logical GLSL450
           OpModuleProcessed "this is too early"
           OpName %void "void"
%void    = OpTypeVoid
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  // By the mechanics of the validator, we assume ModuleProcessed is in the
  // right spot, but then that OpName is in the wrong spot.
  EXPECT_THAT(getDiagnosticString(),
              HasSubstr("Name cannot appear in a function declaration"));
}

TEST_F(ValidateLayout, ModuleProcessedInvalidAfterFirstAnnotation) {
  char str[] = R"(
           OpCapability Shader
           OpCapability Linkage
           OpMemoryModel Logical GLSL450
           OpDecorate %void Volatile ; this is bogus, but keeps the example short
           OpModuleProcessed "this is too late"
%void    = OpTypeVoid
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr("ModuleProcessed cannot appear in a function declaration"));
}

TEST_F(ValidateLayout, ModuleProcessedInvalidInFunctionBeforeLabel) {
  char str[] = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpEntryPoint GLCompute %main "main"
%void    = OpTypeVoid
%voidfn  = OpTypeFunction %void
%main    = OpFunction %void None %voidfn
           OpModuleProcessed "this is too late, in function before label"
%entry  =  OpLabel
           OpReturn
           OpFunctionEnd
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr("ModuleProcessed cannot appear in a function declaration"));
}

TEST_F(ValidateLayout, ModuleProcessedInvalidInBasicBlock) {
  char str[] = R"(
           OpCapability Shader
           OpMemoryModel Logical GLSL450
           OpEntryPoint GLCompute %main "main"
%void    = OpTypeVoid
%voidfn  = OpTypeFunction %void
%main    = OpFunction %void None %voidfn
%entry   = OpLabel
           OpModuleProcessed "this is too late, in basic block"
           OpReturn
           OpFunctionEnd
)";

  CompileSuccessfully(str, SPV_ENV_UNIVERSAL_1_1);
  ASSERT_EQ(SPV_ERROR_INVALID_LAYOUT,
            ValidateInstructions(SPV_ENV_UNIVERSAL_1_1));
  EXPECT_THAT(
      getDiagnosticString(),
      HasSubstr("ModuleProcessed cannot appear in a function declaration"));
}

// TODO(umar): Test optional instructions

}  // namespace
}  // namespace val
}  // namespace spvtools