File: SPIRVEntry.cpp

package info (click to toggle)
spirv-llvm-translator-19 19.1.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,996 kB
  • sloc: cpp: 45,009; ansic: 6,283; lisp: 3,739; sh: 162; python: 58; makefile: 33
file content (868 lines) | stat: -rw-r--r-- 28,012 bytes parent folder | download | duplicates (2)
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//===- SPIRVEntry.cpp - Base Class for SPIR-V Entities ----------*- C++ -*-===//
//
//                     The LLVM/SPIRV Translator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the documentation
// and/or other materials provided with the distribution.
// Neither the names of Advanced Micro Devices, Inc., nor the names of its
// contributors may be used to endorse or promote products derived from this
// Software without specific prior written permission.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
// THE SOFTWARE.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements base class for SPIR-V entities.
///
//===----------------------------------------------------------------------===//

#include "SPIRVEntry.h"
#include "SPIRVAsm.h"
#include "SPIRVBasicBlock.h"
#include "SPIRVDebug.h"
#include "SPIRVDecorate.h"
#include "SPIRVFunction.h"
#include "SPIRVInstruction.h"
#include "SPIRVMemAliasingINTEL.h"
#include "SPIRVNameMapEnum.h"
#include "SPIRVStream.h"
#include "SPIRVType.h"

#include <algorithm>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>

using namespace SPIRV;

namespace SPIRV {

template <typename T> SPIRVEntry *create() { return new T(); }

SPIRVEntry *SPIRVEntry::create(Op OpCode) {
  typedef SPIRVEntry *(*SPIRVFactoryTy)();
  struct TableEntry {
    Op Opn;
    SPIRVFactoryTy Factory;
    operator std::pair<const Op, SPIRVFactoryTy>() {
      return std::make_pair(Opn, Factory);
    }
  };

  static TableEntry Table[] = {
#define _SPIRV_OP(x, ...) {Op##x, &SPIRV::create<SPIRV##x>},
#define _SPIRV_OP_INTERNAL(x, ...) {internal::Op##x, &SPIRV::create<SPIRV##x>},
#include "SPIRVOpCodeEnum.h"
#include "SPIRVOpCodeEnumInternal.h"
#undef _SPIRV_OP_INTERNAL
#undef _SPIRV_OP
  };

  typedef std::unordered_map<Op, SPIRVFactoryTy> OpToFactoryMapTy;
  static const OpToFactoryMapTy OpToFactoryMap(std::begin(Table),
                                               std::end(Table));

  // TODO: To remove this when we make a switch to new version
  if (OpCode == internal::OpTypeJointMatrixINTELv2)
    OpCode = internal::OpTypeJointMatrixINTEL;

  OpToFactoryMapTy::const_iterator Loc = OpToFactoryMap.find(OpCode);
  if (Loc != OpToFactoryMap.end())
    return Loc->second();

  SPIRVDBG(spvdbgs() << "No factory for OpCode " << (unsigned)OpCode << '\n';)
  assert(0 && "Not implemented");
  return 0;
}

std::unique_ptr<SPIRV::SPIRVEntry> SPIRVEntry::createUnique(Op OC) {
  return std::unique_ptr<SPIRVEntry>(create(OC));
}

std::unique_ptr<SPIRV::SPIRVExtInst>
SPIRVEntry::createUnique(SPIRVExtInstSetKind Set, unsigned ExtOp) {
  return std::unique_ptr<SPIRVExtInst>(new SPIRVExtInst(Set, ExtOp));
}

SPIRVErrorLog &SPIRVEntry::getErrorLog() const { return Module->getErrorLog(); }

bool SPIRVEntry::exist(SPIRVId TheId) const { return Module->exist(TheId); }

SPIRVEntry *SPIRVEntry::getOrCreate(SPIRVId TheId) const {
  SPIRVEntry *Entry = nullptr;
  bool Found = Module->exist(TheId, &Entry);
  if (!Found)
    return Module->addForward(TheId, nullptr);
  return Entry;
}

SPIRVValue *SPIRVEntry::getValue(SPIRVId TheId) const {
  return get<SPIRVValue>(TheId);
}

SPIRVType *SPIRVEntry::getValueType(SPIRVId TheId) const {
  return get<SPIRVValue>(TheId)->getType();
}

SPIRVEncoder SPIRVEntry::getEncoder(spv_ostream &O) const {
  return SPIRVEncoder(O);
}

SPIRVDecoder SPIRVEntry::getDecoder(std::istream &I) {
  return SPIRVDecoder(I, *Module);
}

void SPIRVEntry::setWordCount(SPIRVWord TheWordCount) {
  WordCount = TheWordCount;
}

void SPIRVEntry::setName(const std::string &TheName) {
  Name = TheName;
  SPIRVDBG(spvdbgs() << "Set name for obj " << Id << " " << Name << '\n');
}

void SPIRVEntry::setModule(SPIRVModule *TheModule) {
  assert(TheModule && "Invalid module");
  if (TheModule == Module)
    return;
  assert(Module == NULL && "Cannot change owner of entry");
  Module = TheModule;
}

void SPIRVEntry::encode(spv_ostream &O) const {
  assert(0 && "Not implemented");
}

void SPIRVEntry::encodeName(spv_ostream &O) const {
  if (!Name.empty())
    O << SPIRVName(this, Name);
}

bool SPIRVEntry::isEndOfBlock() const {
  switch (OpCode) {
  case OpBranch:
  case OpBranchConditional:
  case OpSwitch:
  case OpKill:
  case OpReturn:
  case OpReturnValue:
  case OpUnreachable:
    return true;
  default:
    return false;
  }
}

void SPIRVEntry::encodeLine(spv_ostream &O) const {
  if (!Module)
    return;
  const std::shared_ptr<const SPIRVLine> &CurrLine = Module->getCurrentLine();
  if (Line && (!CurrLine || *Line != *CurrLine)) {
    O << *Line;
    Module->setCurrentLine(Line);
  }
  if (isEndOfBlock() || OpCode == OpNoLine)
    Module->setCurrentLine(nullptr);
}

namespace {
bool isDebugLineEqual(const SPIRVExtInst &DL1, const SPIRVExtInst &DL2) {
  std::vector<SPIRVWord> DL1Args = DL1.getArguments();
  std::vector<SPIRVWord> DL2Args = DL2.getArguments();

  using namespace SPIRVDebug::Operand::DebugLine;
  assert(DL1Args.size() == OperandCount && DL2Args.size() == OperandCount &&
         "Invalid number of operands");
  return DL1Args[SourceIdx] == DL2Args[SourceIdx] &&
         DL1Args[StartIdx] == DL2Args[StartIdx] &&
         DL1Args[EndIdx] == DL2Args[EndIdx] &&
         DL1Args[ColumnStartIdx] == DL2Args[ColumnStartIdx] &&
         DL1Args[ColumnEndIdx] == DL2Args[ColumnEndIdx];
}
} // namespace

void SPIRVEntry::encodeDebugLine(spv_ostream &O) const {
  if (!Module)
    return;
  const std::shared_ptr<const SPIRVExtInst> &CurrDebugLine =
      Module->getCurrentDebugLine();
  if (DebugLine &&
      (!CurrDebugLine || !isDebugLineEqual(*DebugLine, *CurrDebugLine))) {
    O << *DebugLine;
    Module->setCurrentDebugLine(DebugLine);
  }
  if (isEndOfBlock() ||
      isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_100,
                SPIRVDebug::DebugNoLine) ||
      isExtInst(SPIRVEIS_NonSemantic_Shader_DebugInfo_200,
                SPIRVDebug::DebugNoLine))
    Module->setCurrentDebugLine(nullptr);
}

void SPIRVEntry::encodeAll(spv_ostream &O) const {
  encodeLine(O);
  encodeDebugLine(O);
  encodeWordCountOpCode(O);
  encode(O);
  encodeChildren(O);
}

void SPIRVEntry::encodeChildren(spv_ostream &O) const {}

void SPIRVEntry::encodeWordCountOpCode(spv_ostream &O) const {
#ifdef _SPIRV_SUPPORT_TEXT_FMT
  if (SPIRVUseTextFormat) {
    getEncoder(O) << WordCount << OpCode;
    return;
  }
#endif
  assert(WordCount < 65536 && "WordCount must fit into 16-bit value");
  SPIRVWord WordCountOpCode = (WordCount << WordCountShift) | OpCode;
  getEncoder(O) << WordCountOpCode;
}
// Read words from SPIRV binary and create members for SPIRVEntry.
// The word count and op code has already been read before calling this
// function for creating the SPIRVEntry. Therefore the input stream only
// contains the remaining part of the words for the SPIRVEntry.
void SPIRVEntry::decode(std::istream &I) { assert(0 && "Not implemented"); }

std::vector<SPIRVValue *>
SPIRVEntry::getValues(const std::vector<SPIRVId> &IdVec) const {
  std::vector<SPIRVValue *> ValueVec;
  for (auto I : IdVec)
    ValueVec.push_back(getValue(I));
  return ValueVec;
}

std::vector<SPIRVType *>
SPIRVEntry::getValueTypes(const std::vector<SPIRVId> &IdVec) const {
  std::vector<SPIRVType *> TypeVec;
  for (auto I : IdVec)
    TypeVec.push_back(getValue(I)->getType());
  return TypeVec;
}

std::vector<SPIRVId>
SPIRVEntry::getIds(const std::vector<SPIRVValue *> ValueVec) const {
  std::vector<SPIRVId> IdVec;
  for (auto *I : ValueVec)
    IdVec.push_back(I->getId());
  return IdVec;
}

SPIRVEntry *SPIRVEntry::getEntry(SPIRVId TheId) const {
  return Module->getEntry(TheId);
}

void SPIRVEntry::validateFunctionControlMask(SPIRVWord TheFCtlMask) const {
  SPIRVCK(isValidFunctionControlMask(TheFCtlMask), InvalidFunctionControlMask,
          "");
}

void SPIRVEntry::validateValues(const std::vector<SPIRVId> &Ids) const {
  for (auto I : Ids)
    getValue(I)->validate();
}

void SPIRVEntry::validateBuiltin(SPIRVWord TheSet, SPIRVWord Index) const {
  assert(TheSet != SPIRVWORD_MAX && Index != SPIRVWORD_MAX &&
         "Invalid builtin");
}

void SPIRVEntry::addDecorate(SPIRVDecorate *Dec) {
  auto Kind = Dec->getDecorateKind();
  Decorates.insert(std::make_pair(Kind, Dec));
  Module->addDecorate(Dec);
  if (Kind == spv::DecorationLinkageAttributes) {
    auto *LinkageAttr = static_cast<const SPIRVDecorateLinkageAttr *>(Dec);
    setName(LinkageAttr->getLinkageName());
  }
  SPIRVDBG(spvdbgs() << "[addDecorate] Add "
                     << SPIRVDecorationNameMap::map(Kind) << " to Id " << Id
                     << '\n';)
}

void SPIRVEntry::addDecorate(SPIRVDecorateId *Dec) {
  auto Kind = Dec->getDecorateKind();
  DecorateIds.insert(std::make_pair(Kind, Dec));
  Module->addDecorate(Dec);
  SPIRVDBG(spvdbgs() << "[addDecorateId] Add"
                     << SPIRVDecorationNameMap::map(Kind) << " to Id " << Id
                     << '\n';)
}

void SPIRVEntry::addDecorate(Decoration Kind) {
  addDecorate(new SPIRVDecorate(Kind, this));
}

void SPIRVEntry::addDecorate(Decoration Kind, SPIRVWord Literal) {
  switch (static_cast<int>(Kind)) {
  case DecorationAliasScopeINTEL:
  case DecorationNoAliasINTEL:
    addDecorate(new SPIRVDecorateId(Kind, this, Literal));
    return;
  default:
    addDecorate(new SPIRVDecorate(Kind, this, Literal));
  }
}

void SPIRVEntry::eraseDecorate(Decoration Dec) { Decorates.erase(Dec); }

void SPIRVEntry::takeDecorates(SPIRVEntry *E) {
  Decorates = std::move(E->Decorates);
  SPIRVDBG(spvdbgs() << "[takeDecorates] " << Id << '\n';)
}

void SPIRVEntry::takeDecorateIds(SPIRVEntry *E) {
  DecorateIds = std::move(E->DecorateIds);
  SPIRVDBG(spvdbgs() << "[takeDecorateIds] " << Id << '\n';)
}

void SPIRVEntry::setLine(const std::shared_ptr<const SPIRVLine> &L) {
  Line = L;
  SPIRVDBG(if (L) spvdbgs() << "[setLine] " << *L << '\n';)
}

void SPIRVEntry::setDebugLine(const std::shared_ptr<const SPIRVExtInst> &DL) {
  DebugLine = DL;
  SPIRVDBG(if (DL) spvdbgs() << "[setDebugLine] " << *DL << '\n';)
}

void SPIRVEntry::addMemberDecorate(SPIRVMemberDecorate *Dec) {
  assert(canHaveMemberDecorates());
  MemberDecorates.insert(std::make_pair(
      std::make_pair(Dec->getMemberNumber(), Dec->getDecorateKind()), Dec));
  Module->addDecorate(Dec);
  SPIRVDBG(spvdbgs() << "[addMemberDecorate] " << *Dec << '\n';)
}

void SPIRVEntry::addMemberDecorate(SPIRVWord MemberNumber, Decoration Kind) {
  addMemberDecorate(new SPIRVMemberDecorate(Kind, MemberNumber, this));
}

void SPIRVEntry::addMemberDecorate(SPIRVWord MemberNumber, Decoration Kind,
                                   SPIRVWord Literal) {
  addMemberDecorate(new SPIRVMemberDecorate(Kind, MemberNumber, this, Literal));
}

void SPIRVEntry::eraseMemberDecorate(SPIRVWord MemberNumber, Decoration Dec) {
  MemberDecorates.erase(std::make_pair(MemberNumber, Dec));
}

void SPIRVEntry::takeMemberDecorates(SPIRVEntry *E) {
  MemberDecorates = std::move(E->MemberDecorates);
  SPIRVDBG(spvdbgs() << "[takeMemberDecorates] " << Id << '\n';)
}

void SPIRVEntry::takeAnnotations(SPIRVForward *E) {
  Module->setName(this, E->getName());
  takeDecorates(E);
  takeDecorateIds(E);
  takeMemberDecorates(E);
  if (OpCode == OpFunction)
    static_cast<SPIRVFunction *>(this)->takeExecutionModes(E);
}

void SPIRVEntry::replaceTargetIdInDecorates(SPIRVId Id) {
  for (auto It = Decorates.begin(), E = Decorates.end(); It != E; ++It)
    const_cast<SPIRVDecorate *>(It->second)->setTargetId(Id);
  for (auto It = DecorateIds.begin(), E = DecorateIds.end(); It != E; ++It)
    const_cast<SPIRVDecorateId *>(It->second)->setTargetId(Id);
  for (auto It = MemberDecorates.begin(), E = MemberDecorates.end(); It != E;
       ++It)
    const_cast<SPIRVMemberDecorate *>(It->second)->setTargetId(Id);
}

// Check if an entry has Kind of decoration and get the literal of the
// first decoration of such kind at Index.
bool SPIRVEntry::hasDecorate(Decoration Kind, size_t Index,
                             SPIRVWord *Result) const {
  auto Loc = Decorates.find(Kind);
  if (Loc == Decorates.end())
    return false;
  if (Result)
    *Result = Loc->second->getLiteral(Index);
  return true;
}

bool SPIRVEntry::hasDecorateId(Decoration Kind, size_t Index,
                               SPIRVId *Result) const {
  auto Loc = DecorateIds.find(Kind);
  if (Loc == DecorateIds.end())
    return false;
  if (Result)
    *Result = Loc->second->getLiteral(Index);
  return true;
}

// Check if an entry member has Kind of decoration and get the literal of the
// first decoration of such kind at Index.
bool SPIRVEntry::hasMemberDecorate(Decoration Kind, size_t Index,
                                   SPIRVWord MemberNumber,
                                   SPIRVWord *Result) const {
  auto Loc = MemberDecorates.find({MemberNumber, Kind});
  if (Loc == MemberDecorates.end())
    return false;
  if (Result)
    *Result = Loc->second->getLiteral(Index);
  return true;
}

std::vector<std::string>
SPIRVEntry::getDecorationStringLiteral(Decoration Kind) const {
  auto Loc = Decorates.find(Kind);
  if (Loc == Decorates.end())
    return {};

  return getVecString(Loc->second->getVecLiteral());
}

std::vector<std::string>
SPIRVEntry::getMemberDecorationStringLiteral(Decoration Kind,
                                             SPIRVWord MemberNumber) const {
  auto Loc = MemberDecorates.find({MemberNumber, Kind});
  if (Loc == MemberDecorates.end())
    return {};

  return getVecString(Loc->second->getVecLiteral());
}

std::vector<std::vector<std::string>>
SPIRVEntry::getAllDecorationStringLiterals(Decoration Kind) const {
  auto Loc = Decorates.find(Kind);
  if (Loc == Decorates.end())
    return {};

  std::vector<std::vector<std::string>> Literals;
  auto It = Decorates.equal_range(Kind);
  for (auto Itr = It.first; Itr != It.second; ++Itr)
    Literals.push_back(getVecString(Itr->second->getVecLiteral()));
  return Literals;
}

std::vector<std::vector<std::string>>
SPIRVEntry::getAllMemberDecorationStringLiterals(Decoration Kind,
                                                 SPIRVWord MemberNumber) const {
  auto Loc = MemberDecorates.find({MemberNumber, Kind});
  if (Loc == MemberDecorates.end())
    return {};

  std::vector<std::vector<std::string>> Literals;
  auto It = MemberDecorates.equal_range({MemberNumber, Kind});
  for (auto Itr = It.first; Itr != It.second; ++Itr)
    Literals.push_back(getVecString(Itr->second->getVecLiteral()));
  return Literals;
}

std::vector<SPIRVWord>
SPIRVEntry::getDecorationLiterals(Decoration Kind) const {
  auto Loc = Decorates.find(Kind);
  if (Loc == Decorates.end())
    return {};

  return (Loc->second->getVecLiteral());
}

std::vector<SPIRVId>
SPIRVEntry::getDecorationIdLiterals(Decoration Kind) const {
  auto Loc = DecorateIds.find(Kind);
  if (Loc == DecorateIds.end())
    return {};

  return (Loc->second->getVecLiteral());
}

std::vector<SPIRVWord>
SPIRVEntry::getMemberDecorationLiterals(Decoration Kind,
                                        SPIRVWord MemberNumber) const {
  auto Loc = MemberDecorates.find({MemberNumber, Kind});
  if (Loc == MemberDecorates.end())
    return {};

  return (Loc->second->getVecLiteral());
}

// Get literals of all decorations of Kind at Index.
std::set<SPIRVWord> SPIRVEntry::getDecorate(Decoration Kind,
                                            size_t Index) const {
  auto Range = Decorates.equal_range(Kind);
  std::set<SPIRVWord> Value;
  for (auto I = Range.first, E = Range.second; I != E; ++I) {
    assert(Index < I->second->getLiteralCount() && "Invalid index");
    Value.insert(I->second->getLiteral(Index));
  }
  return Value;
}

std::vector<SPIRVDecorate const *>
SPIRVEntry::getDecorations(Decoration Kind) const {
  auto Range = Decorates.equal_range(Kind);
  std::vector<SPIRVDecorate const *> Decors;
  Decors.reserve(Decorates.count(Kind));
  for (auto I = Range.first, E = Range.second; I != E; ++I) {
    Decors.push_back(I->second);
  }
  return Decors;
}

std::vector<SPIRVDecorate const *> SPIRVEntry::getDecorations() const {
  std::vector<SPIRVDecorate const *> Decors;
  Decors.reserve(Decorates.size());
  for (auto &DecoPair : Decorates)
    Decors.push_back(DecoPair.second);
  return Decors;
}

std::set<SPIRVId> SPIRVEntry::getDecorateId(Decoration Kind,
                                            size_t Index) const {
  auto Range = DecorateIds.equal_range(Kind);
  std::set<SPIRVId> Value;
  for (auto I = Range.first, E = Range.second; I != E; ++I) {
    assert(Index < I->second->getLiteralCount() && "Invalid index");
    Value.insert(I->second->getLiteral(Index));
  }
  return Value;
}

std::vector<SPIRVDecorateId const *>
SPIRVEntry::getDecorationIds(Decoration Kind) const {
  auto Range = DecorateIds.equal_range(Kind);
  std::vector<SPIRVDecorateId const *> Decors;
  Decors.reserve(DecorateIds.count(Kind));
  for (auto I = Range.first, E = Range.second; I != E; ++I) {
    Decors.push_back(I->second);
  }
  return Decors;
}

bool SPIRVEntry::hasLinkageType() const {
  return OpCode == OpFunction || OpCode == OpVariable;
}

bool SPIRVEntry::isExtInst(const SPIRVExtInstSetKind InstSet) const {
  if (isExtInst()) {
    const SPIRVExtInst *EI = static_cast<const SPIRVExtInst *>(this);
    return EI->getExtSetKind() == InstSet;
  }
  return false;
}

bool SPIRVEntry::isExtInst(const SPIRVExtInstSetKind InstSet,
                           const SPIRVWord ExtOp) const {
  if (isExtInst()) {
    const SPIRVExtInst *EI = static_cast<const SPIRVExtInst *>(this);
    if (EI->getExtSetKind() == InstSet) {
      return EI->getExtOp() == ExtOp;
    }
  }
  return false;
}

void SPIRVEntry::encodeDecorate(spv_ostream &O) const {
  for (auto &I : Decorates)
    O << *I.second;
  for (auto &I : DecorateIds)
    O << *I.second;
}

SPIRVLinkageTypeKind SPIRVEntry::getLinkageType() const {
  assert(hasLinkageType());
  DecorateMapType::const_iterator Loc =
      Decorates.find(DecorationLinkageAttributes);
  if (Loc == Decorates.end())
    return internal::LinkageTypeInternal;
  return static_cast<const SPIRVDecorateLinkageAttr *>(Loc->second)
      ->getLinkageType();
}

void SPIRVEntry::setLinkageType(SPIRVLinkageTypeKind LT) {
  assert(isValid(LT));
  assert(hasLinkageType());
  addDecorate(new SPIRVDecorateLinkageAttr(this, Name, LT));
}

void SPIRVEntry::updateModuleVersion() const {
  if (!Module)
    return;

  Module->setMinSPIRVVersion(getRequiredSPIRVVersion());
}

spv_ostream &operator<<(spv_ostream &O, const SPIRVEntry &E) {
  E.validate();
  E.encodeAll(O);
  O << SPIRVNL();
  return O;
}

std::istream &operator>>(std::istream &I, SPIRVEntry &E) {
  E.decode(I);
  return I;
}

SPIRVEntryPoint::SPIRVEntryPoint(SPIRVModule *TheModule,
                                 SPIRVExecutionModelKind TheExecModel,
                                 SPIRVId TheId, const std::string &TheName,
                                 std::vector<SPIRVId> Variables)
    : SPIRVAnnotation(OpEntryPoint, TheModule->get<SPIRVFunction>(TheId),
                      getSizeInWords(TheName) + Variables.size() + 3),
      ExecModel(TheExecModel), Name(TheName), Variables(Variables) {}

void SPIRVEntryPoint::encode(spv_ostream &O) const {
  getEncoder(O) << ExecModel << Target << Name << Variables;
}

void SPIRVEntryPoint::decode(std::istream &I) {
  getDecoder(I) >> ExecModel >> Target >> Name;
  Variables.resize(WordCount - FixedWC - getSizeInWords(Name) + 1);
  getDecoder(I) >> Variables;
  Module->setName(getOrCreateTarget(), Name);
  Module->addEntryPoint(ExecModel, Target, Name, Variables);
}

void SPIRVExecutionMode::encode(spv_ostream &O) const {
  getEncoder(O) << Target << ExecMode << WordLiterals;
}

void SPIRVExecutionMode::decode(std::istream &I) {
  getDecoder(I) >> Target >> ExecMode;
  switch (static_cast<uint32_t>(ExecMode)) {
  case ExecutionModeLocalSize:
  case ExecutionModeLocalSizeId:
  case ExecutionModeLocalSizeHint:
  case ExecutionModeLocalSizeHintId:
  case ExecutionModeMaxWorkgroupSizeINTEL:
    WordLiterals.resize(3);
    break;
  case ExecutionModeInvocations:
  case ExecutionModeOutputVertices:
  case ExecutionModeVecTypeHint:
  case ExecutionModeDenormPreserve:
  case ExecutionModeDenormFlushToZero:
  case ExecutionModeSignedZeroInfNanPreserve:
  case ExecutionModeRoundingModeRTE:
  case ExecutionModeRoundingModeRTZ:
  case ExecutionModeRoundingModeRTPINTEL:
  case ExecutionModeRoundingModeRTNINTEL:
  case ExecutionModeFloatingPointModeALTINTEL:
  case ExecutionModeFloatingPointModeIEEEINTEL:
  case ExecutionModeSharedLocalMemorySizeINTEL:
  case ExecutionModeNamedBarrierCountINTEL:
  case ExecutionModeSubgroupSize:
  case ExecutionModeSubgroupsPerWorkgroup:
  case ExecutionModeSubgroupsPerWorkgroupId:
  case ExecutionModeMaxWorkDimINTEL:
  case ExecutionModeNumSIMDWorkitemsINTEL:
  case ExecutionModeSchedulerTargetFmaxMhzINTEL:
  case ExecutionModeRegisterMapInterfaceINTEL:
  case ExecutionModeStreamingInterfaceINTEL:
  case spv::internal::ExecutionModeNamedSubgroupSizeINTEL:
  case ExecutionModeMaximumRegistersINTEL:
  case ExecutionModeMaximumRegistersIdINTEL:
  case ExecutionModeNamedMaximumRegistersINTEL:
    WordLiterals.resize(1);
    break;
  default:
    // Do nothing. Keep this to avoid VS2013 warning.
    break;
  }
  getDecoder(I) >> WordLiterals;
  getOrCreateTarget()->addExecutionMode(Module->add(this));
}

SPIRVForward *SPIRVAnnotationGeneric::getOrCreateTarget() const {
  SPIRVEntry *Entry = nullptr;
  bool Found = Module->exist(Target, &Entry);
  assert((!Found || Entry->getOpCode() == internal::OpForward) &&
         "Annotations only allowed on forward");
  if (!Found)
    Entry = Module->addForward(Target, nullptr);
  return static_cast<SPIRVForward *>(Entry);
}

SPIRVName::SPIRVName(const SPIRVEntry *TheTarget, const std::string &TheStr)
    : SPIRVAnnotation(OpName, TheTarget, getSizeInWords(TheStr) + 2),
      Str(TheStr) {}

void SPIRVName::encode(spv_ostream &O) const { getEncoder(O) << Target << Str; }

void SPIRVName::decode(std::istream &I) {
  getDecoder(I) >> Target >> Str;
  Module->setName(getOrCreateTarget(), Str);
}

void SPIRVName::validate() const {
  assert(WordCount == getSizeInWords(Str) + 2 && "Incorrect word count");
}

_SPIRV_IMP_ENCDEC2(SPIRVString, Id, Str)
_SPIRV_IMP_ENCDEC3(SPIRVMemberName, Target, MemberNumber, Str)

void SPIRVLine::encode(spv_ostream &O) const {
  getEncoder(O) << FileName << Line << Column;
}

void SPIRVLine::decode(std::istream &I) {
  getDecoder(I) >> FileName >> Line >> Column;
}

void SPIRVLine::validate() const {
  assert(OpCode == OpLine);
  assert(WordCount == 4);
  assert(get<SPIRVEntry>(FileName)->getOpCode() == OpString);
  assert(Line != SPIRVWORD_MAX);
  assert(Column != SPIRVWORD_MAX);
  assert(!hasId());
}

void SPIRVMemberName::validate() const {
  assert(OpCode == OpMemberName);
  assert(WordCount == getSizeInWords(Str) + FixedWC);
  assert(get<SPIRVEntry>(Target)->getOpCode() == OpTypeStruct);
  assert(MemberNumber < get<SPIRVTypeStruct>(Target)->getStructMemberCount());
}

SPIRVExtInstImport::SPIRVExtInstImport(SPIRVModule *TheModule, SPIRVId TheId,
                                       const std::string &TheStr)
    : SPIRVEntry(TheModule, 2 + getSizeInWords(TheStr), OC, TheId),
      Str(TheStr) {
  validate();
}

void SPIRVExtInstImport::encode(spv_ostream &O) const {
  getEncoder(O) << Id << Str;
}

void SPIRVExtInstImport::decode(std::istream &I) {
  getDecoder(I) >> Id >> Str;
  Module->importBuiltinSetWithId(Str, Id);
}

void SPIRVExtInstImport::validate() const {
  SPIRVEntry::validate();
  assert(!Str.empty() && "Invalid builtin set");
}

void SPIRVMemoryModel::encode(spv_ostream &O) const {
  getEncoder(O) << Module->getAddressingModel() << Module->getMemoryModel();
}

void SPIRVMemoryModel::decode(std::istream &I) {
  SPIRVAddressingModelKind AddrModel;
  SPIRVMemoryModelKind MemModel;
  getDecoder(I) >> AddrModel >> MemModel;
  Module->setAddressingModel(AddrModel);
  Module->setMemoryModel(MemModel);
}

void SPIRVMemoryModel::validate() const {
  auto AM = Module->getAddressingModel();
  auto MM = Module->getMemoryModel();
  SPIRVCK(isValid(AM), InvalidAddressingModel,
          "Actual is " + std::to_string(AM));
  SPIRVCK(isValid(MM), InvalidMemoryModel, "Actual is " + std::to_string(MM));
}

void SPIRVSource::encode(spv_ostream &O) const {
  SPIRVWord Ver = SPIRVWORD_MAX;
  auto Language = Module->getSourceLanguage(&Ver);
  getEncoder(O) << Language << Ver;
}

void SPIRVSource::decode(std::istream &I) {
  SourceLanguage Lang = SourceLanguageUnknown;
  SPIRVWord Ver = SPIRVWORD_MAX;
  getDecoder(I) >> Lang >> Ver;
  Module->setSourceLanguage(Lang, Ver);
}

SPIRVSourceExtension::SPIRVSourceExtension(SPIRVModule *M,
                                           const std::string &SS)
    : SPIRVEntryNoId(M, 1 + getSizeInWords(SS)), S(SS) {}

void SPIRVSourceExtension::encode(spv_ostream &O) const { getEncoder(O) << S; }

void SPIRVSourceExtension::decode(std::istream &I) {
  getDecoder(I) >> S;
  Module->getSourceExtension().insert(S);
}

SPIRVExtension::SPIRVExtension(SPIRVModule *M, const std::string &SS)
    : SPIRVEntryNoId(M, 1 + getSizeInWords(SS)), S(SS) {}

void SPIRVExtension::encode(spv_ostream &O) const { getEncoder(O) << S; }

void SPIRVExtension::decode(std::istream &I) {
  getDecoder(I) >> S;
  Module->getExtension().insert(S);
}

SPIRVCapability::SPIRVCapability(SPIRVModule *M, SPIRVCapabilityKind K)
    : SPIRVEntryNoId(M, 2), Kind(K) {
  updateModuleVersion();
}

void SPIRVCapability::encode(spv_ostream &O) const { getEncoder(O) << Kind; }

void SPIRVCapability::decode(std::istream &I) {
  getDecoder(I) >> Kind;
  Module->addCapability(Kind);
}

template <spv::Op OC> void SPIRVContinuedInstINTELBase<OC>::validate() const {
  SPIRVEntry::validate();
}

template <spv::Op OC>
void SPIRVContinuedInstINTELBase<OC>::encode(spv_ostream &O) const {
  SPIRVEntry::getEncoder(O) << (Elements);
}
template <spv::Op OC>
void SPIRVContinuedInstINTELBase<OC>::decode(std::istream &I) {
  SPIRVEntry::getDecoder(I) >> (Elements);
}

SPIRVType *SPIRVTypeStructContinuedINTEL::getMemberType(size_t I) const {
  return static_cast<SPIRVType *>(SPIRVEntry::getEntry(Elements[I]));
}

void SPIRVModuleProcessed::validate() const {
  assert(WordCount == FixedWC + getSizeInWords(ProcessStr) &&
         "Incorrect word count in OpModuleProcessed");
}

void SPIRVModuleProcessed::encode(spv_ostream &O) const {
  getEncoder(O) << ProcessStr;
}

void SPIRVModuleProcessed::decode(std::istream &I) {
  getDecoder(I) >> ProcessStr;
  Module->addModuleProcessed(ProcessStr);
}

std::string SPIRVModuleProcessed::getProcessStr() { return ProcessStr; }

} // namespace SPIRV