Autodiff Coverage for full test suite

Coverage Report

Created: 2023-11-30 18:54

/Volumes/compiler/apple/swift/lib/SIL/Parser/ParseSIL.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ParseSIL.cpp - SIL File Parsing logic ----------------------------===//
2
//
3
// This source file is part of the Swift.org open source project
4
//
5
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6
// Licensed under Apache License v2.0 with Runtime Library Exception
7
//
8
// See https://swift.org/LICENSE.txt for license information
9
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "SILParserFunctionBuilder.h"
14
#include "SILParserState.h"
15
#include "swift/AST/ASTWalker.h"
16
#include "swift/AST/DiagnosticsParse.h"
17
#include "swift/AST/ExistentialLayout.h"
18
#include "swift/AST/GenericEnvironment.h"
19
#include "swift/AST/NameLookup.h"
20
#include "swift/AST/NameLookupRequests.h"
21
#include "swift/AST/ProtocolConformance.h"
22
#include "swift/AST/SILGenRequests.h"
23
#include "swift/AST/SourceFile.h"
24
#include "swift/AST/TypeCheckRequests.h"
25
#include "swift/Basic/Defer.h"
26
#include "swift/Demangling/Demangle.h"
27
#include "swift/Parse/Lexer.h"
28
#include "swift/Parse/ParseSILSupport.h"
29
#include "swift/Parse/Parser.h"
30
#include "swift/SIL/AbstractionPattern.h"
31
#include "swift/SIL/InstructionUtils.h"
32
#include "swift/SIL/OwnershipUtils.h"
33
#include "swift/SIL/ParseTestSpecification.h"
34
#include "swift/SIL/SILArgument.h"
35
#include "swift/SIL/SILBuilder.h"
36
#include "swift/SIL/SILDebugScope.h"
37
#include "swift/SIL/SILModule.h"
38
#include "swift/SIL/SILMoveOnlyDeinit.h"
39
#include "swift/SIL/SILUndef.h"
40
#include "swift/SIL/TypeLowering.h"
41
#include "swift/Sema/SILTypeResolutionContext.h"
42
#include "swift/Subsystems.h"
43
#include "llvm/ADT/StringSwitch.h"
44
#include "llvm/Support/CommandLine.h"
45
#include "llvm/Support/SaveAndRestore.h"
46
47
using namespace swift;
48
49
static llvm::cl::opt<bool>
50
ParseSerializedSIL("parse-serialized-sil",
51
                   llvm::cl::desc("Parse the output of a serialized module"));
52
53
static llvm::cl::opt<bool>
54
    DisableInputVerify("sil-disable-input-verify",
55
                       llvm::cl::desc("Disable verification of input SIL"),
56
                       llvm::cl::init(false));
57
58
// Option for testing -silgen-cleanup -enable-complete-ossa
59
static llvm::cl::opt<bool>
60
ParseIncompleteOSSA("parse-incomplete-ossa",
61
                    llvm::cl::desc("Parse OSSA with incomplete lifetimes"));
62
63
static llvm::cl::opt<bool> DisablePopulateOwnershipFlags(
64
    "disable-populate-ownership-flags",
65
    llvm::cl::desc("Disable populating ownership flags"),
66
    llvm::cl::init(false));
67
68
//===----------------------------------------------------------------------===//
69
// SILParserState implementation
70
//===----------------------------------------------------------------------===//
71
72
3.80k
SILParserState::~SILParserState() {
73
3.80k
  if (!ForwardRefFns.empty()) {
74
3
    for (auto Entry : ForwardRefFns) {
75
3
      if (Entry.second.Loc.isValid()) {
76
3
        M.getASTContext().Diags.diagnose(Entry.second.Loc,
77
3
                                         diag::sil_use_of_undefined_value,
78
3
                                         Entry.first.str());
79
3
      }
80
3
    }
81
3
  }
82
83
  // Turn any debug-info-only function declarations into zombies.
84
3.80k
  for (auto *Fn : PotentialZombieFns)
85
162
    if (Fn->isExternalDeclaration()) {
86
3
      Fn->setInlined();
87
3
      M.eraseFunction(Fn);
88
3
    }
89
3.80k
}
90
91
std::unique_ptr<SILModule>
92
ParseSILModuleRequest::evaluate(Evaluator &evaluator,
93
3.80k
                                ASTLoweringDescriptor desc) const {
94
3.80k
  auto *SF = desc.getSourceFileToParse();
95
3.80k
  assert(SF);
96
97
0
  auto bufferID = SF->getBufferID();
98
3.80k
  assert(bufferID);
99
100
  // For leak detection.
101
0
  SILInstruction::resetInstructionCounts();
102
103
3.80k
  auto silMod = SILModule::createEmptyModule(desc.context, desc.conv,
104
3.80k
                                             desc.opts);
105
3.80k
  SILParserState parserState(*silMod.get());
106
3.80k
  Parser parser(*bufferID, *SF, &parserState);
107
3.80k
  PrettyStackTraceParser StackTrace(parser);
108
109
3.80k
  if (ParseSerializedSIL) {
110
72
    silMod.get()->setParsedAsSerializedSIL();
111
72
  }
112
113
3.80k
  auto hadError = parser.parseTopLevelSIL();
114
3.80k
  if (hadError) {
115
    // The rest of the SIL pipeline expects well-formed SIL, so if we encounter
116
    // a parsing error, just return an empty SIL module.
117
    //
118
    // Because the SIL parser's notion of failing with an error is distinct from
119
    // the ASTContext's notion of having emitted a diagnostic, it's possible for
120
    // the parser to fail silently without emitting a diagnostic. This assertion
121
    // ensures that +asserts builds will fail fast. If you crash here, please go
122
    // back and add a diagnostic after identifying where the SIL parser failed.
123
18
    assert(SF->getASTContext().hadError() &&
124
18
           "Failed to parse SIL but did not emit any errors!");
125
0
    return SILModule::createEmptyModule(desc.context, desc.conv, desc.opts);
126
18
  }
127
  // If SIL parsing succeeded, verify the generated SIL.
128
3.78k
  if (!parser.Diags.hadAnyError() && !DisableInputVerify) {
129
3.77k
    silMod->verify(/*SingleFunction=*/true, !ParseIncompleteOSSA);
130
3.77k
  }
131
132
3.78k
  return silMod;
133
3.80k
}
134
135
//===----------------------------------------------------------------------===//
136
// SILParser
137
//===----------------------------------------------------------------------===//
138
139
namespace {
140
  struct ParsedSubstitution {
141
    SourceLoc loc;
142
    Type replacement;
143
  };
144
145
  struct ParsedSpecAttr {
146
    ArrayRef<RequirementRepr> requirements;
147
    bool exported;
148
    SILSpecializeAttr::SpecializationKind kind;
149
    SILFunction *target = nullptr;
150
    Identifier spiGroupID;
151
    ModuleDecl *spiModule;
152
    AvailabilityContext availability = AvailabilityContext::alwaysAvailable();
153
  };
154
} // namespace
155
156
namespace swift {
157
  /// The parser for an individual SIL function.
158
  class SILParser {
159
    friend SILParserState;
160
  public:
161
    Parser &P;
162
    SILModule &SILMod;
163
    SILParserState &TUState;
164
    SILFunction *F = nullptr;
165
    GenericSignature ContextGenericSig;
166
    GenericParamList *ContextGenericParams = nullptr;
167
168
  private:
169
    /// HadError - Have we seen an error parsing this function?
170
    bool HadError = false;
171
172
    /// Transient state for parsing a multiple optional attributes
173
    /// in parseSpecificSILInstruction:
174
    ///   <regular syntax>[, keyword1][, keyword2]
175
    bool parsedComma = false;
176
177
    /// Data structures used to perform name lookup of basic blocks.
178
    llvm::DenseMap<Identifier, SILBasicBlock*> BlocksByName;
179
    llvm::DenseMap<SILBasicBlock*,
180
                   Located<Identifier>> UndefinedBlocks;
181
182
    /// The set of opened packs in the function, indexed by UUID.
183
    /// Note that we don't currently support parsing references to
184
    /// opened packs prior to their instruction, although this is
185
    /// theoretically possible if basic blocks are not sorted in
186
    /// dominance order.
187
    SILTypeResolutionContext::OpenedPackElementsMap OpenedPackElements;
188
189
    /// Data structures used to perform name lookup for local values.
190
    llvm::StringMap<ValueBase*> LocalValues;
191
    llvm::StringMap<llvm::SmallVector<TestSpecificationInst *>>
192
        TestSpecsWithRefs;
193
    llvm::StringMap<SourceLoc> ForwardRefLocalValues;
194
195
    Type performTypeResolution(TypeRepr *TyR, bool IsSILType,
196
                               GenericSignature GenericSig,
197
                               GenericParamList *GenericParams);
198
199
    void convertRequirements(ArrayRef<RequirementRepr> From,
200
                             SmallVectorImpl<Requirement> &To,
201
                             SmallVectorImpl<Type> &typeErasedParams);
202
203
    ProtocolConformanceRef parseProtocolConformanceHelper(
204
        ProtocolDecl *&proto,
205
        GenericSignature GenericSig,
206
        GenericParamList *WitnessParams);
207
208
  public:
209
    SILParser(Parser &P)
210
        : P(P), SILMod(static_cast<SILParserState *>(P.SIL)->M),
211
58.5k
          TUState(*static_cast<SILParserState *>(P.SIL)) {}
212
213
    ~SILParser();
214
215
    /// diagnoseProblems - After a function is fully parse, emit any diagnostics
216
    /// for errors and return true if there were any.
217
    bool diagnoseProblems();
218
219
    /// getGlobalNameForReference - Given a reference to a global name, look it
220
    /// up and return an appropriate SIL function.
221
    SILFunction *getGlobalNameForReference(Identifier Name,
222
                                           CanSILFunctionType Ty,
223
                                           SourceLoc Loc,
224
                                           bool IgnoreFwdRef = false);
225
    /// getGlobalNameForDefinition - Given a definition of a global name, look
226
    /// it up and return an appropriate SIL function.
227
    SILFunction *getGlobalNameForDefinition(Identifier Name,
228
                                            CanSILFunctionType Ty,
229
                                            SourceLoc Loc);
230
231
    /// getBBForDefinition - Return the SILBasicBlock for a definition of the
232
    /// specified block.
233
    SILBasicBlock *getBBForDefinition(Identifier Name, SourceLoc Loc);
234
    
235
    /// getBBForReference - return the SILBasicBlock of the specified name.  The
236
    /// source location is used to diagnose a failure if the block ends up never
237
    /// being defined.
238
    SILBasicBlock *getBBForReference(Identifier Name, SourceLoc Loc);
239
240
    struct UnresolvedValueName {
241
      StringRef Name;
242
      SourceLoc NameLoc;
243
244
362k
      bool isUndef() const { return Name == "undef"; }
245
    };
246
247
    /// getLocalValue - Get a reference to a local value with the specified name
248
    /// and type.
249
    SILValue getLocalValue(UnresolvedValueName Name, SILType Type,
250
                           SILLocation L, SILBuilder &B);
251
252
    /// setLocalValue - When an instruction or block argument is defined, this
253
    /// method is used to register it and update our symbol table.
254
    void setLocalValue(ValueBase *Value, StringRef Name, SourceLoc NameLoc);
255
256
0
    SILDebugLocation getDebugLoc(SILBuilder & B, SILLocation Loc) {
257
0
      return SILDebugLocation(Loc, F->getDebugScope());
258
0
    }
259
260
    /// @{ Primitive parsing.
261
262
    /// \verbatim
263
    ///   sil-identifier ::= [A-Za-z_0-9]+
264
    /// \endverbatim
265
    bool parseSILIdentifier(Identifier &Result, SourceLoc &Loc,
266
                            const Diagnostic &D);
267
268
    template<typename ...DiagArgTypes, typename ...ArgTypes>
269
    bool parseSILIdentifier(Identifier &Result, Diag<DiagArgTypes...> ID,
270
101k
                            ArgTypes... Args) {
271
101k
      SourceLoc L;
272
101k
      return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
273
101k
    }
274
275
    template <typename T, typename... DiagArgTypes, typename... ArgTypes>
276
    bool parseSILIdentifierSwitch(T &Result, ArrayRef<StringRef> Strings,
277
15.3k
                                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
278
15.3k
      Identifier TmpResult;
279
15.3k
      SourceLoc L;
280
15.3k
      if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
281
0
        return true;
282
0
      }
283
284
15.3k
      auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
285
15.3k
      if (Iter == Strings.end()) {
286
0
        P.diagnose(P.Tok, Diagnostic(ID, Args...));
287
0
        return true;
288
0
      }
289
290
15.3k
      Result = T(*Iter);
291
15.3k
      return false;
292
15.3k
    }
_ZN5swift9SILParser24parseSILIdentifierSwitchINS_18ValueOwnershipKindEJEJEEEbRT_N4llvm8ArrayRefINS5_9StringRefEEENS_4DiagIJDpT0_EEEDpT1_
Line
Count
Source
277
14.9k
                                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
278
14.9k
      Identifier TmpResult;
279
14.9k
      SourceLoc L;
280
14.9k
      if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
281
0
        return true;
282
0
      }
283
284
14.9k
      auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
285
14.9k
      if (Iter == Strings.end()) {
286
0
        P.diagnose(P.Tok, Diagnostic(ID, Args...));
287
0
        return true;
288
0
      }
289
290
14.9k
      Result = T(*Iter);
291
14.9k
      return false;
292
14.9k
    }
_ZN5swift9SILParser24parseSILIdentifierSwitchINS_41NormalDifferentiableFunctionTypeComponentEJEJEEEbRT_N4llvm8ArrayRefINS5_9StringRefEEENS_4DiagIJDpT0_EEEDpT1_
Line
Count
Source
277
144
                                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
278
144
      Identifier TmpResult;
279
144
      SourceLoc L;
280
144
      if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
281
0
        return true;
282
0
      }
283
284
144
      auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
285
144
      if (Iter == Strings.end()) {
286
0
        P.diagnose(P.Tok, Diagnostic(ID, Args...));
287
0
        return true;
288
0
      }
289
290
144
      Result = T(*Iter);
291
144
      return false;
292
144
    }
_ZN5swift9SILParser24parseSILIdentifierSwitchINS_41LinearDifferentiableFunctionTypeComponentEJEJEEEbRT_N4llvm8ArrayRefINS5_9StringRefEEENS_4DiagIJDpT0_EEEDpT1_
Line
Count
Source
277
24
                                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
278
24
      Identifier TmpResult;
279
24
      SourceLoc L;
280
24
      if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
281
0
        return true;
282
0
      }
283
284
24
      auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
285
24
      if (Iter == Strings.end()) {
286
0
        P.diagnose(P.Tok, Diagnostic(ID, Args...));
287
0
        return true;
288
0
      }
289
290
24
      Result = T(*Iter);
291
24
      return false;
292
24
    }
_ZN5swift9SILParser24parseSILIdentifierSwitchINS_36DifferentiabilityWitnessFunctionKindEJEJEEEbRT_N4llvm8ArrayRefINS5_9StringRefEEENS_4DiagIJDpT0_EEEDpT1_
Line
Count
Source
277
208
                                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
278
208
      Identifier TmpResult;
279
208
      SourceLoc L;
280
208
      if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
281
0
        return true;
282
0
      }
283
284
208
      auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
285
208
      if (Iter == Strings.end()) {
286
0
        P.diagnose(P.Tok, Diagnostic(ID, Args...));
287
0
        return true;
288
0
      }
289
290
208
      Result = T(*Iter);
291
208
      return false;
292
208
    }
293
294
    template<typename ...DiagArgTypes, typename ...ArgTypes>
295
    bool parseSILIdentifier(Identifier &Result, SourceLoc &L,
296
529k
                            Diag<DiagArgTypes...> ID, ArgTypes... Args) {
297
529k
      return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
298
529k
    }
_ZN5swift9SILParser18parseSILIdentifierIJN4llvm9StringRefEEJS3_EEEbRNS_10IdentifierERNS_9SourceLocENS_4DiagIJDpT_EEEDpT0_
Line
Count
Source
296
13.9k
                            Diag<DiagArgTypes...> ID, ArgTypes... Args) {
297
13.9k
      return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
298
13.9k
    }
_ZN5swift9SILParser18parseSILIdentifierIJEJEEEbRNS_10IdentifierERNS_9SourceLocENS_4DiagIJDpT_EEEDpT0_
Line
Count
Source
296
487k
                            Diag<DiagArgTypes...> ID, ArgTypes... Args) {
297
487k
      return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
298
487k
    }
_ZN5swift9SILParser18parseSILIdentifierIJN4llvm9StringRefEEJPKcEEEbRNS_10IdentifierERNS_9SourceLocENS_4DiagIJDpT_EEEDpT0_
Line
Count
Source
296
27.4k
                            Diag<DiagArgTypes...> ID, ArgTypes... Args) {
297
27.4k
      return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
298
27.4k
    }
299
300
    template <typename T>
301
    bool parseSILQualifier(
302
        llvm::Optional<T> &result,
303
        llvm::function_ref<llvm::Optional<T>(StringRef)> parseName);
304
305
    bool parseVerbatim(StringRef identifier);
306
307
    template <typename T>
308
6.72k
    bool parseInteger(T &Result, const Diagnostic &D) {
309
6.72k
      if (!P.Tok.is(tok::integer_literal)) {
310
0
        P.diagnose(P.Tok, D);
311
0
        return true;
312
0
      }
313
6.72k
      bool error = parseIntegerLiteral(P.Tok.getText(), 0, Result);
314
6.72k
      P.consumeToken(tok::integer_literal);
315
6.72k
      return error;
316
6.72k
    }
_ZN5swift9SILParser12parseIntegerIyEEbRT_RKNS_10DiagnosticE
Line
Count
Source
308
630
    bool parseInteger(T &Result, const Diagnostic &D) {
309
630
      if (!P.Tok.is(tok::integer_literal)) {
310
0
        P.diagnose(P.Tok, D);
311
0
        return true;
312
0
      }
313
630
      bool error = parseIntegerLiteral(P.Tok.getText(), 0, Result);
314
630
      P.consumeToken(tok::integer_literal);
315
630
      return error;
316
630
    }
_ZN5swift9SILParser12parseIntegerIxEEbRT_RKNS_10DiagnosticE
Line
Count
Source
308
24
    bool parseInteger(T &Result, const Diagnostic &D) {
309
24
      if (!P.Tok.is(tok::integer_literal)) {
310
0
        P.diagnose(P.Tok, D);
311
0
        return true;
312
0
      }
313
24
      bool error = parseIntegerLiteral(P.Tok.getText(), 0, Result);
314
24
      P.consumeToken(tok::integer_literal);
315
24
      return error;
316
24
    }
_ZN5swift9SILParser12parseIntegerIjEEbRT_RKNS_10DiagnosticE
Line
Count
Source
308
6.06k
    bool parseInteger(T &Result, const Diagnostic &D) {
309
6.06k
      if (!P.Tok.is(tok::integer_literal)) {
310
0
        P.diagnose(P.Tok, D);
311
0
        return true;
312
0
      }
313
6.06k
      bool error = parseIntegerLiteral(P.Tok.getText(), 0, Result);
314
6.06k
      P.consumeToken(tok::integer_literal);
315
6.06k
      return error;
316
6.06k
    }
317
318
    template <typename T>
319
17.8k
    bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) {
320
17.8k
      text = prepareIntegerLiteralForParsing(text);
321
17.8k
      return text.getAsInteger(radix, result);
322
17.8k
    }
_ZN5swift9SILParser19parseIntegerLiteralIyEEbN4llvm9StringRefEjRT_
Line
Count
Source
319
630
    bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) {
320
630
      text = prepareIntegerLiteralForParsing(text);
321
630
      return text.getAsInteger(radix, result);
322
630
    }
_ZN5swift9SILParser19parseIntegerLiteralIxEEbN4llvm9StringRefEjRT_
Line
Count
Source
319
24
    bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) {
320
24
      text = prepareIntegerLiteralForParsing(text);
321
24
      return text.getAsInteger(radix, result);
322
24
    }
_ZN5swift9SILParser19parseIntegerLiteralItEEbN4llvm9StringRefEjRT_
Line
Count
Source
319
3.32k
    bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) {
320
3.32k
      text = prepareIntegerLiteralForParsing(text);
321
3.32k
      return text.getAsInteger(radix, result);
322
3.32k
    }
_ZN5swift9SILParser19parseIntegerLiteralIjEEbN4llvm9StringRefEjRT_
Line
Count
Source
319
13.8k
    bool parseIntegerLiteral(StringRef text, unsigned radix, T &result) {
320
13.8k
      text = prepareIntegerLiteralForParsing(text);
321
13.8k
      return text.getAsInteger(radix, result);
322
13.8k
    }
323
324
38.4k
    StringRef prepareIntegerLiteralForParsing(StringRef text) {
325
      // tok::integer_literal can contain characters that the library
326
      // parsing routines don't expect.
327
38.4k
      if (text.contains('_'))
328
6
        text = P.copyAndStripUnderscores(text);
329
38.4k
      return text;
330
38.4k
    }
331
332
    /// @}
333
334
    /// @{ Type parsing.
335
    bool parseASTType(CanType &result,
336
                      GenericSignature genericSig=GenericSignature(),
337
                      GenericParamList *genericParams=nullptr,
338
                      bool forceContextualType = false);
339
    bool parseASTType(CanType &result,
340
                      SourceLoc &TypeLoc,
341
                      GenericSignature genericSig=GenericSignature(),
342
                      GenericParamList *genericParams=nullptr,
343
1.48k
                      bool forceContextualType = false) {
344
1.48k
      TypeLoc = P.Tok.getLoc();
345
1.48k
      return parseASTType(result, genericSig, genericParams,
346
1.48k
                          forceContextualType);
347
1.48k
    }
348
349
189
    bool parseASTPackType(CanPackType &result) {
350
189
      SourceLoc loc;
351
189
      CanType rawType;
352
189
      if (parseASTType(rawType, loc))
353
0
        return true;
354
189
      result = dyn_cast<PackType>(rawType);
355
189
      if (!result) {
356
0
        P.diagnose(loc, diag::expected_sil_type_kind, "match $Pack{...}");
357
0
        return true;
358
0
      }
359
189
      return false;
360
189
    }
361
362
    llvm::Optional<StringRef>
363
56.3k
    parseOptionalAttribute(ArrayRef<StringRef> expected) {
364
      // We parse here @ <identifier>.
365
56.3k
      if (P.Tok.getKind() != tok::at_sign)
366
41.3k
        return llvm::None;
367
368
15.0k
      auto name = P.peekToken().getText();
369
15.0k
      if (!is_contained(expected, name))
370
14.6k
        return llvm::None;
371
372
      // Ok, we can do this.
373
369
      P.consumeToken(tok::at_sign);
374
369
      P.consumeToken(tok::identifier);
375
369
      return name;
376
15.0k
    }
377
378
29.7k
    bool parseSILOwnership(ValueOwnershipKind &OwnershipKind) {
379
      // We parse here @ <identifier>.
380
29.7k
      if (!P.consumeIf(tok::at_sign)) {
381
        // If we fail, we must have @any ownership. We check elsewhere in the
382
        // parser that this matches what the function signature wants.
383
14.7k
        OwnershipKind = OwnershipKind::None;
384
14.7k
        return false;
385
14.7k
      }
386
387
14.9k
      StringRef AllOwnershipKinds[4] = {"unowned", "owned", "guaranteed",
388
14.9k
                                        "none"};
389
14.9k
      return parseSILIdentifierSwitch(OwnershipKind, AllOwnershipKinds,
390
14.9k
                                      diag::expected_sil_value_ownership_kind);
391
29.7k
    }
392
    void bindSILGenericParams(TypeRepr *TyR);
393
    bool parseSILType(SILType &Result,
394
                      GenericSignature &parsedGenericSig,
395
                      GenericParamList *&parsedGenericParams,
396
                      bool IsFuncDecl=false,
397
                      GenericSignature parentGenericSig=GenericSignature(),
398
                      GenericParamList *parentGenericParams=nullptr);
399
431k
    bool parseSILType(SILType &Result) {
400
431k
      GenericSignature IgnoredSig;
401
431k
      GenericParamList *IgnoredParams = nullptr;
402
431k
      return parseSILType(Result, IgnoredSig, IgnoredParams);
403
431k
    }
404
2.86k
    bool parseSILType(SILType &Result, SourceLoc &TypeLoc) {
405
2.86k
      TypeLoc = P.Tok.getLoc();
406
2.86k
      return parseSILType(Result);
407
2.86k
    }
408
    bool parseSILType(SILType &Result, SourceLoc &TypeLoc,
409
                      GenericSignature &parsedGenericSig,
410
                      GenericParamList *&parsedGenericParams,
411
                      GenericSignature parentGenericSig=GenericSignature(),
412
36.0k
                      GenericParamList *parentGenericParams=nullptr) {
413
36.0k
      TypeLoc = P.Tok.getLoc();
414
36.0k
      return parseSILType(Result, parsedGenericSig, parsedGenericParams,
415
36.0k
                          false, parentGenericSig, parentGenericParams);
416
36.0k
    }
417
    /// @}
418
419
    bool parseSILDottedPath(ValueDecl *&Decl,
420
                            SmallVectorImpl<ValueDecl *> &values);
421
14.5k
    bool parseSILDottedPath(ValueDecl *&Decl) {
422
14.5k
      SmallVector<ValueDecl *, 4> values;
423
14.5k
      return parseSILDottedPath(Decl, values);
424
14.5k
    }
425
    bool parseSILDottedPathWithoutPound(ValueDecl *&Decl,
426
                                        SmallVectorImpl<ValueDecl *> &values);
427
30
    bool parseSILDottedPathWithoutPound(ValueDecl *&Decl) {
428
30
      SmallVector<ValueDecl *, 4> values;
429
30
      return parseSILDottedPathWithoutPound(Decl, values);
430
30
    }
431
    /// At the time of calling this function, we may not have the type of the
432
    /// Decl yet. So we return a SILDeclRef on the first lookup result and also
433
    /// return all the lookup results. After parsing the expected type, the
434
    /// caller of this function can choose the one that has the expected type.
435
    bool parseSILDeclRef(SILDeclRef &Result,
436
                         SmallVectorImpl<ValueDecl *> &values);
437
10.0k
    bool parseSILDeclRef(SILDeclRef &Result) {
438
10.0k
      SmallVector<ValueDecl *, 4> values;
439
10.0k
      return parseSILDeclRef(Result, values);
440
10.0k
    }
441
    bool parseSILDeclRef(SILDeclRef &Member, bool FnTypeRequired);
442
    bool parseGlobalName(Identifier &Name);
443
    bool parseValueName(UnresolvedValueName &Name);
444
    bool parseValueRef(SILValue &Result, SILType Ty, SILLocation Loc,
445
                       SILBuilder &B);
446
    bool parseTypedValueRef(SILValue &Result, SourceLoc &Loc, SILBuilder &B);
447
198k
    bool parseTypedValueRef(SILValue &Result, SILBuilder &B) {
448
198k
      SourceLoc Tmp;
449
198k
      return parseTypedValueRef(Result, Tmp, B);
450
198k
    }
451
    bool parseSILOpcode(SILInstructionKind &Opcode, SourceLoc &OpcodeLoc,
452
                        StringRef &OpcodeName);
453
    bool parseSILDebugVar(SILDebugVariable &Var);
454
455
    bool parseSILDebugInfoExpression(SILDebugInfoExpression &DIExpr);
456
457
    /// Parses the basic block arguments as part of branch instruction.
458
    bool parseSILBBArgsAtBranch(SmallVector<SILValue, 6> &Args, SILBuilder &B);
459
460
    bool parseSILLocation(SILLocation &L);
461
    bool parseScopeRef(SILDebugScope *&DS);
462
    bool parseForwardingOwnershipKind(ValueOwnershipKind &forwardingKind);
463
    bool parseSILDebugLocation(SILLocation &L, SILBuilder &B);
464
    bool parseSpecificSILInstruction(SILBuilder &B, SILInstructionKind Opcode,
465
                                     SourceLoc OpcodeLoc, StringRef OpcodeName,
466
                                     SILInstruction *&ResultVal);
467
468
    bool parseSILInstruction(SILBuilder &B);
469
    bool parseCallInstruction(SILLocation InstLoc,
470
                              SILInstructionKind Opcode, SILBuilder &B,
471
                              SILInstruction *&ResultVal);
472
    bool parseSILFunctionRef(SILLocation InstLoc, SILFunction *&ResultFn);
473
474
    bool parseSILBasicBlock(SILBuilder &B);
475
    bool parseKeyPathPatternComponent(KeyPathPatternComponent &component,
476
                                      SmallVectorImpl<SILType> &operandTypes,
477
                                      SourceLoc componentLoc,
478
                                      Identifier componentKind,
479
                                      SILLocation InstLoc,
480
                                      GenericSignature patternSig,
481
                                      GenericParamList *patternParams);
482
    bool isStartOfSILInstruction();
483
484
    bool parseSubstitutions(SmallVectorImpl<ParsedSubstitution> &parsed,
485
                            GenericSignature GenericSig=GenericSignature(),
486
                            GenericParamList *GenericParams=nullptr);
487
488
    ProtocolConformanceRef parseProtocolConformance(
489
        ProtocolDecl *&proto,
490
        GenericSignature &genericSig,
491
        GenericParamList *&genericParams);
492
    ProtocolConformanceRef
493
104
    parseProtocolConformance() {
494
104
      ProtocolDecl *dummy = nullptr;
495
104
      GenericSignature genericSig;
496
104
      GenericParamList *genericParams = nullptr;
497
104
      return parseProtocolConformance(dummy, genericSig, genericParams);
498
104
    }
499
500
    llvm::Optional<llvm::coverage::Counter>
501
    parseSILCoverageExpr(llvm::coverage::CounterExpressionBuilder &Builder);
502
503
    template <class T>
504
    struct ParsedEnum {
505
      llvm::Optional<T> Value;
506
      StringRef Name;
507
      SourceLoc Loc;
508
509
25.8k
      bool isSet() const { return Value.has_value(); }
_ZNK5swift9SILParser10ParsedEnumINS_13SILAccessKindEE5isSetEv
Line
Count
Source
509
4.25k
      bool isSet() const { return Value.has_value(); }
_ZNK5swift9SILParser10ParsedEnumINS_20SILAccessEnforcementEE5isSetEv
Line
Count
Source
509
4.30k
      bool isSet() const { return Value.has_value(); }
_ZNK5swift9SILParser10ParsedEnumIbE5isSetEv
Line
Count
Source
509
17.3k
      bool isSet() const { return Value.has_value(); }
510
21.5k
      T operator*() const { return *Value; }
_ZNK5swift9SILParser10ParsedEnumINS_13SILAccessKindEEdeEv
Line
Count
Source
510
4.25k
      T operator*() const { return *Value; }
_ZNK5swift9SILParser10ParsedEnumINS_20SILAccessEnforcementEEdeEv
Line
Count
Source
510
4.30k
      T operator*() const { return *Value; }
_ZNK5swift9SILParser10ParsedEnumIbEdeEv
Line
Count
Source
510
12.9k
      T operator*() const { return *Value; }
511
    };
512
513
    template <class T>
514
    void setEnum(ParsedEnum<T> &existing,
515
8.92k
                 T value, StringRef name, SourceLoc loc) {
516
8.92k
      if (existing.Value) {
517
0
        if (*existing.Value == value) {
518
0
          P.diagnose(loc, diag::duplicate_attribute, /*modifier*/ 1);
519
0
        } else {
520
0
          P.diagnose(loc, diag::mutually_exclusive_attrs, name,
521
0
                     existing.Name, /*modifier*/ 1);
522
0
        }
523
0
        P.diagnose(existing.Loc, diag::previous_attribute, /*modifier*/ 1);
524
0
      }
525
8.92k
      existing.Value = value;
526
8.92k
      existing.Name = name;
527
8.92k
      existing.Loc = loc;
528
8.92k
    }
_ZN5swift9SILParser7setEnumINS_20SILAccessEnforcementEEEvRNS0_10ParsedEnumIT_EES4_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
515
4.30k
                 T value, StringRef name, SourceLoc loc) {
516
4.30k
      if (existing.Value) {
517
0
        if (*existing.Value == value) {
518
0
          P.diagnose(loc, diag::duplicate_attribute, /*modifier*/ 1);
519
0
        } else {
520
0
          P.diagnose(loc, diag::mutually_exclusive_attrs, name,
521
0
                     existing.Name, /*modifier*/ 1);
522
0
        }
523
0
        P.diagnose(existing.Loc, diag::previous_attribute, /*modifier*/ 1);
524
0
      }
525
4.30k
      existing.Value = value;
526
4.30k
      existing.Name = name;
527
4.30k
      existing.Loc = loc;
528
4.30k
    }
_ZN5swift9SILParser7setEnumINS_13SILAccessKindEEEvRNS0_10ParsedEnumIT_EES4_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
515
4.25k
                 T value, StringRef name, SourceLoc loc) {
516
4.25k
      if (existing.Value) {
517
0
        if (*existing.Value == value) {
518
0
          P.diagnose(loc, diag::duplicate_attribute, /*modifier*/ 1);
519
0
        } else {
520
0
          P.diagnose(loc, diag::mutually_exclusive_attrs, name,
521
0
                     existing.Name, /*modifier*/ 1);
522
0
        }
523
0
        P.diagnose(existing.Loc, diag::previous_attribute, /*modifier*/ 1);
524
0
      }
525
4.25k
      existing.Value = value;
526
4.25k
      existing.Name = name;
527
4.25k
      existing.Loc = loc;
528
4.25k
    }
_ZN5swift9SILParser7setEnumIbEEvRNS0_10ParsedEnumIT_EES3_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
515
363
                 T value, StringRef name, SourceLoc loc) {
516
363
      if (existing.Value) {
517
0
        if (*existing.Value == value) {
518
0
          P.diagnose(loc, diag::duplicate_attribute, /*modifier*/ 1);
519
0
        } else {
520
0
          P.diagnose(loc, diag::mutually_exclusive_attrs, name,
521
0
                     existing.Name, /*modifier*/ 1);
522
0
        }
523
0
        P.diagnose(existing.Loc, diag::previous_attribute, /*modifier*/ 1);
524
0
      }
525
363
      existing.Value = value;
526
363
      existing.Name = name;
527
363
      existing.Loc = loc;
528
363
    }
529
530
    template <class T>
531
    void maybeSetEnum(bool allowed, ParsedEnum<T> &existing,
532
8.92k
                      T value, StringRef name, SourceLoc loc) {
533
8.92k
      if (allowed)
534
8.92k
        setEnum(existing, value, name, loc);
535
0
      else
536
0
        P.diagnose(loc, diag::unknown_attribute, name);
537
8.92k
    }
_ZN5swift9SILParser12maybeSetEnumINS_20SILAccessEnforcementEEEvbRNS0_10ParsedEnumIT_EES4_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
532
4.30k
                      T value, StringRef name, SourceLoc loc) {
533
4.30k
      if (allowed)
534
4.30k
        setEnum(existing, value, name, loc);
535
0
      else
536
0
        P.diagnose(loc, diag::unknown_attribute, name);
537
4.30k
    }
_ZN5swift9SILParser12maybeSetEnumINS_13SILAccessKindEEEvbRNS0_10ParsedEnumIT_EES4_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
532
4.25k
                      T value, StringRef name, SourceLoc loc) {
533
4.25k
      if (allowed)
534
4.25k
        setEnum(existing, value, name, loc);
535
0
      else
536
0
        P.diagnose(loc, diag::unknown_attribute, name);
537
4.25k
    }
_ZN5swift9SILParser12maybeSetEnumIbEEvbRNS0_10ParsedEnumIT_EES3_N4llvm9StringRefENS_9SourceLocE
Line
Count
Source
532
363
                      T value, StringRef name, SourceLoc loc) {
533
363
      if (allowed)
534
363
        setEnum(existing, value, name, loc);
535
0
      else
536
0
        P.diagnose(loc, diag::unknown_attribute, name);
537
363
    }
538
  };
539
} // namespace swift
540
541
bool SILParser::parseSILIdentifier(Identifier &Result, SourceLoc &Loc,
542
645k
                                   const Diagnostic &D) {
543
645k
  switch (P.Tok.getKind()) {
544
635k
  case tok::identifier:
545
635k
  case tok::dollarident:
546
635k
    Result = P.Context.getIdentifier(P.Tok.getText());
547
635k
    break;
548
176
  case tok::string_literal: {
549
    // Drop the double quotes.
550
176
    StringRef rawString = P.Tok.getText().drop_front().drop_back();
551
176
    Result = P.Context.getIdentifier(rawString);
552
176
    break;
553
635k
  }
554
0
  case tok::oper_binary_unspaced:  // fixme?
555
0
  case tok::oper_binary_spaced:
556
6.71k
  case tok::kw_init:
557
    // A binary operator or `init` can be part of a SILDeclRef.
558
6.71k
    Result = P.Context.getIdentifier(P.Tok.getText());
559
6.71k
    break;
560
3.78k
  default:
561
    // If it's some other keyword, grab an identifier for it.
562
3.78k
    if (P.Tok.isKeyword()) {
563
3.78k
      Result = P.Context.getIdentifier(P.Tok.getText());
564
3.78k
      break;
565
3.78k
    }
566
0
    P.diagnose(P.Tok, D);
567
0
    return true;
568
645k
  }
569
570
645k
  Loc = P.Tok.getLoc();
571
645k
  P.consumeToken();
572
645k
  return false;
573
645k
}
574
575
13.9k
bool SILParser::parseVerbatim(StringRef name) {
576
13.9k
  Identifier tok;
577
13.9k
  SourceLoc loc;
578
579
13.9k
  if (parseSILIdentifier(tok, loc, diag::expected_tok_in_sil_instr, name)) {
580
0
    return true;
581
0
  }
582
13.9k
  if (tok.str() != name) {
583
0
    P.diagnose(loc, diag::expected_tok_in_sil_instr, name);
584
0
    return true;
585
0
  }
586
13.9k
  return false;
587
13.9k
}
588
589
58.5k
SILParser::~SILParser() {
590
58.5k
  for (auto &Entry : ForwardRefLocalValues) {
591
9
    if (ValueBase *dummyVal = LocalValues[Entry.first()]) {
592
9
      dummyVal->replaceAllUsesWith(SILUndef::get(dummyVal->getType(), SILMod));
593
9
      ::delete cast<PlaceholderValue>(dummyVal);
594
9
    }
595
9
  }
596
58.5k
}
597
598
599
/// diagnoseProblems - After a function is fully parse, emit any diagnostics
600
/// for errors and return true if there were any.
601
54.5k
bool SILParser::diagnoseProblems() {
602
  // Check for any uses of basic blocks that were not defined.
603
54.5k
  if (!UndefinedBlocks.empty()) {
604
    // FIXME: These are going to come out in nondeterministic order.
605
0
    for (auto Entry : UndefinedBlocks)
606
0
      P.diagnose(Entry.second.Loc, diag::sil_undefined_basicblock_use,
607
0
                 Entry.second.Item);
608
609
0
    HadError = true;
610
0
  }
611
  
612
54.5k
  if (!ForwardRefLocalValues.empty()) {
613
    // FIXME: These are going to come out in nondeterministic order.
614
6
    for (auto &Entry : ForwardRefLocalValues)
615
6
      P.diagnose(Entry.second, diag::sil_use_of_undefined_value,
616
6
                 Entry.first());
617
6
    HadError = true;
618
6
  }
619
  
620
54.5k
  return HadError;
621
54.5k
}
622
623
/// getGlobalNameForDefinition - Given a definition of a global name, look
624
/// it up and return an appropriate SIL function.
625
SILFunction *SILParser::getGlobalNameForDefinition(Identifier name,
626
                                                   CanSILFunctionType ty,
627
54.6k
                                                   SourceLoc sourceLoc) {
628
54.6k
  SILParserFunctionBuilder builder(SILMod);
629
54.6k
  auto silLoc = RegularLocation(sourceLoc);
630
631
  // Check to see if a function of this name has been forward referenced.  If so
632
  // complete the forward reference.
633
54.6k
  auto iter = TUState.ForwardRefFns.find(name);
634
54.6k
  if (iter != TUState.ForwardRefFns.end()) {
635
4.21k
    SILFunction *fn = iter->second.Item;
636
637
    // Verify that the types match up.
638
4.21k
    if (fn->getLoweredFunctionType() != ty) {
639
3
      P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(),
640
3
                 fn->getLoweredFunctionType(), ty);
641
3
      P.diagnose(iter->second.Loc, diag::sil_prior_reference);
642
3
      fn = builder.createFunctionForForwardReference("" /*name*/, ty, silLoc);
643
3
    }
644
645
4.21k
    assert(fn->isExternalDeclaration() && "Forward defns cannot have bodies!");
646
0
    TUState.ForwardRefFns.erase(iter);
647
648
    // Move the function to this position in the module.
649
    //
650
    // FIXME: Should we move this functionality into SILParserFunctionBuilder?
651
4.21k
    SILMod.getFunctionList().remove(fn);
652
4.21k
    SILMod.getFunctionList().push_back(fn);
653
654
4.21k
    return fn;
655
4.21k
  }
656
657
  // If we don't have a forward reference, make sure the function hasn't been
658
  // defined already.
659
50.4k
  if (SILMod.lookUpFunction(name.str()) != nullptr) {
660
3
    P.diagnose(sourceLoc, diag::sil_value_redefinition, name.str());
661
3
    return builder.createFunctionForForwardReference("" /*name*/, ty, silLoc);
662
3
  }
663
664
  // Otherwise, this definition is the first use of this name.
665
50.4k
  return builder.createFunctionForForwardReference(name.str(), ty, silLoc);
666
50.4k
}
667
668
/// getGlobalNameForReference - Given a reference to a global name, look it
669
/// up and return an appropriate SIL function.
670
SILFunction *SILParser::getGlobalNameForReference(Identifier name,
671
                                                  CanSILFunctionType funcTy,
672
                                                  SourceLoc sourceLoc,
673
30.3k
                                                  bool ignoreFwdRef) {
674
30.3k
  SILParserFunctionBuilder builder(SILMod);
675
30.3k
  auto silLoc = RegularLocation(sourceLoc);
676
677
  // Check to see if we have a function by this name already.
678
30.3k
  if (SILFunction *fn = SILMod.lookUpFunction(name.str())) {
679
    // If so, check for matching types.
680
26.1k
    if (fn->getLoweredFunctionType() == funcTy) {
681
26.1k
      return fn;
682
26.1k
    }
683
684
3
    P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(),
685
3
               fn->getLoweredFunctionType(), funcTy);
686
687
3
    return builder.createFunctionForForwardReference("" /*name*/, funcTy,
688
3
                                                     silLoc);
689
26.1k
  }
690
  
691
  // If we didn't find a function, create a new one - it must be a forward
692
  // reference.
693
4.21k
  auto *fn =
694
4.21k
      builder.createFunctionForForwardReference(name.str(), funcTy, silLoc);
695
4.21k
  TUState.ForwardRefFns[name] = {fn, ignoreFwdRef ? SourceLoc() : sourceLoc};
696
4.21k
  return fn;
697
30.3k
}
698
699
700
/// getBBForDefinition - Return the SILBasicBlock for a definition of the
701
/// specified block.
702
237k
SILBasicBlock *SILParser::getBBForDefinition(Identifier Name, SourceLoc Loc) {
703
  // If there was no name specified for this block, just create a new one.
704
237k
  if (Name.empty())
705
1.62k
    return F->createBasicBlock();
706
707
236k
  SILBasicBlock *&BB = BlocksByName[Name];
708
  // If the block has never been named yet, just create it.
709
236k
  if (BB == nullptr)
710
42.2k
    return BB = F->createBasicBlock();
711
712
  // If it already exists, it was either a forward reference or a redefinition.
713
  // If it is a forward reference, it should be in our undefined set.
714
193k
  if (!UndefinedBlocks.erase(BB)) {
715
    // If we have a redefinition, return a new BB to avoid inserting
716
    // instructions after the terminator.
717
3
    P.diagnose(Loc, diag::sil_basicblock_redefinition, Name);
718
3
    HadError = true;
719
3
    return F->createBasicBlock();
720
3
  }
721
722
  // FIXME: Splice the block to the end of the function so they come out in the
723
  // right order.
724
193k
  return BB;
725
193k
}
726
727
/// getBBForReference - return the SILBasicBlock of the specified name.  The
728
/// source location is used to diagnose a failure if the block ends up never
729
/// being defined.
730
207k
SILBasicBlock *SILParser::getBBForReference(Identifier Name, SourceLoc Loc) {
731
  // If the block has already been created, use it.
732
207k
  SILBasicBlock *&BB = BlocksByName[Name];
733
207k
  if (BB != nullptr)
734
13.7k
    return BB;
735
736
  // Otherwise, create it and remember that this is a forward reference so
737
  // that we can diagnose use without definition problems.
738
193k
  BB = F->createBasicBlock();
739
193k
  UndefinedBlocks[BB] = {Name, Loc};
740
193k
  return BB;
741
207k
}
742
743
///   sil-global-name:
744
///     '@' identifier
745
30.3k
bool SILParser::parseGlobalName(Identifier &Name) {
746
30.3k
  return P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
747
30.3k
         parseSILIdentifier(Name, diag::expected_sil_value_name);
748
30.3k
}
749
750
/// getLocalValue - Get a reference to a local value with the specified name
751
/// and type.
752
SILValue SILParser::getLocalValue(UnresolvedValueName Name, SILType Type,
753
362k
                                  SILLocation Loc, SILBuilder &B) {
754
362k
  if (Name.isUndef())
755
8.69k
    return SILUndef::get(Type, B.getFunction());
756
757
  // Check to see if this is already defined.
758
353k
  ValueBase *&Entry = LocalValues[Name.Name];
759
760
353k
  if (Entry) {
761
    // If this value is already defined, check it to make sure types match.
762
353k
    SILType EntryTy = Entry->getType();
763
764
353k
    if (EntryTy != Type) {
765
6
      HadError = true;
766
6
      P.diagnose(Name.NameLoc, diag::sil_value_use_type_mismatch, Name.Name,
767
6
                 EntryTy.getRawASTType(), Type.getRawASTType());
768
      // Make sure to return something of the requested type.
769
6
      return SILUndef::get(Type, B.getFunction());
770
6
    }
771
772
353k
    return SILValue(Entry);
773
353k
  }
774
  
775
  // Otherwise, this is a forward reference.  Create a dummy node to represent
776
  // it until we see a real definition.
777
180
  ForwardRefLocalValues[Name.Name] = Name.NameLoc;
778
779
180
  Entry = ::new PlaceholderValue(Type);
780
180
  return Entry;
781
353k
}
782
783
/// setLocalValue - When an instruction or block argument is defined, this
784
/// method is used to register it and update our symbol table.
785
void SILParser::setLocalValue(ValueBase *Value, StringRef Name,
786
287k
                              SourceLoc NameLoc) {
787
287k
  ValueBase *&Entry = LocalValues[Name];
788
789
  // If this value was already defined, it is either a redefinition, or a
790
  // specification for a forward referenced value.
791
287k
  if (Entry) {
792
174
    if (!ForwardRefLocalValues.erase(Name)) {
793
3
      P.diagnose(NameLoc, diag::sil_value_redefinition, Name);
794
3
      HadError = true;
795
3
      return;
796
3
    }
797
798
    // If the forward reference was of the wrong type, diagnose this now.
799
171
    if (Entry->getType() != Value->getType()) {
800
0
      P.diagnose(NameLoc, diag::sil_value_def_type_mismatch, Name,
801
0
                 Entry->getType().getRawASTType(),
802
0
                 Value->getType().getRawASTType());
803
0
      HadError = true;
804
171
    } else {
805
171
      if (TestSpecsWithRefs.find(Name) != TestSpecsWithRefs.end()) {
806
0
        for (auto *tsi : TestSpecsWithRefs[Name]) {
807
0
          tsi->setValueForName(Name, Value);
808
0
        }
809
0
      }
810
811
      // Forward references only live here if they have a single result.
812
171
      Entry->replaceAllUsesWith(Value);
813
171
      ::delete cast<PlaceholderValue>(Entry);
814
171
    }
815
171
    Entry = Value;
816
171
    return;
817
174
  }
818
819
287k
  if (TestSpecsWithRefs.find(Name) != TestSpecsWithRefs.end()) {
820
6
    for (auto *tsi : TestSpecsWithRefs[Name]) {
821
6
      tsi->setValueForName(Name, Value);
822
6
    }
823
6
  }
824
825
  // Otherwise, just store it in our map.
826
287k
  Entry = Value;
827
287k
}
828
829
830
//===----------------------------------------------------------------------===//
831
// SIL Parsing Logic
832
//===----------------------------------------------------------------------===//
833
834
/// parseSILLinkage - Parse a linkage specifier if present.
835
///   sil-linkage:
836
///     /*empty*/          // default depends on whether this is a definition
837
///     'public'
838
///     'hidden'
839
///     'shared'
840
///     'private'
841
///     'public_external'
842
///     'hidden_external'
843
///     'private_external'
844
56.7k
static bool parseSILLinkage(llvm::Optional<SILLinkage> &Result, Parser &P) {
845
  // Begin by initializing result to our base value of None.
846
56.7k
  Result = llvm::None;
847
848
  // Unfortunate collision with access control keywords.
849
56.7k
  if (P.Tok.is(tok::kw_public)) {
850
240
    Result = SILLinkage::Public;
851
240
    P.consumeToken();
852
240
    return false;
853
240
  }
854
855
  // Unfortunate collision with access control keywords.
856
56.4k
  if (P.Tok.is(tok::kw_private)) {
857
1.87k
    Result = SILLinkage::Private;
858
1.87k
    P.consumeToken();
859
1.87k
    return false;
860
1.87k
  }
861
862
  // If we do not have an identifier, bail. All SILLinkages that we are parsing
863
  // are identifiers.
864
54.5k
  if (P.Tok.isNot(tok::identifier))
865
45.5k
    return false;
866
867
  // Then use a string switch to try and parse the identifier.
868
9.05k
  Result = llvm::StringSwitch<llvm::Optional<SILLinkage>>(P.Tok.getText())
869
9.05k
               .Case("non_abi", SILLinkage::PublicNonABI)
870
9.05k
               .Case("hidden", SILLinkage::Hidden)
871
9.05k
               .Case("shared", SILLinkage::Shared)
872
9.05k
               .Case("public_external", SILLinkage::PublicExternal)
873
9.05k
               .Case("hidden_external", SILLinkage::HiddenExternal)
874
9.05k
               .Default(llvm::None);
875
876
  // If we succeed, consume the token.
877
9.05k
  if (Result) {
878
8.77k
    P.consumeToken(tok::identifier);
879
8.77k
  }
880
881
9.05k
  return false;
882
54.5k
}
883
884
/// Given whether it's known to be a definition, resolve an optional
885
/// SIL linkage to a real one.
886
static SILLinkage resolveSILLinkage(llvm::Optional<SILLinkage> linkage,
887
54.5k
                                    bool isDefinition) {
888
54.5k
  if (linkage.has_value()) {
889
10.0k
    return linkage.value();
890
44.5k
  } else if (isDefinition) {
891
33.7k
    return SILLinkage::DefaultForDefinition;
892
33.7k
  } else {
893
10.7k
    return SILLinkage::DefaultForDeclaration;
894
10.7k
  }
895
54.5k
}
896
897
// Returns false if no optional exists. Returns true on both success and
898
// failure. On success, the Result string is nonempty. If the optional is
899
// assigned to an integer value, \p value contains the parsed value. Otherwise,
900
// value is set to the maximum uint64_t.
901
static bool parseSILOptional(StringRef &Result, uint64_t &value, SourceLoc &Loc,
902
129k
                             SILParser &SP) {
903
129k
  if (!SP.P.consumeIf(tok::l_square))
904
104k
    return false;
905
906
25.5k
  value = ~uint64_t(0);
907
908
25.5k
  Identifier Id;
909
25.5k
  if (SP.parseSILIdentifier(Id, Loc, diag::expected_in_attribute_list))
910
0
    return true;
911
912
25.5k
  if (SP.P.consumeIf(tok::equal)) {
913
57
    if (SP.parseInteger(value, diag::expected_in_attribute_list))
914
0
      return true;
915
57
  }
916
25.5k
  if (SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list))
917
0
    return true;
918
919
25.5k
  Result = Id.str();
920
25.5k
  return true;
921
25.5k
}
922
923
127k
static bool parseSILOptional(StringRef &Result, SourceLoc &Loc, SILParser &SP) {
924
127k
  uint64_t value;
925
127k
  return parseSILOptional(Result, value, Loc, SP);
926
127k
}
927
928
76.4k
static bool parseSILOptional(StringRef &Result, SILParser &SP) {
929
76.4k
  SourceLoc Loc;
930
76.4k
  return parseSILOptional(Result, Loc, SP);
931
76.4k
}
932
933
/// Parse an option attribute ('[' Expected ']')?
934
25.0k
static bool parseSILOptional(bool &Result, SILParser &SP, StringRef Expected) {
935
25.0k
  StringRef Optional;
936
25.0k
  SourceLoc Loc;
937
25.0k
  if (parseSILOptional(Optional, Loc, SP)) {
938
4.97k
    if (Optional != Expected) {
939
0
      SP.P.diagnose(Loc, diag::sil_invalid_attribute_for_expected, Optional,
940
0
                    Expected);
941
0
      return true;
942
0
    }
943
4.97k
    Result = true;
944
4.97k
  }
945
25.0k
  return false;
946
25.0k
}
947
948
// If the qualifier string is unrecognized, then diagnose and fail.
949
//
950
// If the qualifier is absent, then succeed and set the result to None.
951
// The caller can decide how to proceed with an absent qualifier.
952
//
953
// Usage:
954
// auto parseQualifierName = [](StringRef Str) {
955
//   return llvm::StringSwitch<llvm::Optional<SomeQualifier>>(Str)
956
//       .Case("one", SomeQualifier::One)
957
//       .Case("two", SomeQualifier::Two)
958
//       .Default(None);
959
// };
960
// if (parseSILQualifier<SomeQualifier>(Qualifier, parseQualifierName))
961
//   return true;
962
template <typename T>
963
bool SILParser::parseSILQualifier(
964
    llvm::Optional<T> &result,
965
24.8k
    llvm::function_ref<llvm::Optional<T>(StringRef)> parseName) {
966
24.8k
  auto loc = P.Tok.getLoc();
967
24.8k
  StringRef Str;
968
  // If we do not parse '[' ... ']',
969
24.8k
  if (!parseSILOptional(Str, *this)) {
970
10.4k
    result = llvm::None;
971
10.4k
    return false;
972
10.4k
  }
973
14.3k
  result = parseName(Str);
974
14.3k
  if (!result) {
975
0
    P.diagnose(loc, Diagnostic(diag::unrecognized_sil_qualifier));
976
0
    return true;
977
0
  }
978
14.3k
  return false;
979
14.3k
}
_ZN5swift9SILParser17parseSILQualifierINS_22LoadOwnershipQualifierEEEbRNSt3__18optionalIT_EEN4llvm12function_refIFS6_NS8_9StringRefEEEE
Line
Count
Source
965
11.4k
    llvm::function_ref<llvm::Optional<T>(StringRef)> parseName) {
966
11.4k
  auto loc = P.Tok.getLoc();
967
11.4k
  StringRef Str;
968
  // If we do not parse '[' ... ']',
969
11.4k
  if (!parseSILOptional(Str, *this)) {
970
4.55k
    result = llvm::None;
971
4.55k
    return false;
972
4.55k
  }
973
6.91k
  result = parseName(Str);
974
6.91k
  if (!result) {
975
0
    P.diagnose(loc, Diagnostic(diag::unrecognized_sil_qualifier));
976
0
    return true;
977
0
  }
978
6.91k
  return false;
979
6.91k
}
_ZN5swift9SILParser17parseSILQualifierINS_23StoreOwnershipQualifierEEEbRNSt3__18optionalIT_EEN4llvm12function_refIFS6_NS8_9StringRefEEEE
Line
Count
Source
965
12.7k
    llvm::function_ref<llvm::Optional<T>(StringRef)> parseName) {
966
12.7k
  auto loc = P.Tok.getLoc();
967
12.7k
  StringRef Str;
968
  // If we do not parse '[' ... ']',
969
12.7k
  if (!parseSILOptional(Str, *this)) {
970
5.38k
    result = llvm::None;
971
5.38k
    return false;
972
5.38k
  }
973
7.40k
  result = parseName(Str);
974
7.40k
  if (!result) {
975
0
    P.diagnose(loc, Diagnostic(diag::unrecognized_sil_qualifier));
976
0
    return true;
977
0
  }
978
7.40k
  return false;
979
7.40k
}
_ZN5swift9SILParser17parseSILQualifierINS_24AssignOwnershipQualifierEEEbRNSt3__18optionalIT_EEN4llvm12function_refIFS6_NS8_9StringRefEEEE
Line
Count
Source
965
557
    llvm::function_ref<llvm::Optional<T>(StringRef)> parseName) {
966
557
  auto loc = P.Tok.getLoc();
967
557
  StringRef Str;
968
  // If we do not parse '[' ... ']',
969
557
  if (!parseSILOptional(Str, *this)) {
970
506
    result = llvm::None;
971
506
    return false;
972
506
  }
973
51
  result = parseName(Str);
974
51
  if (!result) {
975
0
    P.diagnose(loc, Diagnostic(diag::unrecognized_sil_qualifier));
976
0
    return true;
977
0
  }
978
51
  return false;
979
51
}
980
981
/// Remap RequirementReps to Requirements.
982
void SILParser::convertRequirements(ArrayRef<RequirementRepr> From,
983
                                    SmallVectorImpl<Requirement> &To,
984
456
                                    SmallVectorImpl<Type> &typeErasedParams) {
985
456
  if (From.empty()) {
986
0
    To.clear();
987
0
    return;
988
0
  }
989
990
  // Use parser lexical scopes to resolve references
991
  // to the generic parameters.
992
774
  auto ResolveToInterfaceType = [&](TypeRepr *TyR) -> Type {
993
774
    return performTypeResolution(TyR, /*IsSILType=*/false, ContextGenericSig,
994
774
                                 ContextGenericParams);
995
774
  };
996
997
456
  for (auto &Req : From) {
998
456
    if (Req.getKind() == RequirementReprKind::SameType) {
999
318
      auto FirstType = ResolveToInterfaceType(Req.getFirstTypeRepr());
1000
318
      auto SecondType = ResolveToInterfaceType(Req.getSecondTypeRepr());
1001
318
      Requirement ConvertedRequirement(RequirementKind::SameType, FirstType,
1002
318
                                       SecondType);
1003
318
      To.push_back(ConvertedRequirement);
1004
318
      continue;
1005
318
    }
1006
1007
138
    if (Req.getKind() == RequirementReprKind::TypeConstraint) {
1008
0
      auto Subject = ResolveToInterfaceType(Req.getSubjectRepr());
1009
0
      auto Constraint = ResolveToInterfaceType(Req.getConstraintRepr());
1010
0
      Requirement ConvertedRequirement(RequirementKind::Conformance, Subject,
1011
0
                                       Constraint);
1012
0
      To.push_back(ConvertedRequirement);
1013
0
      continue;
1014
0
    }
1015
1016
138
    if (Req.getKind() == RequirementReprKind::LayoutConstraint) {
1017
138
      auto Subject = ResolveToInterfaceType(Req.getSubjectRepr());
1018
138
      Requirement ConvertedRequirement(RequirementKind::Layout, Subject,
1019
138
                                       Req.getLayoutConstraint());
1020
138
      To.push_back(ConvertedRequirement);
1021
1022
138
      if (SILMod.getASTContext().LangOpts.hasFeature(Feature::LayoutPrespecialization)) {
1023
138
        if (auto *attributedTy = dyn_cast<AttributedTypeRepr>(Req.getSubjectRepr())) {
1024
48
          if (attributedTy->getAttrs().has(TAK__noMetadata)) {
1025
48
            typeErasedParams.push_back(Subject);
1026
48
          }
1027
48
        }
1028
138
      }
1029
1030
138
      continue;
1031
138
    }
1032
1033
0
    llvm_unreachable("Unsupported requirement kind");
1034
0
  }
1035
456
}
1036
1037
static bool parseDeclSILOptional(bool *isTransparent,
1038
                                 IsSerialized_t *isSerialized,
1039
                                 bool *isCanonical,
1040
                                 bool *hasOwnershipSSA,
1041
                                 IsThunk_t *isThunk,
1042
                                 IsDynamicallyReplaceable_t *isDynamic,
1043
                                 IsDistributed_t *isDistributed,
1044
                                 IsRuntimeAccessible_t *isRuntimeAccessible,
1045
                                 ForceEnableLexicalLifetimes_t *forceEnableLexicalLifetimes,
1046
                                 UseStackForPackMetadata_t *useStackForPackMetadata,
1047
                                 bool *hasUnsafeNonEscapableResult,
1048
                                 IsExactSelfClass_t *isExactSelfClass,
1049
                                 SILFunction **dynamicallyReplacedFunction,
1050
                                 SILFunction **usedAdHocRequirementWitness,
1051
                                 Identifier *objCReplacementFor,
1052
                                 SILFunction::Purpose *specialPurpose,
1053
                                 Inline_t *inlineStrategy,
1054
                                 OptimizationMode *optimizationMode,
1055
                                 PerformanceConstraints *perfConstraints,
1056
                                 bool *markedAsUsed,
1057
                                 StringRef *section,
1058
                                 bool *isLet,
1059
                                 bool *isWeakImported,
1060
                                 bool *needStackProtection,
1061
                                 AvailabilityContext *availability,
1062
                                 bool *isWithoutActuallyEscapingThunk,
1063
                                 SmallVectorImpl<std::string> *Semantics,
1064
                                 SmallVectorImpl<ParsedSpecAttr> *SpecAttrs,
1065
                                 ValueDecl **ClangDecl,
1066
                                 EffectsKind *MRK,
1067
57.7k
                                 SILParser &SP, SILModule &M) {
1068
94.3k
  while (SP.P.consumeIf(tok::l_square)) {
1069
36.5k
    if (isLet && SP.P.Tok.is(tok::kw_let)) {
1070
153
      *isLet = true;
1071
153
      SP.P.consumeToken(tok::kw_let);
1072
153
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1073
153
      continue;
1074
153
    }
1075
36.4k
    else if (SP.P.Tok.isNot(tok::identifier)) {
1076
0
      SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1077
0
      return true;
1078
36.4k
    } else if (isTransparent && SP.P.Tok.getText() == "transparent")
1079
3.13k
      *isTransparent = true;
1080
33.2k
    else if (isSerialized && SP.P.Tok.getText() == "serialized")
1081
3.13k
      *isSerialized = IsSerialized;
1082
30.1k
    else if (isDynamic && SP.P.Tok.getText() == "dynamically_replacable")
1083
24
      *isDynamic = IsDynamic;
1084
30.1k
    else if (isDistributed && SP.P.Tok.getText() == "distributed")
1085
6
      *isDistributed = IsDistributed;
1086
30.1k
    else if (isRuntimeAccessible && SP.P.Tok.getText() == "runtime_accessible")
1087
6
      *isRuntimeAccessible = IsRuntimeAccessible;
1088
30.1k
    else if (forceEnableLexicalLifetimes &&
1089
30.1k
             SP.P.Tok.getText() == "lexical_lifetimes")
1090
9
      *forceEnableLexicalLifetimes = DoForceEnableLexicalLifetimes;
1091
30.1k
    else if (useStackForPackMetadata &&
1092
30.1k
             SP.P.Tok.getText() == "no_onstack_pack_metadata")
1093
6
      *useStackForPackMetadata = DoNotUseStackForPackMetadata;
1094
30.1k
    else if (hasUnsafeNonEscapableResult &&
1095
30.1k
             SP.P.Tok.getText() == "unsafe_nonescapable_result")
1096
3
      *useStackForPackMetadata = DoNotUseStackForPackMetadata;
1097
30.1k
    else if (isExactSelfClass && SP.P.Tok.getText() == "exact_self_class")
1098
105
      *isExactSelfClass = IsExactSelfClass;
1099
30.0k
    else if (isCanonical && SP.P.Tok.getText() == "canonical")
1100
63
      *isCanonical = true;
1101
29.9k
    else if (hasOwnershipSSA && SP.P.Tok.getText() == "ossa")
1102
22.7k
      *hasOwnershipSSA = true;
1103
7.21k
    else if (needStackProtection && SP.P.Tok.getText() == "stack_protection")
1104
0
      *needStackProtection = true;
1105
7.21k
    else if (isThunk && SP.P.Tok.getText() == "thunk")
1106
558
      *isThunk = IsThunk;
1107
6.65k
    else if (isThunk && SP.P.Tok.getText() == "signature_optimized_thunk")
1108
27
      *isThunk = IsSignatureOptimizedThunk;
1109
6.63k
    else if (isThunk && SP.P.Tok.getText() == "reabstraction_thunk")
1110
156
      *isThunk = IsReabstractionThunk;
1111
6.47k
    else if (isWithoutActuallyEscapingThunk
1112
6.47k
             && SP.P.Tok.getText() == "without_actually_escaping")
1113
18
      *isWithoutActuallyEscapingThunk = true;
1114
6.45k
    else if (specialPurpose && SP.P.Tok.getText() == "global_init")
1115
75
      *specialPurpose = SILFunction::Purpose::GlobalInit;
1116
6.38k
    else if (specialPurpose && SP.P.Tok.getText() == "lazy_getter")
1117
27
      *specialPurpose = SILFunction::Purpose::LazyPropertyGetter;
1118
6.35k
    else if (specialPurpose && SP.P.Tok.getText() == "global_init_once_fn")
1119
78
      *specialPurpose = SILFunction::Purpose::GlobalInitOnceFunction;
1120
6.27k
    else if (isWeakImported && SP.P.Tok.getText() == "weak_imported") {
1121
27
      if (M.getASTContext().LangOpts.Target.isOSBinFormatCOFF())
1122
3
        SP.P.diagnose(SP.P.Tok, diag::attr_unsupported_on_target,
1123
3
                      SP.P.Tok.getText(),
1124
3
                      M.getASTContext().LangOpts.Target.str());
1125
24
      else
1126
24
        *isWeakImported = true;
1127
6.24k
    } else if (availability && SP.P.Tok.getText() == "available") {
1128
60
      SP.P.consumeToken(tok::identifier);
1129
1130
60
      SourceRange range;
1131
60
      llvm::VersionTuple version;
1132
60
      if (SP.P.parseVersionTuple(version, range,
1133
60
                                 diag::sil_availability_expected_version))
1134
0
        return true;
1135
1136
60
      *availability = AvailabilityContext(VersionRange::allGTE(version));
1137
1138
60
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1139
60
      continue;
1140
6.18k
    } else if (inlineStrategy && SP.P.Tok.getText() == "noinline")
1141
1.52k
      *inlineStrategy = NoInline;
1142
4.66k
    else if (optimizationMode && SP.P.Tok.getText() == "Onone")
1143
321
      *optimizationMode = OptimizationMode::NoOptimization;
1144
4.34k
    else if (optimizationMode && SP.P.Tok.getText() == "Ospeed")
1145
6
      *optimizationMode = OptimizationMode::ForSpeed;
1146
4.33k
    else if (optimizationMode && SP.P.Tok.getText() == "Osize")
1147
51
      *optimizationMode = OptimizationMode::ForSize;
1148
4.28k
    else if (perfConstraints && SP.P.Tok.getText() == "no_locks")
1149
24
      *perfConstraints = PerformanceConstraints::NoLocks;
1150
4.26k
    else if (perfConstraints && SP.P.Tok.getText() == "no_allocation")
1151
24
      *perfConstraints = PerformanceConstraints::NoAllocation;
1152
4.23k
    else if (markedAsUsed && SP.P.Tok.getText() == "used")
1153
0
      *markedAsUsed = true;
1154
4.23k
    else if (section && SP.P.Tok.getText() == "section") {
1155
0
      SP.P.consumeToken(tok::identifier);
1156
0
      if (SP.P.Tok.getKind() != tok::string_literal) {
1157
0
        SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1158
0
        return true;
1159
0
      }
1160
  
1161
      // Drop the double quotes.
1162
0
      StringRef rawString = SP.P.Tok.getText().drop_front().drop_back();
1163
0
      *section = SP.P.Context.getIdentifier(rawString).str();
1164
0
      SP.P.consumeToken(tok::string_literal);
1165
1166
0
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1167
0
      continue;
1168
0
    }
1169
4.23k
    else if (inlineStrategy && SP.P.Tok.getText() == "always_inline")
1170
510
      *inlineStrategy = AlwaysInline;
1171
3.72k
    else if (MRK && SP.P.Tok.getText() == "readnone")
1172
30
      *MRK = EffectsKind::ReadNone;
1173
3.69k
    else if (MRK && SP.P.Tok.getText() == "readonly")
1174
212
      *MRK = EffectsKind::ReadOnly;
1175
3.48k
    else if (MRK && SP.P.Tok.getText() == "readwrite")
1176
3
      *MRK = EffectsKind::ReadWrite;
1177
3.48k
    else if (MRK && SP.P.Tok.getText() == "releasenone")
1178
30
      *MRK = EffectsKind::ReleaseNone;
1179
3.45k
    else if (dynamicallyReplacedFunction && SP.P.Tok.getText() == "dynamic_replacement_for") {
1180
15
      SP.P.consumeToken(tok::identifier);
1181
15
      if (SP.P.Tok.getKind() != tok::string_literal) {
1182
0
        SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1183
0
        return true;
1184
0
      }
1185
      // Drop the double quotes.
1186
15
      StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back();
1187
15
      SILFunction *Func = M.lookUpFunction(replacedFunc.str());
1188
15
      if (!Func) {
1189
0
        Identifier Id = SP.P.Context.getIdentifier(replacedFunc);
1190
0
        SP.P.diagnose(SP.P.Tok, diag::sil_dynamically_replaced_func_not_found,
1191
0
                      Id);
1192
0
        return true;
1193
0
      }
1194
15
      *dynamicallyReplacedFunction = Func;
1195
15
      SP.P.consumeToken(tok::string_literal);
1196
1197
15
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1198
15
      continue;
1199
3.43k
    } else if (usedAdHocRequirementWitness && SP.P.Tok.getText() == "ref_adhoc_requirement_witness") {
1200
0
      SP.P.consumeToken(tok::identifier);
1201
0
      if (SP.P.Tok.getKind() != tok::string_literal) {
1202
0
        SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1203
0
        return true;
1204
0
      }
1205
      // Drop the double quotes.
1206
0
      StringRef witnessFunc = SP.P.Tok.getText().drop_front().drop_back();
1207
0
      SILFunction *Func = M.lookUpFunction(witnessFunc.str());
1208
0
      if (!Func) {
1209
0
        Identifier Id = SP.P.Context.getIdentifier(witnessFunc);
1210
0
        SP.P.diagnose(SP.P.Tok, diag::sil_adhoc_requirement_witness_func_not_found,
1211
0
                      Id);
1212
0
        return true;
1213
0
      }
1214
0
      *usedAdHocRequirementWitness = Func;
1215
0
      SP.P.consumeToken(tok::string_literal);
1216
1217
0
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1218
0
      continue;
1219
3.43k
    } else if (objCReplacementFor &&
1220
3.43k
               SP.P.Tok.getText() == "objc_replacement_for") {
1221
0
      SP.P.consumeToken(tok::identifier);
1222
0
      if (SP.P.Tok.getKind() != tok::string_literal) {
1223
0
        SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1224
0
        return true;
1225
0
      }
1226
      // Drop the double quotes.
1227
0
      StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back();
1228
0
      *objCReplacementFor = SP.P.Context.getIdentifier(replacedFunc);
1229
0
      SP.P.consumeToken(tok::string_literal);
1230
1231
0
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1232
0
      continue;
1233
3.43k
    } else if (Semantics && SP.P.Tok.getText() == "_semantics") {
1234
2.85k
      SP.P.consumeToken(tok::identifier);
1235
2.85k
      if (SP.P.Tok.getKind() != tok::string_literal) {
1236
0
        SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1237
0
        return true;
1238
0
      }
1239
  
1240
      // Drop the double quotes.
1241
2.85k
      StringRef rawString = SP.P.Tok.getText().drop_front().drop_back();
1242
2.85k
      Semantics->push_back(rawString.str());
1243
2.85k
      SP.P.consumeToken(tok::string_literal);
1244
1245
2.85k
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1246
2.85k
      continue;
1247
2.85k
    } else if (SpecAttrs && SP.P.Tok.getText() == "_specialize") {
1248
552
      SourceLoc AtLoc = SP.P.Tok.getLoc();
1249
552
      SourceLoc Loc(AtLoc);
1250
1251
      // Parse a _specialized attribute, building a parsed substitution list
1252
      // and pushing a new ParsedSpecAttr on the SpecAttrs list. Conformances
1253
      // cannot be generated until the function declaration is fully parsed so
1254
      // that the function's generic signature can be consulted.
1255
552
      ParsedSpecAttr SpecAttr;
1256
552
      SpecAttr.requirements = {};
1257
552
      SpecAttr.exported = false;
1258
552
      SpecAttr.kind = SILSpecializeAttr::SpecializationKind::Full;
1259
552
      SpecializeAttr *Attr;
1260
552
      StringRef targetFunctionName;
1261
552
      ModuleDecl *module = nullptr;
1262
552
      AvailabilityContext availability = AvailabilityContext::alwaysAvailable();
1263
552
      if (!SP.P.parseSpecializeAttribute(
1264
552
              tok::r_square, AtLoc, Loc, Attr, &availability,
1265
552
              [&targetFunctionName](Parser &P) -> bool {
1266
12
                if (P.Tok.getKind() != tok::string_literal) {
1267
0
                  P.diagnose(P.Tok, diag::expected_in_attribute_list);
1268
0
                  return true;
1269
0
                }
1270
                // Drop the double quotes.
1271
12
                targetFunctionName = P.Tok.getText().drop_front().drop_back();
1272
1273
12
                P.consumeToken(tok::string_literal);
1274
12
                return true;
1275
12
              },
1276
552
              [&module](Parser &P) -> bool {
1277
0
                if (P.Tok.getKind() != tok::identifier) {
1278
0
                  P.diagnose(P.Tok, diag::expected_in_attribute_list);
1279
0
                  return true;
1280
0
                }
1281
0
                auto ident = P.Context.getIdentifier(P.Tok.getText());
1282
0
                module = P.Context.getModuleByIdentifier(ident);
1283
0
                assert(module);
1284
0
                P.consumeToken();
1285
0
                return true;
1286
0
              }))
1287
0
        return true;
1288
552
      SILFunction *targetFunction = nullptr;
1289
552
      if (!targetFunctionName.empty()) {
1290
12
        targetFunction = M.lookUpFunction(targetFunctionName.str());
1291
12
        if (!targetFunction) {
1292
0
          Identifier Id = SP.P.Context.getIdentifier(targetFunctionName);
1293
0
          SP.P.diagnose(SP.P.Tok, diag::sil_specialize_target_func_not_found,
1294
0
                        Id);
1295
0
          return true;
1296
0
        }
1297
12
      }
1298
      // Convert SpecializeAttr into ParsedSpecAttr.
1299
552
      SpecAttr.requirements = Attr->getTrailingWhereClause()->getRequirements();
1300
552
      SpecAttr.kind = Attr->getSpecializationKind() ==
1301
552
                              swift::SpecializeAttr::SpecializationKind::Full
1302
552
                          ? SILSpecializeAttr::SpecializationKind::Full
1303
552
                          : SILSpecializeAttr::SpecializationKind::Partial;
1304
552
      SpecAttr.exported = Attr->isExported();
1305
552
      SpecAttr.target = targetFunction;
1306
552
      SpecAttr.availability = availability;
1307
552
      SpecAttrs->emplace_back(SpecAttr);
1308
552
      if (!Attr->getSPIGroups().empty()) {
1309
0
        SpecAttr.spiGroupID = Attr->getSPIGroups()[0];
1310
0
      }
1311
552
      continue;
1312
552
    }
1313
30
    else if (ClangDecl && SP.P.Tok.getText() == "clang") {
1314
30
      SP.P.consumeToken(tok::identifier);
1315
30
      if (SP.parseSILDottedPathWithoutPound(*ClangDecl))
1316
0
        return true;
1317
1318
30
      SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1319
30
      continue;
1320
30
    } else {
1321
0
      SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
1322
0
      return true;
1323
0
    }
1324
32.9k
    SP.P.consumeToken(tok::identifier);
1325
32.9k
    SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
1326
32.9k
  }
1327
57.7k
  return false;
1328
57.7k
}
1329
1330
Type SILParser::performTypeResolution(TypeRepr *TyR, bool IsSILType,
1331
                                      GenericSignature GenericSig,
1332
542k
                                      GenericParamList *GenericParams) {
1333
542k
  if (!GenericSig)
1334
476k
    GenericSig = ContextGenericSig;
1335
1336
542k
  SILTypeResolutionContext SILContext(IsSILType, GenericParams,
1337
542k
                                      &OpenedPackElements);
1338
1339
542k
  return swift::performTypeResolution(TyR, P.Context, GenericSig,
1340
542k
                                      &SILContext, &P.SF);
1341
542k
}
1342
1343
/// Find the top-level ValueDecl or Module given a name.
1344
static llvm::PointerUnion<ValueDecl *, ModuleDecl *>
1345
32.3k
lookupTopDecl(Parser &P, DeclBaseName Name, bool typeLookup) {
1346
  // Use UnqualifiedLookup to look through all of the imports.
1347
32.3k
  UnqualifiedLookupOptions options;
1348
32.3k
  if (typeLookup)
1349
32.3k
    options |= UnqualifiedLookupFlags::TypeLookup;
1350
1351
32.3k
  auto &ctx = P.SF.getASTContext();
1352
32.3k
  auto descriptor = UnqualifiedLookupDescriptor(DeclNameRef(Name), &P.SF);
1353
32.3k
  auto lookup = evaluateOrDefault(ctx.evaluator,
1354
32.3k
                                  UnqualifiedLookupRequest{descriptor}, {});
1355
32.3k
  lookup.filter([](LookupResultEntry entry, bool isOuter) -> bool {
1356
32.3k
    return !isa<MacroDecl>(entry.getValueDecl());
1357
32.3k
  });
1358
1359
32.3k
  assert(lookup.size() == 1);
1360
1361
0
  return lookup.back().getValueDecl();
1362
32.3k
}
1363
1364
/// Find the ValueDecl given an interface type and a member name.
1365
static ValueDecl *lookupMember(Parser &P, Type Ty, DeclBaseName Name,
1366
                               SourceLoc Loc,
1367
                               SmallVectorImpl<ValueDecl *> &Lookup,
1368
29.9k
                               bool ExpectMultipleResults) {
1369
29.9k
  Type CheckTy = Ty;
1370
29.9k
  if (auto MetaTy = CheckTy->getAs<AnyMetatypeType>())
1371
29.9k
    CheckTy = MetaTy->getInstanceType();
1372
1373
29.9k
  if (auto nominal = CheckTy->getAnyNominal()) {
1374
29.9k
    if (Name == DeclBaseName::createDestructor() &&
1375
29.9k
        isa<ClassDecl>(nominal)) {
1376
351
      auto *classDecl = cast<ClassDecl>(nominal);
1377
351
      Lookup.push_back(classDecl->getDestructor());
1378
29.5k
    } else {
1379
29.5k
      auto found = nominal->lookupDirect(Name);
1380
29.5k
      Lookup.append(found.begin(), found.end());
1381
29.5k
    }
1382
29.9k
  } else if (auto moduleTy = CheckTy->getAs<ModuleType>()) {
1383
0
    moduleTy->getModule()->lookupValue(Name, NLKind::QualifiedLookup, Lookup);
1384
0
  } else {
1385
0
    P.diagnose(Loc, diag::sil_member_lookup_bad_type, Name, Ty);
1386
0
    return nullptr;
1387
0
  }
1388
1389
29.9k
  if (Lookup.empty() || (!ExpectMultipleResults && Lookup.size() != 1)) {
1390
0
    P.diagnose(Loc, diag::sil_named_member_decl_not_found, Name, Ty);
1391
0
    return nullptr;
1392
0
  }
1393
29.9k
  return Lookup[0];
1394
29.9k
}
1395
1396
bool SILParser::parseASTType(CanType &result,
1397
                             GenericSignature genericSig,
1398
                             GenericParamList *genericParams,
1399
6.90k
                             bool forceContextualType) {
1400
6.90k
  ParserResult<TypeRepr> parsedType = P.parseType();
1401
6.90k
  if (parsedType.isNull()) return true;
1402
1403
  // If we weren't given a specific generic context to resolve the type
1404
  // within, use the contextual generic parameters and always produce
1405
  // a contextual type.  Otherwise, produce a contextual type only if
1406
  // we were asked for one.
1407
6.90k
  bool wantContextualType = forceContextualType;
1408
6.90k
  if (!genericSig) {
1409
6.42k
    genericSig = ContextGenericSig;
1410
6.42k
    wantContextualType = true;
1411
6.42k
  }
1412
6.90k
  if (genericParams == nullptr)
1413
6.42k
    genericParams = ContextGenericParams;
1414
1415
6.90k
  bindSILGenericParams(parsedType.get());
1416
1417
6.90k
  auto resolvedType = performTypeResolution(
1418
6.90k
      parsedType.get(), /*isSILType=*/false, genericSig, genericParams);
1419
6.90k
  if (wantContextualType && genericSig) {
1420
1.56k
    resolvedType = genericSig.getGenericEnvironment()
1421
1.56k
        ->mapTypeIntoContext(resolvedType);
1422
1.56k
  }
1423
1424
6.90k
  if (resolvedType->hasError())
1425
0
    return true;
1426
1427
6.90k
  result = resolvedType->getCanonicalType();
1428
1429
6.90k
  return false;
1430
6.90k
}
1431
1432
532k
void SILParser::bindSILGenericParams(TypeRepr *TyR) {
1433
  // Resolve the generic environments for parsed generic function and box types.
1434
532k
  class HandleSILGenericParamsWalker : public ASTWalker {
1435
532k
    SourceFile *SF;
1436
1437
532k
  public:
1438
532k
    HandleSILGenericParamsWalker(SourceFile *SF) : SF(SF) {}
1439
1440
    /// Walk everything in a macro
1441
532k
    MacroWalking getMacroWalkingBehavior() const override {
1442
0
      return MacroWalking::ArgumentsAndExpansion;
1443
0
    }
1444
1445
1.62M
    PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
1446
1.62M
      if (auto fnType = dyn_cast<FunctionTypeRepr>(T)) {
1447
149k
        if (auto *genericParams = fnType->getGenericParams()) {
1448
20.1k
          auto sig = handleSILGenericParams(genericParams, SF);
1449
20.1k
          fnType->setGenericSignature(sig);
1450
20.1k
        }
1451
1452
149k
        if (auto *genericParams = fnType->getPatternGenericParams()) {
1453
1.12k
          auto sig = handleSILGenericParams(genericParams, SF);
1454
1.12k
          fnType->setPatternGenericSignature(sig);
1455
1.12k
        }
1456
149k
      }
1457
1458
1.62M
      if (auto boxType = dyn_cast<SILBoxTypeRepr>(T)) {
1459
13.0k
        if (auto *genericParams = boxType->getGenericParams()) {
1460
7.44k
          auto sig = handleSILGenericParams(genericParams, SF);
1461
7.44k
          boxType->setGenericSignature(sig);
1462
7.44k
        }
1463
13.0k
      }
1464
1465
1.62M
      return Action::Continue();
1466
1.62M
    }
1467
532k
  };
1468
1469
532k
  TyR->walk(HandleSILGenericParamsWalker(&P.SF));
1470
532k
}
1471
1472
///   sil-type:
1473
///     '$' '*'? attribute-list (generic-params)? type
1474
///
1475
bool SILParser::parseSILType(SILType &Result,
1476
                             GenericSignature &ParsedGenericSig,
1477
                             GenericParamList *&ParsedGenericParams,
1478
                             bool IsFuncDecl,
1479
                             GenericSignature OuterGenericSig,
1480
522k
                             GenericParamList *OuterGenericParams) {
1481
522k
  ParsedGenericSig = GenericSignature();
1482
522k
  ParsedGenericParams = nullptr;
1483
1484
522k
  if (!OuterGenericSig)
1485
522k
    OuterGenericSig = ContextGenericSig;
1486
522k
  if (OuterGenericParams == nullptr)
1487
522k
    OuterGenericParams = ContextGenericParams;
1488
1489
522k
  if (P.parseToken(tok::sil_dollar, diag::expected_sil_type))
1490
3
    return true;
1491
1492
  // If we have a '*', then this is an address type.
1493
522k
  SILValueCategory category = SILValueCategory::Object;
1494
522k
  if (P.Tok.isAnyOperator() && P.Tok.getText().startswith("*")) {
1495
88.5k
    category = SILValueCategory::Address;
1496
88.5k
    P.consumeStartingCharacterOfCurrentToken();
1497
88.5k
  }
1498
1499
  // Parse attributes.
1500
522k
  ParamDecl::Specifier specifier;
1501
522k
  SourceLoc specifierLoc;
1502
522k
  SourceLoc isolatedLoc;
1503
522k
  SourceLoc constLoc;
1504
522k
  TypeAttributes attrs;
1505
522k
  P.parseTypeAttributeList(specifier, specifierLoc, isolatedLoc, constLoc, attrs);
1506
1507
  // Global functions are implicitly @convention(thin) if not specified otherwise.
1508
522k
  if (IsFuncDecl && !attrs.has(TAK_convention)) {
1509
    // Use a random location.
1510
1.55k
    attrs.setAttr(TAK_convention, P.PreviousLoc);
1511
1.55k
    attrs.ConventionArguments =
1512
1.55k
      TypeAttributes::Convention::makeSwiftConvention("thin");
1513
1.55k
  }
1514
1515
522k
  ParserResult<TypeRepr> TyR = P.parseType(diag::expected_sil_type);
1516
1517
522k
  if (TyR.isNull())
1518
0
    return true;
1519
1520
522k
  bindSILGenericParams(TyR.get());
1521
  
1522
  // Apply attributes to the type.
1523
522k
  auto *attrRepr =
1524
522k
      P.applyAttributeToType(
1525
522k
        TyR.get(), attrs, specifier, specifierLoc, isolatedLoc, constLoc);
1526
522k
  auto Ty = performTypeResolution(attrRepr, /*IsSILType=*/true, OuterGenericSig,
1527
522k
                                  OuterGenericParams);
1528
522k
  if (OuterGenericSig) {
1529
58.5k
    Ty = OuterGenericSig.getGenericEnvironment()->mapTypeIntoContext(Ty);
1530
58.5k
  }
1531
1532
522k
  if (Ty->hasError())
1533
36
    return true;
1534
1535
  // Save the top-level function generic environment if there was one.
1536
522k
  if (auto fnType = dyn_cast<FunctionTypeRepr>(TyR.get())) {
1537
134k
    if (auto genericSig = fnType->getGenericSignature())
1538
19.0k
      ParsedGenericSig = genericSig;
1539
134k
    if (auto *genericParams = fnType->getGenericParams())
1540
19.0k
      ParsedGenericParams = genericParams;
1541
134k
  }
1542
1543
522k
  Result = SILType::getPrimitiveType(Ty->getCanonicalType(),
1544
522k
                                     category);
1545
1546
522k
  return false;
1547
522k
}
1548
1549
bool SILParser::parseSILDottedPath(ValueDecl *&Decl,
1550
29.8k
                                   SmallVectorImpl<ValueDecl *> &values) {
1551
29.8k
  if (P.parseToken(tok::pound, diag::expected_sil_constant))
1552
0
    return true;
1553
29.8k
  return parseSILDottedPathWithoutPound(Decl, values);
1554
29.8k
}
1555
1556
bool SILParser::parseSILDottedPathWithoutPound(ValueDecl *&Decl,
1557
29.8k
                                   SmallVectorImpl<ValueDecl *> &values) {
1558
  // Handle sil-dotted-path.
1559
29.8k
  Identifier Id;
1560
29.8k
  SmallVector<DeclBaseName, 4> FullName;
1561
29.8k
  SmallVector<SourceLoc, 4> Locs;
1562
59.7k
  do {
1563
59.7k
    Locs.push_back(P.Tok.getLoc());
1564
59.7k
    switch (P.Tok.getKind()) {
1565
64
    case tok::kw_subscript:
1566
64
      P.consumeToken();
1567
64
      FullName.push_back(DeclBaseName::createSubscript());
1568
64
      break;
1569
612
    case tok::kw_init:
1570
612
      P.consumeToken();
1571
612
      FullName.push_back(DeclBaseName::createConstructor());
1572
612
      break;
1573
351
    case tok::kw_deinit:
1574
351
      P.consumeToken();
1575
351
      FullName.push_back(DeclBaseName::createDestructor());
1576
351
      break;
1577
58.7k
    default:
1578
58.7k
      if (parseSILIdentifier(Id, diag::expected_sil_constant))
1579
0
        return true;
1580
58.7k
      FullName.push_back(Id);
1581
58.7k
      break;
1582
59.7k
    }
1583
59.7k
  } while (P.consumeIf(tok::period));
1584
1585
  // Look up ValueDecl from a dotted path. If there are multiple components,
1586
  // the first one must be a type declaration.
1587
29.8k
  ValueDecl *VD;
1588
29.8k
  llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res = lookupTopDecl(
1589
29.8k
    P, FullName[0], /*typeLookup=*/FullName.size() > 1);
1590
  // It is possible that the last member lookup can return multiple lookup
1591
  // results. One example is the overloaded member functions.
1592
29.8k
  if (Res.is<ModuleDecl*>()) {
1593
0
    assert(FullName.size() > 1 &&
1594
0
           "A single module is not a full path to SILDeclRef");
1595
0
    auto Mod = Res.get<ModuleDecl*>();
1596
0
    values.clear();
1597
0
    VD = lookupMember(P, ModuleType::get(Mod), FullName[1], Locs[1], values,
1598
0
                      FullName.size() == 2/*ExpectMultipleResults*/);
1599
0
    for (unsigned I = 2, E = FullName.size(); I < E; ++I) {
1600
0
      values.clear();
1601
0
      VD = lookupMember(P, VD->getInterfaceType(), FullName[I], Locs[I], values,
1602
0
                        I == FullName.size() - 1/*ExpectMultipleResults*/);
1603
0
    }
1604
29.8k
  } else {
1605
29.8k
    VD = Res.get<ValueDecl*>();
1606
59.7k
    for (unsigned I = 1, E = FullName.size(); I < E; ++I) {
1607
29.8k
      values.clear();
1608
29.8k
      VD = lookupMember(P, VD->getInterfaceType(), FullName[I], Locs[I], values,
1609
29.8k
                        I == FullName.size() - 1/*ExpectMultipleResults*/);
1610
29.8k
    }
1611
29.8k
  }
1612
0
  Decl = VD;
1613
29.8k
  return false;
1614
29.8k
}
1615
1616
11.5k
static llvm::Optional<AccessorKind> getAccessorKind(StringRef ident) {
1617
11.5k
  return llvm::StringSwitch<llvm::Optional<AccessorKind>>(ident)
1618
11.5k
      .Case("getter", AccessorKind::Get)
1619
11.5k
      .Case("setter", AccessorKind::Set)
1620
11.5k
      .Case("addressor", AccessorKind::Address)
1621
11.5k
      .Case("mutableAddressor", AccessorKind::MutableAddress)
1622
11.5k
      .Case("read", AccessorKind::Read)
1623
11.5k
      .Case("modify", AccessorKind::Modify)
1624
11.5k
      .Default(llvm::None);
1625
11.5k
}
1626
1627
///  sil-decl-ref ::= '#' sil-identifier ('.' sil-identifier)* sil-decl-subref?
1628
///  sil-decl-subref ::= '!' sil-decl-subref-part ('.' sil-decl-lang)?
1629
///                      ('.' sil-decl-autodiff)?
1630
///  sil-decl-subref ::= '!' sil-decl-lang
1631
///  sil-decl-subref ::= '!' sil-decl-autodiff
1632
///  sil-decl-subref-part ::= 'getter'
1633
///  sil-decl-subref-part ::= 'setter'
1634
///  sil-decl-subref-part ::= 'allocator'
1635
///  sil-decl-subref-part ::= 'initializer'
1636
///  sil-decl-subref-part ::= 'enumelt'
1637
///  sil-decl-subref-part ::= 'destroyer'
1638
///  sil-decl-subref-part ::= 'globalaccessor'
1639
///  sil-decl-lang ::= 'foreign'
1640
///  sil-decl-autodiff ::= sil-decl-autodiff-kind '.' sil-decl-autodiff-indices
1641
///  sil-decl-autodiff-kind ::= 'jvp'
1642
///  sil-decl-autodiff-kind ::= 'vjp'
1643
///  sil-decl-autodiff-indices ::= [SU]+
1644
bool SILParser::parseSILDeclRef(SILDeclRef &Result,
1645
15.3k
                                SmallVectorImpl<ValueDecl *> &values) {
1646
15.3k
  ValueDecl *VD;
1647
15.3k
  if (parseSILDottedPath(VD, values))
1648
0
    return true;
1649
1650
  // Initialize SILDeclRef components.
1651
15.3k
  SILDeclRef::Kind Kind = SILDeclRef::Kind::Func;
1652
15.3k
  bool IsObjC = false;
1653
15.3k
  AutoDiffDerivativeFunctionIdentifier *DerivativeId = nullptr;
1654
1655
15.3k
  if (!P.consumeIf(tok::sil_exclamation)) {
1656
    // Construct SILDeclRef.
1657
3.78k
    Result = SILDeclRef(VD, Kind, IsObjC,
1658
3.78k
                        /*distributed=*/false, /*knownToBeLocal=*/false,
1659
3.78k
                        /*runtimeAccessible=*/false,
1660
3.78k
                        SILDeclRef::BackDeploymentKind::None, DerivativeId);
1661
3.78k
    return false;
1662
3.78k
  }
1663
1664
  // Handle SILDeclRef components. ParseState tracks the last parsed component.
1665
  //
1666
  // When ParseState is 0, accept kind (`func|getter|setter|...`) and set
1667
  // ParseState to 1.
1668
  //
1669
  // Always accept `foreign` and derivative function identifier.
1670
11.5k
  unsigned ParseState = 0;
1671
11.5k
  Identifier Id;
1672
11.6k
  do {
1673
11.6k
    if (P.Tok.is(tok::identifier)) {
1674
11.6k
      auto IdLoc = P.Tok.getLoc();
1675
11.6k
      if (parseSILIdentifier(Id, diag::expected_sil_constant))
1676
0
        return true;
1677
11.6k
      llvm::Optional<AccessorKind> accessorKind;
1678
11.6k
      if (!ParseState && Id.str() == "func") {
1679
0
        Kind = SILDeclRef::Kind::Func;
1680
0
        ParseState = 1;
1681
11.6k
      } else if (!ParseState &&
1682
11.6k
                 (accessorKind = getAccessorKind(Id.str())).has_value()) {
1683
        // Drill down to the corresponding accessor for each declaration,
1684
        // compacting away decls that lack it.
1685
544
        size_t destI = 0;
1686
1.24k
        for (size_t srcI = 0, e = values.size(); srcI != e; ++srcI) {
1687
698
          if (auto storage = dyn_cast<AbstractStorageDecl>(values[srcI]))
1688
677
            if (auto accessor = storage->getOpaqueAccessor(*accessorKind))
1689
674
              values[destI++] = accessor;
1690
698
        }
1691
544
        values.resize(destI);
1692
1693
        // Complain if none of the decls had a corresponding accessor.
1694
544
        if (destI == 0) {
1695
0
          P.diagnose(IdLoc, diag::referenced_value_no_accessor, 0);
1696
0
          return true;
1697
0
        }
1698
1699
544
        Kind = SILDeclRef::Kind::Func;
1700
544
        VD = values[0];
1701
544
        ParseState = 1;
1702
11.1k
      } else if (!ParseState && Id.str() == "allocator") {
1703
321
        Kind = SILDeclRef::Kind::Allocator;
1704
321
        ParseState = 1;
1705
10.8k
      } else if (!ParseState && Id.str() == "initializer") {
1706
285
        Kind = SILDeclRef::Kind::Initializer;
1707
285
        ParseState = 1;
1708
10.5k
      } else if (!ParseState && Id.str() == "enumelt") {
1709
9.83k
        Kind = SILDeclRef::Kind::EnumElement;
1710
9.83k
        ParseState = 1;
1711
9.83k
      } else if (!ParseState && Id.str() == "destroyer") {
1712
0
        Kind = SILDeclRef::Kind::Destroyer;
1713
0
        ParseState = 1;
1714
711
      } else if (!ParseState && Id.str() == "deallocator") {
1715
351
        Kind = SILDeclRef::Kind::Deallocator;
1716
351
        ParseState = 1;
1717
360
      } else if (!ParseState && Id.str() == "globalaccessor") {
1718
0
        Kind = SILDeclRef::Kind::GlobalAccessor;
1719
0
        ParseState = 1;
1720
360
      } else if (!ParseState && Id.str() == "ivardestroyer") {
1721
0
        Kind = SILDeclRef::Kind::IVarDestroyer;
1722
0
        ParseState = 1;
1723
360
      } else if (!ParseState && Id.str() == "ivarinitializer") {
1724
0
        Kind = SILDeclRef::Kind::IVarInitializer;
1725
0
        ParseState = 1;
1726
360
      } else if (!ParseState && Id.str() == "defaultarg") {
1727
0
        Kind = SILDeclRef::Kind::IVarInitializer;
1728
0
        ParseState = 1;
1729
360
      } else if (!ParseState && Id.str() == "propertyinit") {
1730
0
        Kind = SILDeclRef::Kind::StoredPropertyInitializer;
1731
0
        ParseState = 1;
1732
360
      } else if (!ParseState && Id.str() == "backinginit") {
1733
0
        Kind = SILDeclRef::Kind::PropertyWrapperBackingInitializer;
1734
0
        ParseState = 1;
1735
360
      } else if (!ParseState && Id.str() == "projectedvalueinit") {
1736
0
        Kind = SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue;
1737
0
        ParseState = 1;
1738
360
      } else if (Id.str() == "foreign") {
1739
300
        IsObjC = true;
1740
300
        break;
1741
300
      } else if (Id.str() == "jvp" || Id.str() == "vjp") {
1742
48
        IndexSubset *parameterIndices = nullptr;
1743
48
        GenericSignature derivativeGenSig;
1744
        // Parse derivative function kind.
1745
48
        AutoDiffDerivativeFunctionKind derivativeKind(Id.str());
1746
48
        if (!P.consumeIf(tok::period)) {
1747
0
          P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ".");
1748
0
          return true;
1749
0
        }
1750
        // Parse parameter indices.
1751
48
        parameterIndices =
1752
48
            IndexSubset::getFromString(SILMod.getASTContext(), P.Tok.getText());
1753
48
        if (!parameterIndices) {
1754
0
          P.diagnose(P.Tok, diag::invalid_index_subset);
1755
0
          return true;
1756
0
        }
1757
48
        P.consumeToken();
1758
        // Parse derivative generic signature (optional).
1759
48
        if (P.Tok.is(tok::oper_binary_unspaced) && P.Tok.getText() == ".<") {
1760
16
          P.consumeStartingCharacterOfCurrentToken(tok::period);
1761
          // Create a new scope to avoid type redefinition errors.
1762
16
          auto *genericParams = P.maybeParseGenericParams().getPtrOrNull();
1763
16
          assert(genericParams);
1764
0
          derivativeGenSig = handleSILGenericParams(genericParams, &P.SF);
1765
16
        }
1766
0
        DerivativeId = AutoDiffDerivativeFunctionIdentifier::get(
1767
48
            derivativeKind, parameterIndices, derivativeGenSig,
1768
48
            SILMod.getASTContext());
1769
48
        break;
1770
48
      } else {
1771
12
        break;
1772
12
      }
1773
11.6k
    } else
1774
0
      break;
1775
1776
11.6k
  } while (P.consumeIf(tok::period));
1777
1778
  // Construct SILDeclRef.
1779
11.5k
  Result = SILDeclRef(VD, Kind, IsObjC,
1780
11.5k
                      /*distributed=*/false, /*knownToBeLocal=*/false,
1781
11.5k
                      /*runtimeAccessible=*/false,
1782
11.5k
                      SILDeclRef::BackDeploymentKind::None, DerivativeId);
1783
11.5k
  return false;
1784
11.5k
}
1785
1786
/// parseValueName - Parse a value name without a type available yet.
1787
///
1788
///     sil-value-name:
1789
///       sil-local-name
1790
///       'undef'
1791
///
1792
362k
bool SILParser::parseValueName(UnresolvedValueName &Result) {
1793
362k
  Result.Name = P.Tok.getText();
1794
1795
362k
  if (P.Tok.is(tok::kw_undef)) {
1796
8.69k
    Result.NameLoc = P.consumeToken(tok::kw_undef);
1797
8.69k
    return false;
1798
8.69k
  }
1799
1800
  // Parse the local-name.
1801
353k
  if (P.parseToken(tok::sil_local_name, Result.NameLoc,
1802
353k
                   diag::expected_sil_value_name))
1803
0
    return true;
1804
1805
353k
  return false;
1806
353k
}
1807
1808
/// parseValueRef - Parse a value, given a contextual type.
1809
///
1810
///     sil-value-ref:
1811
///       sil-local-name
1812
///
1813
bool SILParser::parseValueRef(SILValue &Result, SILType Ty,
1814
615
                              SILLocation Loc, SILBuilder &B) {
1815
615
  UnresolvedValueName Name;
1816
615
  if (parseValueName(Name)) return true;
1817
615
  Result = getLocalValue(Name, Ty, Loc, B);
1818
615
  return false;
1819
615
}
1820
1821
/// parseTypedValueRef - Parse a type/value reference pair.
1822
///
1823
///    sil-typed-valueref:
1824
///       sil-value-ref ':' sil-type
1825
///
1826
bool SILParser::parseTypedValueRef(SILValue &Result, SourceLoc &Loc,
1827
253k
                                   SILBuilder &B) {
1828
253k
  Loc = P.Tok.getLoc();
1829
1830
253k
  UnresolvedValueName Name;
1831
253k
  SILType Ty;
1832
253k
  if (parseValueName(Name) ||
1833
253k
      P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) ||
1834
253k
      parseSILType(Ty))
1835
6
    return true;
1836
  
1837
253k
  Result = getLocalValue(Name, Ty, RegularLocation(Loc), B);
1838
253k
  return false;
1839
253k
}
1840
1841
/// Look up whether the given string corresponds to a SIL opcode.
1842
static llvm::Optional<SILInstructionKind>
1843
567k
getOpcodeByName(StringRef OpcodeName) {
1844
567k
  return llvm::StringSwitch<llvm::Optional<SILInstructionKind>>(OpcodeName)
1845
567k
#define FULL_INST(Id, TextualName, Parent, MemBehavior, MayRelease)            \
1846
122M
  .Case(#TextualName, SILInstructionKind::Id)
1847
567k
#include "swift/SIL/SILNodes.def"
1848
567k
      .Default(llvm::None);
1849
567k
}
1850
1851
/// getInstructionKind - This method maps the string form of a SIL instruction
1852
/// opcode to an enum.
1853
bool SILParser::parseSILOpcode(SILInstructionKind &Opcode, SourceLoc &OpcodeLoc,
1854
557k
                               StringRef &OpcodeName) {
1855
557k
  OpcodeLoc = P.Tok.getLoc();
1856
557k
  OpcodeName = P.Tok.getText();
1857
  // Parse this textually to avoid Swift keywords (like 'return') from
1858
  // interfering with opcode recognition.
1859
557k
  auto MaybeOpcode = getOpcodeByName(OpcodeName);
1860
557k
  if (!MaybeOpcode) {
1861
0
    P.diagnose(OpcodeLoc, diag::expected_sil_instr_opcode);
1862
0
    return true;
1863
0
  }
1864
1865
557k
  Opcode = MaybeOpcode.value();
1866
557k
  P.consumeToken();
1867
557k
  return false;
1868
557k
}
1869
1870
1.14k
bool SILParser::parseSILDebugInfoExpression(SILDebugInfoExpression &DIExpr) {
1871
1.14k
  if (P.Tok.getText() != "expr")
1872
0
    return true;
1873
1874
  // All operators that we currently support
1875
1.14k
  static const SILDIExprOperator AllOps[] = {
1876
1.14k
    SILDIExprOperator::Dereference,
1877
1.14k
    SILDIExprOperator::Fragment,
1878
1.14k
    SILDIExprOperator::Plus,
1879
1.14k
    SILDIExprOperator::Minus,
1880
1.14k
    SILDIExprOperator::ConstUInt,
1881
1.14k
    SILDIExprOperator::ConstSInt
1882
1.14k
  };
1883
1884
1.16k
  do {
1885
1.16k
    P.consumeToken();
1886
1.16k
    bool FoundOp = false;
1887
1.16k
    auto OpLoc = P.Tok.getLoc();
1888
1.34k
    for (const auto &Op : AllOps) {
1889
1.34k
      const auto *ExprInfo = SILDIExprInfo::get(Op);
1890
1.34k
      auto OpText = ExprInfo->OpText;
1891
1.34k
      if (OpText != P.Tok.getText())
1892
183
        continue;
1893
1.16k
      auto NewOperator = SILDIExprElement::createOperator(Op);
1894
1.16k
      DIExpr.push_back(NewOperator);
1895
1.16k
      P.consumeToken();
1896
1897
      // Ready to parse the operands
1898
1.16k
      for (const auto &OpKind : ExprInfo->OperandKinds) {
1899
75
        if (P.parseToken(tok::colon, diag::expected_sil_colon,
1900
75
                         "debug info expression operand"))
1901
0
          return true;
1902
1903
75
        switch (OpKind) {
1904
51
        case SILDIExprElement::DeclKind: {
1905
51
          SILDeclRef Result;
1906
51
          if (parseSILDeclRef(Result) || !Result.hasDecl()) {
1907
0
            P.diagnose(P.Tok.getLoc(), diag::sil_dbg_expr_expect_operand_kind,
1908
0
                       OpText, "declaration");
1909
0
            return true;
1910
0
          }
1911
51
          auto NewOperand = SILDIExprElement::createDecl(Result.getDecl());
1912
51
          DIExpr.push_back(NewOperand);
1913
51
          break;
1914
51
        }
1915
24
        case SILDIExprElement::ConstIntKind: {
1916
24
          bool IsNegative = false;
1917
24
          if (P.Tok.is(tok::oper_prefix) && P.Tok.getRawText() == "-") {
1918
6
            P.consumeToken();
1919
6
            IsNegative = true;
1920
6
          }
1921
24
          int64_t Val;
1922
24
          if (parseInteger(Val, diag::sil_invalid_constant))
1923
0
            return true;
1924
24
          if (IsNegative)
1925
6
            Val = -Val;
1926
24
          auto NewOperand =
1927
24
            SILDIExprElement::createConstInt(static_cast<uint64_t>(Val));
1928
24
          DIExpr.push_back(NewOperand);
1929
24
          break;
1930
24
        }
1931
0
        default:
1932
0
          P.diagnose(P.Tok.getLoc(), diag::sil_dbg_unknown_expr_part,
1933
0
                     "operand kind");
1934
0
          return true;
1935
75
        }
1936
75
      }
1937
1.16k
      FoundOp = true;
1938
1.16k
      break;
1939
1.16k
    }
1940
1941
1.16k
    if (!FoundOp) {
1942
0
      P.diagnose(OpLoc, diag::sil_dbg_unknown_expr_part, "operator");
1943
0
      return true;
1944
0
    }
1945
1.16k
  } while (P.Tok.is(tok::colon));
1946
1947
1.14k
  return false;
1948
1.14k
}
1949
1950
27.1k
static bool peekSILDebugLocation(Parser &P) {
1951
27.1k
  auto T = P.peekToken().getText();
1952
27.1k
  return P.Tok.is(tok::comma) && (T == "loc" || T == "scope");
1953
27.1k
}
1954
1955
20.0k
bool SILParser::parseSILDebugVar(SILDebugVariable &Var) {
1956
20.0k
  auto parseVariableName = [&, this](bool Consume) -> bool {
1957
6.32k
    if (Consume)
1958
6.27k
      P.consumeToken();
1959
6.32k
    if (P.Tok.getKind() != tok::string_literal) {
1960
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string");
1961
0
      return true;
1962
0
    }
1963
    // Drop the double quotes.
1964
6.32k
    StringRef Val = P.Tok.getText().drop_front().drop_back();
1965
6.32k
    Var.Name = Val;
1966
6.32k
    return false;
1967
6.32k
  };
1968
1969
38.2k
  while (P.Tok.is(tok::comma) && !peekSILDebugLocation(P)) {
1970
18.2k
    P.consumeToken();
1971
18.2k
    StringRef Key = P.Tok.getText();
1972
18.2k
    bool NoConsume = false;
1973
18.2k
    if (P.consumeIf(tok::l_paren)) {
1974
48
      if (parseVerbatim("name"))
1975
0
        return true;
1976
48
      if (parseVariableName(/*Consume=*/false))
1977
0
        return true;
1978
48
      P.consumeToken();
1979
1980
      // Optional operands
1981
48
      if (peekSILDebugLocation(P)) {
1982
48
        P.consumeToken(tok::comma);
1983
1984
48
        bool requireScope = false;
1985
48
        if (P.Tok.getText() == "loc") {
1986
48
          SILLocation VarLoc = RegularLocation::getAutoGeneratedLocation();
1987
48
          if (parseSILLocation(VarLoc))
1988
0
            return true;
1989
48
          Var.Loc = VarLoc;
1990
48
          requireScope = P.consumeIf(tok::comma);
1991
48
        }
1992
1993
48
        if (P.Tok.getText() == "scope" || requireScope) {
1994
48
          parseVerbatim("scope");
1995
48
          SILDebugScope *DS = nullptr;
1996
48
          if (parseScopeRef(DS))
1997
0
            return true;
1998
48
          if (DS)
1999
48
            Var.Scope = DS;
2000
48
        }
2001
48
      }
2002
2003
48
      if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")"))
2004
0
        return true;
2005
2006
48
      NoConsume = true;
2007
18.1k
    } else if (Key == "name") {
2008
6.27k
      if (parseVariableName(/*Consume=*/true))
2009
0
        return true;
2010
11.8k
    } else if (Key == "argno") {
2011
3.32k
      P.consumeToken();
2012
3.32k
      if (P.Tok.getKind() != tok::integer_literal) {
2013
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer");
2014
0
        return true;
2015
0
      }
2016
3.32k
      uint16_t ArgNo;
2017
3.32k
      if (parseIntegerLiteral(P.Tok.getText(), 0, ArgNo))
2018
0
        return true;
2019
3.32k
      Var.ArgNo = ArgNo;
2020
8.55k
    } else if (Key == "expr") {
2021
1.14k
      if (parseSILDebugInfoExpression(Var.DIExpr))
2022
0
        return true;
2023
1.14k
      NoConsume = true;
2024
7.41k
    } else if (Key == "type") {
2025
      // Auxiliary type information
2026
51
      P.consumeToken();
2027
51
      SILType Ty;
2028
51
      if (parseSILType(Ty))
2029
0
        return true;
2030
51
      Var.Type = Ty;
2031
51
      NoConsume = true;
2032
7.36k
    } else if (Key == "let") {
2033
4.38k
      Var.Constant = true;
2034
4.38k
    } else if (Key == "var") {
2035
1.92k
      Var.Constant = false;
2036
1.92k
    } else if (Key == "loc") {
2037
0
      Var.Constant = false;
2038
1.05k
    } else if (Key == "implicit") {
2039
1.05k
      Var.Implicit = true;
2040
1.05k
    } else {
2041
0
      P.diagnose(P.Tok, diag::sil_dbg_unknown_key, Key);
2042
0
      return true;
2043
0
    }
2044
2045
18.2k
    if (!NoConsume)
2046
16.9k
      P.consumeToken();
2047
18.2k
  }
2048
20.0k
  return false;
2049
20.0k
}
2050
2051
bool SILParser::parseSILBBArgsAtBranch(SmallVector<SILValue, 6> &Args,
2052
197k
                                       SILBuilder &B) {
2053
197k
  if (P.Tok.is(tok::l_paren)) {
2054
10.6k
    SourceLoc LParenLoc = P.consumeToken(tok::l_paren);
2055
10.6k
    SourceLoc RParenLoc;
2056
2057
10.6k
    bool HasError = false;
2058
10.6k
    if (P.parseList(tok::r_paren, LParenLoc, RParenLoc,
2059
10.6k
                    /*AllowSepAfterLast=*/false,
2060
10.6k
                    diag::sil_basicblock_arg_rparen,
2061
12.5k
                    [&]() -> ParserStatus {
2062
12.5k
                      SILValue Arg;
2063
12.5k
                      SourceLoc ArgLoc;
2064
12.5k
                      if (parseTypedValueRef(Arg, ArgLoc, B)) {
2065
3
                        HasError = true;
2066
3
                        return makeParserError();
2067
3
                      }
2068
12.5k
                      Args.push_back(Arg);
2069
12.5k
                      return makeParserSuccess();
2070
12.5k
                    }).isErrorOrHasCompletion() || HasError)
2071
3
      return true;
2072
10.6k
  }
2073
197k
  return false;
2074
197k
}
2075
2076
/// Parse the substitution list for an apply instruction or
2077
/// specialized protocol conformance.
2078
bool SILParser::parseSubstitutions(SmallVectorImpl<ParsedSubstitution> &parsed,
2079
                                   GenericSignature GenericSig,
2080
53.8k
                                   GenericParamList *GenericParams) {
2081
  // Check for an opening '<' bracket.
2082
53.8k
  if (!P.startsWithLess(P.Tok))
2083
46.4k
    return false;
2084
  
2085
7.43k
  if (!GenericSig)
2086
7.28k
    GenericSig = ContextGenericSig;
2087
7.43k
  if (GenericParams == nullptr)
2088
7.28k
    GenericParams = ContextGenericParams;
2089
2090
7.43k
  P.consumeStartingLess();
2091
  
2092
  // Parse a list of Substitutions.
2093
8.79k
  do {
2094
8.79k
    SourceLoc Loc = P.Tok.getLoc();
2095
2096
    // Parse substitution as AST type.
2097
8.79k
    ParserResult<TypeRepr> TyR = P.parseType();
2098
8.79k
    if (TyR.isNull())
2099
0
      return true;
2100
2101
8.79k
    auto Ty = performTypeResolution(TyR.get(), /*IsSILType=*/false, GenericSig,
2102
8.79k
                                    GenericParams);
2103
8.79k
    if (GenericSig) {
2104
3.73k
      Ty = GenericSig.getGenericEnvironment()->mapTypeIntoContext(Ty);
2105
3.73k
    }
2106
2107
8.79k
    if (Ty->hasError())
2108
0
      return true;
2109
8.79k
    parsed.push_back({Loc, Ty});
2110
8.79k
  } while (P.consumeIf(tok::comma));
2111
  
2112
  // Consume the closing '>'.
2113
7.43k
  if (!P.startsWithGreater(P.Tok)) {
2114
0
    P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ">");
2115
0
    return true;
2116
0
  }
2117
7.43k
  P.consumeStartingGreater();
2118
  
2119
7.43k
  return false;
2120
7.43k
}
2121
2122
/// Collect conformances by looking up the conformance from replacement
2123
/// type and protocol decl.
2124
static bool getConformancesForSubstitution(Parser &P,
2125
              ArrayRef<ProtocolDecl*> protocols,
2126
              Type subReplacement,
2127
              SourceLoc loc,
2128
870
              SmallVectorImpl<ProtocolConformanceRef> &conformances) {
2129
870
  auto M = P.SF.getParentModule();
2130
2131
894
  for (auto protoDecl : protocols) {
2132
894
    auto conformance = M->lookupConformance(subReplacement, protoDecl);
2133
894
    if (conformance.isInvalid()) {
2134
0
      P.diagnose(loc, diag::sil_substitution_mismatch, subReplacement,
2135
0
                 protoDecl->getDeclaredInterfaceType());
2136
0
      return true;
2137
0
    }
2138
894
    conformances.push_back(conformance);
2139
894
  }
2140
2141
870
  return false;
2142
870
}
2143
2144
/// Reconstruct an AST substitution map from parsed substitutions.
2145
SubstitutionMap getApplySubstitutionsFromParsed(
2146
                             SILParser &SP,
2147
                             GenericSignature genericSig,
2148
7.43k
                             ArrayRef<ParsedSubstitution> parses) {
2149
7.43k
  if (parses.empty()) {
2150
0
    assert(!genericSig);
2151
0
    return SubstitutionMap();
2152
0
  }
2153
2154
7.43k
  assert(genericSig);
2155
2156
0
  auto loc = parses[0].loc;
2157
2158
  // Ensure that we have the right number of type arguments.
2159
7.43k
  if (parses.size() != genericSig.getGenericParams().size()) {
2160
0
    bool hasTooFew = parses.size() < genericSig.getGenericParams().size();
2161
0
    SP.P.diagnose(loc,
2162
0
                  hasTooFew ? diag::sil_missing_substitutions
2163
0
                            : diag::sil_too_many_substitutions);
2164
0
    return SubstitutionMap();
2165
0
  }
2166
2167
7.43k
  bool failed = false;
2168
7.43k
  auto subMap = SubstitutionMap::get(
2169
7.43k
      genericSig,
2170
13.0k
      [&](SubstitutableType *type) -> Type {
2171
13.0k
        auto genericParam = dyn_cast<GenericTypeParamType>(type);
2172
13.0k
        if (!genericParam)
2173
0
          return nullptr;
2174
2175
13.0k
        auto index = genericSig->getGenericParamOrdinal(genericParam);
2176
13.0k
        assert(index < genericSig.getGenericParams().size());
2177
0
        assert(index < parses.size());
2178
2179
        // Provide the replacement type.
2180
0
        return parses[index].replacement;
2181
13.0k
      },
2182
7.43k
      [&](CanType dependentType, Type replacementType,
2183
7.43k
          ProtocolDecl *proto) -> ProtocolConformanceRef {
2184
4.43k
        auto M = SP.P.SF.getParentModule();
2185
4.43k
        if (auto conformance = M->lookupConformance(replacementType, proto))
2186
4.43k
          return conformance;
2187
2188
0
        SP.P.diagnose(loc, diag::sil_substitution_mismatch, replacementType,
2189
0
                      proto->getDeclaredInterfaceType());
2190
0
        failed = true;
2191
2192
0
        return ProtocolConformanceRef(proto);
2193
4.43k
      });
2194
2195
7.43k
  return failed ? SubstitutionMap() : subMap;
2196
7.43k
}
2197
2198
static ArrayRef<ProtocolConformanceRef>
2199
collectExistentialConformances(Parser &P, CanType conformingType, SourceLoc loc,
2200
1.58k
                               CanType protocolType) {
2201
1.58k
  auto layout = protocolType.getExistentialLayout();
2202
2203
1.58k
  if (layout.requiresClass()) {
2204
369
    if (!conformingType->mayHaveSuperclass() &&
2205
369
        !conformingType->isObjCExistentialType()) {
2206
0
      P.diagnose(loc, diag::sil_not_class, conformingType);
2207
0
    }
2208
369
  }
2209
2210
  // FIXME: Check superclass also.
2211
2212
1.58k
  auto protocols = layout.getProtocols();
2213
1.58k
  if (protocols.empty())
2214
714
    return {};
2215
2216
870
  SmallVector<ProtocolConformanceRef, 2> conformances;
2217
870
  getConformancesForSubstitution(P, protocols, conformingType,
2218
870
                                 loc, conformances);
2219
2220
870
  return P.Context.AllocateCopy(conformances);
2221
1.58k
}
2222
2223
/// sil-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+
2224
1.42k
bool SILParser::parseSILLocation(SILLocation &Loc) {
2225
1.42k
  if (parseVerbatim("loc"))
2226
0
    return true;
2227
2228
1.42k
  bool isAutoGenerated = false;
2229
1.42k
  if (P.Tok.isAnyOperator() && P.Tok.getText().startswith("*")) {
2230
33
    isAutoGenerated = true;
2231
33
    P.consumeStartingCharacterOfCurrentToken();
2232
33
  }
2233
2234
1.42k
  if (P.Tok.getKind() != tok::string_literal) {
2235
0
    P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string");
2236
0
    return true;
2237
0
  }
2238
  // Drop the double quotes.
2239
1.42k
  StringRef File = P.Tok.getText().drop_front().drop_back();
2240
1.42k
  P.consumeToken(tok::string_literal);
2241
1.42k
  if (P.parseToken(tok::colon, diag::expected_colon_in_sil_location))
2242
0
    return true;
2243
1.42k
  unsigned Line = 0;
2244
1.42k
  if (parseInteger(Line, diag::sil_invalid_line_in_sil_location))
2245
0
    return true;
2246
1.42k
  if (P.parseToken(tok::colon, diag::expected_colon_in_sil_location))
2247
0
    return true;
2248
1.42k
  unsigned Column = 0;
2249
1.42k
  if (parseInteger(Column, diag::sil_invalid_column_in_sil_location))
2250
0
    return true;
2251
2252
1.42k
  auto fnl = SILLocation::FilenameAndLocation::alloc(Line, Column,
2253
1.42k
    P.Context.getIdentifier(File).str().data(), SILMod);
2254
2255
1.42k
  Loc = RegularLocation(fnl);
2256
2257
1.42k
  if (isAutoGenerated)
2258
33
    Loc.markAutoGenerated();
2259
2260
1.42k
  return false;
2261
1.42k
}
2262
2263
1.45k
bool SILParser::parseScopeRef(SILDebugScope *&DS) {
2264
1.45k
  unsigned Slot;
2265
1.45k
  SourceLoc SlotLoc = P.Tok.getLoc();
2266
1.45k
  if (parseInteger(Slot, diag::sil_invalid_scope_slot))
2267
0
    return true;
2268
2269
1.45k
  DS = TUState.ScopeSlots[Slot];
2270
1.45k
  if (!DS) {
2271
0
    P.diagnose(SlotLoc, diag::sil_scope_undeclared, Slot);
2272
0
    return true;
2273
0
  }
2274
1.45k
  return false;
2275
1.45k
}
2276
2277
bool SILParser::parseForwardingOwnershipKind(
2278
58.9k
    ValueOwnershipKind &forwardingKind) {
2279
58.9k
  if (P.Tok.is(tok::comma)) {
2280
337
    P.consumeToken();
2281
337
    parsedComma = true;
2282
337
  }
2283
58.9k
  if (!parsedComma)
2284
58.5k
    return false;
2285
2286
376
  if (P.Tok.is(tok::identifier) && P.Tok.getText() == "forwarding") {
2287
88
    parsedComma = false;
2288
88
    P.consumeToken();
2289
88
    return P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")
2290
88
           || parseSILOwnership(forwardingKind);
2291
88
  }
2292
288
  return false;
2293
376
}
2294
2295
///  (',' sil-loc)? (',' sil-scope-ref)?
2296
559k
bool SILParser::parseSILDebugLocation(SILLocation &L, SILBuilder &B) {
2297
  // Parse the debug information, if any.
2298
559k
  if (P.Tok.is(tok::comma)) {
2299
1.19k
    P.consumeToken();
2300
1.19k
    parsedComma = true;
2301
1.19k
  }
2302
559k
  if (!parsedComma)
2303
557k
    return false;
2304
2305
1.48k
  bool requireScope = false;
2306
1.48k
  if (P.Tok.getText() == "loc") {
2307
1.19k
    parsedComma = false;
2308
1.19k
    if (parseSILLocation(L))
2309
0
      return true;
2310
2311
1.19k
    if (P.Tok.is(tok::comma)) {
2312
1.05k
      P.consumeToken();
2313
1.05k
      requireScope = true;
2314
1.05k
    }
2315
1.19k
  }
2316
1.48k
  if (P.Tok.getText() == "scope" || requireScope) {
2317
1.34k
    parsedComma = false;
2318
1.34k
    parseVerbatim("scope");
2319
1.34k
    SILDebugScope *DS = nullptr;
2320
1.34k
    if (parseScopeRef(DS))
2321
0
      return true;
2322
1.34k
    if (DS)
2323
1.34k
      B.setCurrentDebugScope(DS);
2324
1.34k
  }
2325
1.48k
  return false;
2326
1.48k
}
2327
2328
static bool parseAssignByWrapperMode(AssignByWrapperInst::Mode &Result,
2329
15
                                          SILParser &P) {
2330
15
  StringRef Str;
2331
  // If we do not parse '[' ... ']', we have unknown. Set value and return.
2332
15
  if (!parseSILOptional(Str, P)) {
2333
0
    Result = AssignByWrapperInst::Unknown;
2334
0
    return false;
2335
0
  }
2336
2337
  // Then try to parse one of our other initialization kinds. We do not support
2338
  // parsing unknown here so we use that as our fail value.
2339
15
  auto Tmp = llvm::StringSwitch<AssignByWrapperInst::Mode>(Str)
2340
15
        .Case("init", AssignByWrapperInst::Initialization)
2341
15
        .Case("assign", AssignByWrapperInst::Assign)
2342
15
        .Case("assign_wrapped_value", AssignByWrapperInst::AssignWrappedValue)
2343
15
        .Default(AssignByWrapperInst::Unknown);
2344
2345
  // Thus return true (following the conventions in this file) if we fail.
2346
15
  if (Tmp == AssignByWrapperInst::Unknown)
2347
0
    return true;
2348
2349
  // Otherwise, assign Result and return false.
2350
15
  Result = Tmp;
2351
15
  return false;
2352
15
}
2353
2354
static bool parseAssignOrInitMode(AssignOrInitInst::Mode &Result,
2355
9
                                  SILParser &P) {
2356
9
  StringRef Str;
2357
9
  if (!parseSILOptional(Str, P)) {
2358
9
    Result = AssignOrInitInst::Unknown;
2359
9
    return false;
2360
9
  }
2361
2362
0
  auto Tmp = llvm::StringSwitch<AssignOrInitInst::Mode>(Str)
2363
0
      .Case("init", AssignOrInitInst::Init)
2364
0
      .Case("set", AssignOrInitInst::Set)
2365
0
      .Default(AssignOrInitInst::Unknown);
2366
2367
  // Return true (following the conventions in this file) if we fail.
2368
0
  if (Tmp == AssignOrInitInst::Unknown)
2369
0
    return true;
2370
2371
0
  Result = Tmp;
2372
0
  return false;
2373
0
}
2374
2375
static bool
2376
parseAssignOrInitAssignments(llvm::SmallVectorImpl<unsigned> &assignments,
2377
9
                             SILParser &SP) {
2378
  // Could be more than one [assign=<index>] attributes.
2379
9
  for (;;) {
2380
9
    SourceLoc loc;
2381
2382
    // Consume '['
2383
9
    if (!SP.P.consumeIf(tok::l_square))
2384
9
      return false;
2385
2386
    // Consume the identifier which should be "assign"
2387
0
    {
2388
0
      Identifier Id;
2389
0
      if (SP.parseSILIdentifier(Id, loc, diag::expected_in_attribute_list))
2390
0
        return true;
2391
2392
0
      if (!Id.is("assign")) {
2393
0
        SP.P.diagnose(loc, diag::sil_invalid_attribute_for_expected, Id.str(),
2394
0
                      "assign");
2395
0
        return true;
2396
0
      }
2397
0
    }
2398
2399
0
    uint64_t index;
2400
2401
    // Consume '='
2402
0
    if (!SP.P.consumeIf(tok::equal)) {
2403
0
      SP.P.diagnose(loc, diag::expected_equal_in_sil_instr);
2404
0
      return true;
2405
0
    }
2406
2407
    // Consume the property index.
2408
0
    if (SP.parseInteger(index, diag::expected_in_attribute_list))
2409
0
      return true;
2410
2411
    // Consume ']'
2412
0
    if (SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list))
2413
0
      return true;
2414
2415
0
    assignments.push_back(index);
2416
0
  }
2417
9
}
2418
2419
// Parse a list of integer indices, prefaced with the given string label.
2420
// Returns true on error.
2421
static bool parseIndexList(Parser &P, StringRef label,
2422
                           SmallVectorImpl<unsigned> &indices,
2423
1.56k
                           const Diagnostic &parseIndexDiag) {
2424
1.56k
  SourceLoc loc;
2425
  // Parse `[<label> <integer_literal>...]`.
2426
1.56k
  if (P.parseToken(tok::l_square, diag::sil_autodiff_expected_lsquare,
2427
1.56k
                   "index list") ||
2428
1.56k
      P.parseSpecificIdentifier(
2429
1.56k
          label, diag::sil_autodiff_expected_index_list_label, label))
2430
0
    return true;
2431
3.56k
  while (P.Tok.is(tok::integer_literal)) {
2432
1.99k
    unsigned index;
2433
1.99k
    if (P.parseUnsignedInteger(index, loc, parseIndexDiag))
2434
0
      return true;
2435
1.99k
    indices.push_back(index);
2436
1.99k
  }
2437
1.56k
  if (P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare,
2438
1.56k
                   "index list"))
2439
0
    return true;
2440
1.56k
  return false;
2441
1.56k
}
2442
2443
/// Parse a differentiability kind, an autodiff config, and a function name for
2444
/// a differentiability witness. Returns true on error.
2445
///
2446
/// sil-differentiability-witness-config-and-function ::=
2447
///   '[' differentiability-kind ']'
2448
///   '[' 'parameters' index-subset ']'
2449
///   '[' 'results' index-subset ']'
2450
///   ('<' 'where' derivative-generic-signature-requirements '>')?
2451
///   sil-function-ref
2452
///
2453
/// e.g. [reverse] [parameters 0 1] [results 0] <T where T: Differentiable>
2454
///      @foo : <T> $(T) -> T
2455
static bool parseSILDifferentiabilityWitnessConfigAndFunction(
2456
    Parser &P, SILParser &SP, SILLocation L,
2457
    DifferentiabilityKind &resultDiffKind, AutoDiffConfig &resultConfig,
2458
627
    SILFunction *&resultOrigFn) {
2459
  // Parse differentiability kind.
2460
627
  if (P.parseToken(tok::l_square, diag::sil_autodiff_expected_lsquare,
2461
627
                   "differentiability kind"))
2462
0
    return true;
2463
627
  resultDiffKind = llvm::StringSwitch<DifferentiabilityKind>(P.Tok.getText())
2464
627
      .Case("forward", DifferentiabilityKind::Forward)
2465
627
      .Case("reverse", DifferentiabilityKind::Reverse)
2466
627
      .Case("normal", DifferentiabilityKind::Normal)
2467
627
      .Case("linear", DifferentiabilityKind::Linear)
2468
627
      .Default(DifferentiabilityKind::NonDifferentiable);
2469
627
  if (resultDiffKind == DifferentiabilityKind::NonDifferentiable) {
2470
0
    P.diagnose(P.Tok, diag::sil_diff_witness_unknown_kind, P.Tok.getText());
2471
0
    return true;
2472
0
  }
2473
627
  P.consumeToken(tok::identifier);
2474
627
  if (P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare,
2475
627
                   "differentiability kind"))
2476
0
    return true;
2477
  // Parse parameter and result indices.
2478
627
  SmallVector<unsigned, 8> rawParameterIndices;
2479
627
  SmallVector<unsigned, 8> rawResultIndices;
2480
627
  if (parseIndexList(P, "parameters", rawParameterIndices,
2481
627
                     diag::sil_autodiff_expected_parameter_index))
2482
0
    return true;
2483
627
  if (parseIndexList(P, "results", rawResultIndices,
2484
627
                     diag::sil_autodiff_expected_result_index))
2485
0
    return true;
2486
  // Parse witness generic parameter clause.
2487
627
  GenericSignature witnessGenSig = GenericSignature();
2488
627
  SourceLoc witnessGenSigStartLoc = P.getEndOfPreviousLoc();
2489
627
  {
2490
627
    auto *genericParams = P.maybeParseGenericParams().getPtrOrNull();
2491
627
    if (genericParams) {
2492
240
      witnessGenSig = handleSILGenericParams(genericParams, &P.SF);
2493
240
    }
2494
627
  }
2495
  // Parse original function name and type.
2496
627
  if (SP.parseSILFunctionRef(L, resultOrigFn))
2497
0
    return true;
2498
  // Resolve parsed witness generic signature.
2499
627
  if (witnessGenSig) {
2500
240
    auto origGenSig =
2501
240
        resultOrigFn->getLoweredFunctionType()->getSubstGenericSignature();
2502
    // Check whether original function generic signature and parsed witness
2503
    // generic have the same generic parameters.
2504
240
    auto areGenericParametersConsistent = [&]() {
2505
240
      llvm::SmallDenseSet<GenericParamKey, 4> genericParamKeys;
2506
240
      for (auto origGP : origGenSig.getGenericParams())
2507
240
        genericParamKeys.insert(GenericParamKey(origGP.getPointer()));
2508
240
      for (auto *witnessGP : witnessGenSig.getGenericParams())
2509
240
        if (!genericParamKeys.erase(GenericParamKey(witnessGP)))
2510
0
          return false;
2511
240
      return genericParamKeys.empty();
2512
240
    };
2513
240
    if (!areGenericParametersConsistent()) {
2514
0
      P.diagnose(witnessGenSigStartLoc,
2515
0
                 diag::sil_diff_witness_invalid_generic_signature,
2516
0
                 witnessGenSig->getAsString(), origGenSig->getAsString());
2517
0
      return true;
2518
0
    }
2519
    // Combine parsed witness requirements with original function generic
2520
    // signature requirements to form full witness generic signature.
2521
240
    SmallVector<Requirement, 4> witnessRequirements(
2522
240
        witnessGenSig.getRequirements().begin(),
2523
240
        witnessGenSig.getRequirements().end());
2524
240
    witnessGenSig = buildGenericSignature(
2525
240
        P.Context, origGenSig,
2526
240
        /*addedGenericParams=*/{},
2527
240
        std::move(witnessRequirements));
2528
240
  }
2529
627
  auto origFnType = resultOrigFn->getLoweredFunctionType();
2530
627
  auto *parameterIndices = IndexSubset::get(
2531
627
      P.Context, origFnType->getNumParameters(), rawParameterIndices);
2532
627
  auto *resultIndices = IndexSubset::get(P.Context,
2533
627
                                         origFnType->getNumResults() +
2534
627
                                         origFnType->getNumIndirectMutatingParameters(),
2535
627
                                         rawResultIndices);
2536
627
  resultConfig = AutoDiffConfig(parameterIndices, resultIndices, witnessGenSig);
2537
627
  return false;
2538
627
}
2539
2540
5.22k
bool SILParser::parseSILDeclRef(SILDeclRef &Member, bool FnTypeRequired) {
2541
5.22k
  SourceLoc TyLoc;
2542
5.22k
  SmallVector<ValueDecl *, 4> values;
2543
5.22k
  if (parseSILDeclRef(Member, values))
2544
0
    return true;
2545
2546
  // : ( or : < means that what follows is function type.
2547
5.22k
  if (!P.Tok.is(tok::colon))
2548
291
    return false;
2549
2550
4.93k
  if (FnTypeRequired &&
2551
4.93k
      !P.peekToken().is(tok::l_paren) &&
2552
4.93k
      !P.startsWithLess(P.peekToken()))
2553
2.22k
    return false;
2554
2555
  // Type of the SILDeclRef is optional to be compatible with the old format.
2556
2.71k
  if (!P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")) {
2557
    // Parse the type for SILDeclRef.
2558
2.71k
    ParserResult<TypeRepr> TyR = P.parseType();
2559
2.71k
    if (TyR.isNull())
2560
0
      return true;
2561
2562
2.71k
    bindSILGenericParams(TyR.get());
2563
2564
    // The type can be polymorphic.
2565
2.71k
    GenericSignature genericSig;
2566
2.71k
    GenericParamList *genericParams = nullptr;
2567
2.71k
    if (auto *fnType = dyn_cast<FunctionTypeRepr>(TyR.get())) {
2568
2.71k
      genericSig = fnType->getGenericSignature();
2569
2.71k
      genericParams = fnType->getGenericParams();
2570
2.71k
    }
2571
2572
2.71k
    const auto Ty = performTypeResolution(TyR.get(), /*IsSILType=*/false,
2573
2.71k
                                          genericSig, genericParams);
2574
2.71k
    if (Ty->hasError())
2575
0
      return true;
2576
2577
    // Pick the ValueDecl that has the right type.
2578
2.71k
    ValueDecl *TheDecl = nullptr;
2579
2.71k
    auto declTy = Ty->getCanonicalType();
2580
2.77k
    for (unsigned I = 0, E = values.size(); I < E; ++I) {
2581
2.77k
      auto *decl = values[I];
2582
2583
2.77k
      auto lookupTy =
2584
2.77k
        decl->getInterfaceType()
2585
2.77k
            ->removeArgumentLabels(decl->getNumCurryLevels());
2586
2.77k
      if (declTy == lookupTy->getCanonicalType()) {
2587
2.71k
        TheDecl = decl;
2588
        // Update SILDeclRef to point to the right Decl.
2589
2.71k
        Member.loc = decl;
2590
2.71k
        break;
2591
2.71k
      }
2592
63
      if (values.size() == 1 && !TheDecl) {
2593
0
        P.diagnose(TyLoc, diag::sil_member_decl_type_mismatch, declTy,
2594
0
                   lookupTy);
2595
0
        return true;
2596
0
      }
2597
63
    }
2598
2.71k
    if (!TheDecl) {
2599
0
      P.diagnose(TyLoc, diag::sil_member_decl_not_found);
2600
0
      return true;
2601
0
    }
2602
2.71k
  }
2603
2.71k
  return false;
2604
2.71k
}
2605
2606
bool
2607
SILParser::parseKeyPathPatternComponent(KeyPathPatternComponent &component,
2608
                                        SmallVectorImpl<SILType> &operandTypes,
2609
                                        SourceLoc componentLoc,
2610
                                        Identifier componentKind,
2611
                                        SILLocation InstLoc,
2612
                                        GenericSignature patternSig,
2613
531
                                        GenericParamList *patternParams) {
2614
531
   auto parseComponentIndices =
2615
531
     [&](SmallVectorImpl<KeyPathPatternComponent::Index> &indexes) -> bool {
2616
90
       while (true) {
2617
90
         unsigned index;
2618
90
         CanType formalTy;
2619
90
         SILType loweredTy;
2620
90
         if (P.parseToken(tok::oper_prefix,
2621
90
                          diag::expected_tok_in_sil_instr, "%")
2622
90
             || P.parseToken(tok::sil_dollar,
2623
90
                             diag::expected_tok_in_sil_instr, "$"))
2624
0
           return true;
2625
         
2626
90
         if (!P.Tok.is(tok::integer_literal)
2627
90
             || parseIntegerLiteral(P.Tok.getText(), 0, index))
2628
0
           return true;
2629
         
2630
90
         P.consumeToken(tok::integer_literal);
2631
         
2632
90
         SourceLoc formalTyLoc;
2633
90
         SourceLoc loweredTyLoc;
2634
90
         GenericSignature ignoredParsedSig;
2635
90
         GenericParamList *ignoredParsedParams = nullptr;
2636
90
         if (P.parseToken(tok::colon,
2637
90
                          diag::expected_tok_in_sil_instr, ":")
2638
90
             || P.parseToken(tok::sil_dollar,
2639
90
                             diag::expected_tok_in_sil_instr, "$")
2640
90
             || parseASTType(formalTy, formalTyLoc,
2641
90
                             patternSig, patternParams)
2642
90
             || P.parseToken(tok::colon,
2643
90
                             diag::expected_tok_in_sil_instr, ":")
2644
90
             || parseSILType(loweredTy, loweredTyLoc,
2645
90
                             ignoredParsedSig, ignoredParsedParams,
2646
90
                             patternSig, patternParams))
2647
0
           return true;
2648
         
2649
90
         if (patternSig)
2650
39
           loweredTy = SILType::getPrimitiveType(loweredTy.getRawASTType()
2651
39
                                                     ->mapTypeOutOfContext()
2652
39
                                                     ->getCanonicalType(),
2653
39
                                                 loweredTy.getCategory());
2654
2655
         // Formal type must be hashable.
2656
90
         auto proto = P.Context.getProtocol(KnownProtocolKind::Hashable);
2657
90
         Type contextFormalTy = formalTy;
2658
90
         if (patternSig) {
2659
39
           contextFormalTy = patternSig.getGenericEnvironment()
2660
39
              ->mapTypeIntoContext(formalTy);
2661
39
         }
2662
90
         auto lookup = P.SF.getParentModule()->lookupConformance(
2663
90
                                                 contextFormalTy, proto);
2664
90
         if (lookup.isInvalid()) {
2665
0
           P.diagnose(formalTyLoc,
2666
0
                      diag::sil_keypath_index_not_hashable,
2667
0
                      formalTy);
2668
0
           return true;
2669
0
         }
2670
90
         auto conformance = ProtocolConformanceRef(lookup);
2671
2672
90
         indexes.push_back({index, formalTy, loweredTy, conformance});
2673
         
2674
90
         if (operandTypes.size() <= index)
2675
90
           operandTypes.resize(index+1);
2676
90
         if (operandTypes[index] && operandTypes[index] != loweredTy) {
2677
0
           P.diagnose(loweredTyLoc,
2678
0
                      diag::sil_keypath_index_operand_type_conflict, index,
2679
0
                      operandTypes[index].getRawASTType(),
2680
0
                      loweredTy.getRawASTType());
2681
0
           return true;
2682
0
         }
2683
90
         operandTypes[index] = loweredTy;
2684
         
2685
90
         if (P.consumeIf(tok::comma))
2686
33
           continue;
2687
57
         if (P.consumeIf(tok::r_square))
2688
57
           break;
2689
0
         return true;
2690
57
       }
2691
57
       return false;
2692
57
     };
2693
  
2694
531
  if (componentKind.str() == "stored_property") {
2695
243
    ValueDecl *prop;
2696
243
    CanType ty;
2697
243
    if (parseSILDottedPath(prop)
2698
243
        || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")
2699
243
        || P.parseToken(tok::sil_dollar,
2700
243
                        diag::expected_tok_in_sil_instr, "$")
2701
243
        || parseASTType(ty, patternSig, patternParams))
2702
0
      return true;
2703
243
    component =
2704
243
      KeyPathPatternComponent::forStoredProperty(cast<VarDecl>(prop), ty);
2705
243
    return false;
2706
288
  } else if (componentKind.str() == "gettable_property"
2707
288
             || componentKind.str() == "settable_property") {
2708
168
    bool isSettable = componentKind.str()[0] == 's';
2709
    
2710
168
    CanType componentTy;
2711
168
    if (P.parseToken(tok::sil_dollar,diag::expected_tok_in_sil_instr,"$")
2712
168
        || parseASTType(componentTy, patternSig, patternParams)
2713
168
        || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
2714
0
      return true;
2715
    
2716
168
    SILFunction *idFn = nullptr;
2717
168
    SILDeclRef idDecl;
2718
168
    VarDecl *idProperty = nullptr;
2719
168
    SILFunction *getter = nullptr;
2720
168
    SILFunction *setter = nullptr;
2721
168
    SILFunction *equals = nullptr;
2722
168
    SILFunction *hash = nullptr;
2723
168
    AbstractStorageDecl *externalDecl = nullptr;
2724
168
    SubstitutionMap externalSubs;
2725
168
    SmallVector<KeyPathPatternComponent::Index, 4> indexes;
2726
645
    while (true) {
2727
645
      Identifier subKind;
2728
645
      SourceLoc subKindLoc;
2729
645
      if (parseSILIdentifier(subKind, subKindLoc,
2730
645
                             diag::sil_keypath_expected_component_kind))
2731
0
        return true;
2732
2733
645
      if (subKind.str() == "id") {
2734
        // The identifier can be either a function ref, a SILDeclRef
2735
        // to a class or protocol method, or a decl ref to a property:
2736
        // @static_fn_ref : $...
2737
        // #Type.method!whatever : (T) -> ...
2738
        // ##Type.property
2739
168
        if (P.Tok.is(tok::at_sign)) {
2740
138
          if (parseSILFunctionRef(InstLoc, idFn))
2741
0
            return true;
2742
138
        } else if (P.Tok.is(tok::pound)) {
2743
30
          if (P.peekToken().is(tok::pound)) {
2744
9
            ValueDecl *propertyValueDecl;
2745
9
            P.consumeToken(tok::pound);
2746
9
            if (parseSILDottedPath(propertyValueDecl))
2747
0
              return true;
2748
9
            idProperty = cast<VarDecl>(propertyValueDecl);
2749
21
          } else if (parseSILDeclRef(idDecl, /*fnType*/ true))
2750
0
            return true;
2751
30
        } else {
2752
0
          P.diagnose(subKindLoc, diag::expected_tok_in_sil_instr, "# or @");
2753
0
          return true;
2754
0
        }
2755
477
      } else if (subKind.str() == "getter" || subKind.str() == "setter") {
2756
291
        bool isSetter = subKind.str()[0] == 's';
2757
291
        if (parseSILFunctionRef(InstLoc, isSetter ? setter : getter))
2758
0
          return true;
2759
291
      } else if (subKind.str() == "indices") {
2760
57
        if (P.parseToken(tok::l_square,
2761
57
                         diag::expected_tok_in_sil_instr, "[")
2762
57
            || parseComponentIndices(indexes))
2763
0
          return true;
2764
129
      } else if (subKind.str() == "indices_equals") {
2765
57
        if (parseSILFunctionRef(InstLoc, equals))
2766
0
          return true;
2767
72
      } else if (subKind.str() == "indices_hash") {
2768
57
        if (parseSILFunctionRef(InstLoc, hash))
2769
0
          return true;
2770
57
      } else if (subKind.str() == "external") {
2771
15
        ValueDecl *parsedExternalDecl;
2772
15
        SmallVector<ParsedSubstitution, 4> parsedSubs;
2773
2774
15
        if (parseSILDottedPath(parsedExternalDecl)
2775
15
            || parseSubstitutions(parsedSubs, patternSig, patternParams))
2776
0
          return true;
2777
2778
15
        externalDecl = cast<AbstractStorageDecl>(parsedExternalDecl);
2779
2780
15
        if (!parsedSubs.empty()) {
2781
15
          auto genericSig = externalDecl->getInnermostDeclContext()
2782
15
                                        ->getGenericSignatureOfContext();
2783
15
          if (!genericSig) {
2784
0
            P.diagnose(P.Tok,
2785
0
                       diag::sil_substitutions_on_non_polymorphic_type);
2786
0
            return true;
2787
0
          }
2788
15
          externalSubs = getApplySubstitutionsFromParsed(*this, genericSig,
2789
15
                                                         parsedSubs);
2790
15
          if (!externalSubs) return true;
2791
2792
          // Map the substitutions out of the pattern context so that they
2793
          // use interface types.
2794
15
          externalSubs =
2795
15
            externalSubs.mapReplacementTypesOutOfContext().getCanonical();
2796
15
        }
2797
2798
15
      } else {
2799
0
        P.diagnose(subKindLoc, diag::sil_keypath_unknown_component_kind,
2800
0
                   subKind);
2801
0
        return true;
2802
0
      }
2803
      
2804
645
      if (!P.consumeIf(tok::comma))
2805
168
        break;
2806
645
    }
2807
    
2808
168
    if ((idFn == nullptr && idDecl.isNull() && idProperty == nullptr)
2809
168
        || getter == nullptr
2810
168
        || (isSettable && setter == nullptr)) {
2811
0
      P.diagnose(componentLoc,
2812
0
                 diag::sil_keypath_computed_property_missing_part,
2813
0
                 isSettable);
2814
0
      return true;
2815
0
    }
2816
    
2817
168
    if ((idFn != nullptr) + (!idDecl.isNull()) + (idProperty != nullptr)
2818
168
          != 1) {
2819
0
      P.diagnose(componentLoc,
2820
0
                 diag::sil_keypath_computed_property_missing_part,
2821
0
                 isSettable);
2822
0
      return true;
2823
0
    }
2824
    
2825
168
    KeyPathPatternComponent::ComputedPropertyId id;
2826
168
    if (idFn)
2827
138
      id = idFn;
2828
30
    else if (!idDecl.isNull())
2829
21
      id = idDecl;
2830
9
    else if (idProperty)
2831
9
      id = idProperty;
2832
0
    else
2833
0
      llvm_unreachable("no id?!");
2834
    
2835
168
    auto indexesCopy = P.Context.AllocateCopy(indexes);
2836
    
2837
168
    if (!indexes.empty() && (!equals || !hash)) {
2838
0
      P.diagnose(componentLoc,
2839
0
                 diag::sil_keypath_computed_property_missing_part,
2840
0
                 isSettable);
2841
0
    }
2842
    
2843
168
    if (isSettable) {
2844
123
      component = KeyPathPatternComponent::forComputedSettableProperty(
2845
123
                             id, getter, setter,
2846
123
                             indexesCopy, equals, hash,
2847
123
                             externalDecl, externalSubs, componentTy);
2848
123
    } else {
2849
45
      component = KeyPathPatternComponent::forComputedGettableProperty(
2850
45
                             id, getter,
2851
45
                             indexesCopy, equals, hash,
2852
45
                             externalDecl, externalSubs, componentTy);
2853
45
    }
2854
168
    return false;
2855
168
  } else if (componentKind.str() == "optional_wrap"
2856
120
               || componentKind.str() == "optional_chain"
2857
120
               || componentKind.str() == "optional_force") {
2858
33
    CanType ty;
2859
33
    if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")
2860
33
        || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$")
2861
33
        || parseASTType(ty, patternSig, patternParams))
2862
0
      return true;
2863
33
    KeyPathPatternComponent::Kind kind;
2864
    
2865
33
    if (componentKind.str() == "optional_wrap") {
2866
12
      kind = KeyPathPatternComponent::Kind::OptionalWrap;
2867
21
    } else if (componentKind.str() == "optional_chain") {
2868
12
      kind = KeyPathPatternComponent::Kind::OptionalChain;
2869
12
    } else if (componentKind.str() == "optional_force") {
2870
9
      kind = KeyPathPatternComponent::Kind::OptionalForce;
2871
9
    } else {
2872
0
      llvm_unreachable("unpossible");
2873
0
    }
2874
    
2875
33
    component = KeyPathPatternComponent::forOptional(kind, ty);
2876
33
    return false;
2877
87
  } else if (componentKind.str() == "tuple_element") {
2878
87
    unsigned tupleIndex;
2879
87
    CanType ty;
2880
2881
87
    if (P.parseToken(tok::pound, diag::expected_sil_constant)
2882
87
        || parseInteger(tupleIndex, diag::expected_sil_tuple_index)
2883
87
        || P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":")
2884
87
        || P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$")
2885
87
        || parseASTType(ty, patternSig, patternParams))
2886
0
      return true;
2887
      
2888
87
    component = KeyPathPatternComponent::forTupleElement(tupleIndex, ty);
2889
87
    return false;
2890
87
  } else {
2891
0
    P.diagnose(componentLoc, diag::sil_keypath_unknown_component_kind,
2892
0
               componentKind);
2893
0
    return true;
2894
0
  }
2895
531
}
2896
2897
bool SILParser::parseSpecificSILInstruction(SILBuilder &B,
2898
                                            SILInstructionKind Opcode,
2899
                                            SourceLoc OpcodeLoc,
2900
                                            StringRef OpcodeName,
2901
557k
                                            SILInstruction *&ResultVal) {
2902
557k
  SmallVector<SILValue, 4> OpList;
2903
557k
  SILValue Val;
2904
557k
  SILType Ty;
2905
557k
  SILLocation InstLoc = RegularLocation(OpcodeLoc, /*implicit*/ false);
2906
557k
  this->parsedComma = false;
2907
2908
557k
  auto parseFormalTypeAndValue = [&](CanType &formalType,
2909
557k
                                     SILValue &value) -> bool {
2910
1.80k
    return (parseASTType(formalType) || parseVerbatim("in")
2911
1.80k
            || parseTypedValueRef(value, B));
2912
1.80k
  };
2913
2914
557k
  OpenedExistentialAccess AccessKind;
2915
557k
  auto parseOpenExistAddrKind = [&]() -> bool {
2916
519
    Identifier accessKindToken;
2917
519
    SourceLoc accessKindLoc;
2918
519
    if (parseSILIdentifier(accessKindToken, accessKindLoc,
2919
519
                           diag::expected_tok_in_sil_instr,
2920
519
                           "opened existential access kind")) {
2921
0
      return true;
2922
0
    }
2923
519
    auto kind =
2924
519
        llvm::StringSwitch<llvm::Optional<OpenedExistentialAccess>>(
2925
519
            accessKindToken.str())
2926
519
            .Case("mutable_access", OpenedExistentialAccess::Mutable)
2927
519
            .Case("immutable_access", OpenedExistentialAccess::Immutable)
2928
519
            .Default(llvm::None);
2929
2930
519
    if (kind) {
2931
519
      AccessKind = kind.value();
2932
519
      return false;
2933
519
    }
2934
0
    P.diagnose(accessKindLoc, diag::expected_tok_in_sil_instr,
2935
0
               "opened existential access kind");
2936
0
    return true;
2937
519
  };
2938
2939
557k
  CanType SourceType, TargetType;
2940
557k
  SILValue SourceAddr, DestAddr;
2941
557k
  auto parseSourceAndDestAddress = [&] {
2942
903
    return parseFormalTypeAndValue(SourceType, SourceAddr) ||
2943
903
           parseVerbatim("to") || parseFormalTypeAndValue(TargetType, DestAddr);
2944
903
  };
2945
2946
557k
  Identifier SuccessBBName, FailureBBName;
2947
557k
  SourceLoc SuccessBBLoc, FailureBBLoc;
2948
557k
  auto parseConditionalBranchDestinations = [&] {
2949
1.02k
    return P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")
2950
1.02k
           || parseSILIdentifier(SuccessBBName, SuccessBBLoc,
2951
1.02k
                                 diag::expected_sil_block_name)
2952
1.02k
           || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")
2953
1.02k
           || parseSILIdentifier(FailureBBName, FailureBBLoc,
2954
1.02k
                                 diag::expected_sil_block_name);
2955
1.02k
  };
2956
2957
  // Validate the opcode name, and do opcode-specific parsing logic based on the
2958
  // opcode we find.
2959
2960
557k
  switch (Opcode) {
2961
2.14k
  case SILInstructionKind::AllocBoxInst: {
2962
2.14k
    bool hasDynamicLifetime = false;
2963
2.14k
    bool hasReflection = false;
2964
2.14k
    bool usesMoveableValueDebugInfo = false;
2965
2.14k
    bool hasPointerEscape = false;
2966
2.14k
    StringRef attrName;
2967
2.14k
    SourceLoc attrLoc;
2968
2.18k
    while (parseSILOptional(attrName, attrLoc, *this)) {
2969
42
      if (attrName.equals("dynamic_lifetime")) {
2970
15
        hasDynamicLifetime = true;
2971
27
      } else if (attrName.equals("reflection")) {
2972
6
        hasReflection = true;
2973
21
      } else if (attrName.equals("moveable_value_debuginfo")) {
2974
12
        usesMoveableValueDebugInfo = true;
2975
12
      } else if (attrName.equals("pointer_escape")) {
2976
9
        hasPointerEscape = true;
2977
9
      } else {
2978
0
        P.diagnose(attrLoc, diag::sil_invalid_attribute_for_expected, attrName,
2979
0
                   "dynamic_lifetime, reflection, pointer_escape or "
2980
0
                   "usesMoveableValueDebugInfo");
2981
0
      }
2982
42
    }
2983
2984
2.14k
    SILType Ty;
2985
2.14k
    if (parseSILType(Ty))
2986
0
      return true;
2987
2.14k
    SILDebugVariable VarInfo;
2988
2.14k
    if (parseSILDebugVar(VarInfo))
2989
0
      return true;
2990
2.14k
    if (parseSILDebugLocation(InstLoc, B))
2991
0
      return true;
2992
2993
2.14k
    if (Ty.isMoveOnly())
2994
0
      usesMoveableValueDebugInfo = true;
2995
2996
2.14k
    ResultVal = B.createAllocBox(InstLoc, Ty.castTo<SILBoxType>(), VarInfo,
2997
2.14k
                                 hasDynamicLifetime, hasReflection,
2998
2.14k
                                 usesMoveableValueDebugInfo,
2999
2.14k
                                 /*skipVarDeclAssert*/ false, hasPointerEscape);
3000
2.14k
    break;
3001
2.14k
  }
3002
31.3k
  case SILInstructionKind::ApplyInst:
3003
31.8k
  case SILInstructionKind::BeginApplyInst:
3004
34.8k
  case SILInstructionKind::PartialApplyInst:
3005
35.9k
  case SILInstructionKind::TryApplyInst:
3006
35.9k
    if (parseCallInstruction(InstLoc, Opcode, B, ResultVal))
3007
0
      return true;
3008
35.9k
    break;
3009
35.9k
  case SILInstructionKind::AbortApplyInst:
3010
600
  case SILInstructionKind::EndApplyInst: {
3011
600
    UnresolvedValueName argName;
3012
600
    if (parseValueName(argName))
3013
0
      return true;
3014
3015
600
    if (parseSILDebugLocation(InstLoc, B))
3016
0
      return true;
3017
3018
600
    SILType expectedTy = SILType::getSILTokenType(P.Context);
3019
600
    SILValue op = getLocalValue(argName, expectedTy, InstLoc, B);
3020
3021
600
    if (Opcode == SILInstructionKind::AbortApplyInst) {
3022
156
      ResultVal = B.createAbortApply(InstLoc, op);
3023
444
    } else {
3024
444
      ResultVal = B.createEndApply(InstLoc, op);
3025
444
    }
3026
600
    break;
3027
600
  }
3028
20.2k
  case SILInstructionKind::IntegerLiteralInst: {
3029
20.2k
    SILType Ty;
3030
20.2k
    if (parseSILType(Ty) ||
3031
20.2k
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3032
0
      return true;
3033
3034
20.2k
    bool Negative = false;
3035
20.2k
    if (P.Tok.isAnyOperator() && P.Tok.getText() == "-") {
3036
3.38k
      Negative = true;
3037
3.38k
      P.consumeToken();
3038
3.38k
    }
3039
20.2k
    if (P.Tok.getKind() != tok::integer_literal) {
3040
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer");
3041
0
      return true;
3042
0
    }
3043
3044
20.2k
    auto intTy = Ty.getAs<AnyBuiltinIntegerType>();
3045
20.2k
    if (!intTy) {
3046
0
      P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type);
3047
0
      return true;
3048
0
    }
3049
3050
20.2k
    StringRef text = prepareIntegerLiteralForParsing(P.Tok.getText());
3051
3052
20.2k
    bool error;
3053
20.2k
    APInt value = intTy->getWidth().parse(text, 0, Negative, &error);
3054
20.2k
    if (error) {
3055
0
      P.diagnose(P.Tok, diag::sil_integer_literal_not_well_formed, intTy);
3056
0
      return true;
3057
0
    }
3058
3059
20.2k
    P.consumeToken(tok::integer_literal);
3060
20.2k
    if (parseSILDebugLocation(InstLoc, B))
3061
0
      return true;
3062
20.2k
    ResultVal = B.createIntegerLiteral(InstLoc, Ty, value);
3063
20.2k
    break;
3064
20.2k
  }
3065
261
  case SILInstructionKind::FloatLiteralInst: {
3066
261
    SILType Ty;
3067
261
    if (parseSILType(Ty) ||
3068
261
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3069
0
      return true;
3070
3071
    // The value is expressed as bits.
3072
261
    if (P.Tok.getKind() != tok::integer_literal) {
3073
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer");
3074
0
      return true;
3075
0
    }
3076
3077
261
    auto floatTy = Ty.getAs<BuiltinFloatType>();
3078
261
    if (!floatTy) {
3079
0
      P.diagnose(P.Tok, diag::sil_float_literal_not_float_type);
3080
0
      return true;
3081
0
    }
3082
3083
261
    StringRef text = prepareIntegerLiteralForParsing(P.Tok.getText());
3084
3085
261
    APInt bits(floatTy->getBitWidth(), 0);
3086
261
    bool error = text.getAsInteger(0, bits);
3087
261
    assert(!error && "float_literal token did not parse as APInt?!");
3088
0
    (void)error;
3089
3090
261
    if (bits.getBitWidth() != floatTy->getBitWidth())
3091
9
      bits = bits.zextOrTrunc(floatTy->getBitWidth());
3092
3093
261
    APFloat value(floatTy->getAPFloatSemantics(), bits);
3094
261
    if (parseSILDebugLocation(InstLoc, B))
3095
0
      return true;
3096
261
    ResultVal = B.createFloatLiteral(InstLoc, Ty, value);
3097
261
    P.consumeToken(tok::integer_literal);
3098
261
    break;
3099
261
  }
3100
1.81k
  case SILInstructionKind::StringLiteralInst: {
3101
1.81k
    if (P.Tok.getKind() != tok::identifier) {
3102
0
      P.diagnose(P.Tok, diag::sil_string_no_encoding);
3103
0
      return true;
3104
0
    }
3105
3106
1.81k
    StringLiteralInst::Encoding encoding;
3107
1.81k
    if (P.Tok.getText() == "utf8") {
3108
1.79k
      encoding = StringLiteralInst::Encoding::UTF8;
3109
1.79k
    } else if (P.Tok.getText() == "objc_selector") {
3110
9
      encoding = StringLiteralInst::Encoding::ObjCSelector;
3111
9
    } else if (P.Tok.getText() == "bytes") {
3112
9
      encoding = StringLiteralInst::Encoding::Bytes;
3113
9
    } else {
3114
0
      P.diagnose(P.Tok, diag::sil_string_invalid_encoding, P.Tok.getText());
3115
0
      return true;
3116
0
    }
3117
1.81k
    P.consumeToken(tok::identifier);
3118
3119
1.81k
    if (P.Tok.getKind() != tok::string_literal) {
3120
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string");
3121
0
      return true;
3122
0
    }
3123
3124
    // Parse the string.
3125
1.81k
    SmallVector<Lexer::StringSegment, 1> segments;
3126
1.81k
    P.L->getStringLiteralSegments(P.Tok, segments);
3127
1.81k
    assert(segments.size() == 1);
3128
3129
0
    P.consumeToken(tok::string_literal);
3130
1.81k
    if (parseSILDebugLocation(InstLoc, B))
3131
0
      return true;
3132
3133
1.81k
    SmallVector<char, 128> stringBuffer;
3134
3135
1.81k
    if (encoding == StringLiteralInst::Encoding::Bytes) {
3136
      // Decode hex bytes.
3137
9
      CharSourceRange rawStringRange(segments.front().Loc,
3138
9
                                     segments.front().Length);
3139
9
      StringRef rawString = P.SourceMgr.extractText(rawStringRange);
3140
9
      if (rawString.size() & 1) {
3141
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr,
3142
0
                   "even number of hex bytes");
3143
0
        return true;
3144
0
      }
3145
27
      while (!rawString.empty()) {
3146
18
        unsigned byte1 = llvm::hexDigitValue(rawString[0]);
3147
18
        unsigned byte2 = llvm::hexDigitValue(rawString[1]);
3148
18
        if (byte1 == -1U || byte2 == -1U) {
3149
0
          P.diagnose(P.Tok, diag::expected_tok_in_sil_instr,
3150
0
                     "hex bytes should contain 0-9, a-f, A-F only");
3151
0
          return true;
3152
0
        }
3153
18
        stringBuffer.push_back((unsigned char)(byte1 << 4) | byte2);
3154
18
        rawString = rawString.drop_front(2);
3155
18
      }
3156
3157
9
      ResultVal = B.createStringLiteral(InstLoc, stringBuffer, encoding);
3158
9
      break;
3159
9
    }
3160
3161
1.80k
    StringRef string =
3162
1.80k
        P.L->getEncodedStringSegment(segments.front(), stringBuffer);
3163
1.80k
    ResultVal = B.createStringLiteral(InstLoc, string, encoding);
3164
1.80k
    break;
3165
1.81k
  }
3166
3167
1.69k
  case SILInstructionKind::CondFailInst: {
3168
3169
1.69k
    if (parseTypedValueRef(Val, B))
3170
0
      return true;
3171
3172
1.69k
    SmallVector<char, 128> stringBuffer;
3173
1.69k
    StringRef message;
3174
1.69k
    if (P.consumeIf(tok::comma)) {
3175
      // Parse the string.
3176
234
      if (P.Tok.getKind() != tok::string_literal) {
3177
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "string");
3178
0
        return true;
3179
0
      }
3180
234
      SmallVector<Lexer::StringSegment, 1> segments;
3181
234
      P.L->getStringLiteralSegments(P.Tok, segments);
3182
234
      assert(segments.size() == 1);
3183
3184
0
      P.consumeToken(tok::string_literal);
3185
234
      message = P.L->getEncodedStringSegment(segments.front(), stringBuffer);
3186
234
    }
3187
1.69k
    if (parseSILDebugLocation(InstLoc, B))
3188
0
      return true;
3189
3190
1.69k
    ResultVal = B.createCondFail(InstLoc, Val, message);
3191
1.69k
    break;
3192
1.69k
  }
3193
3194
549
  case SILInstructionKind::IncrementProfilerCounterInst: {
3195
    // First argument is the counter index.
3196
549
    unsigned CounterIdx;
3197
549
    if (parseInteger(CounterIdx, diag::expected_sil_profiler_counter_idx))
3198
0
      return true;
3199
3200
549
    if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3201
0
      return true;
3202
3203
    // Parse the PGO function name.
3204
549
    if (P.Tok.getKind() != tok::string_literal) {
3205
0
      P.diagnose(P.Tok, diag::expected_sil_profiler_counter_pgo_func_name);
3206
0
      return true;
3207
0
    }
3208
    // Drop the double quotes.
3209
549
    auto FuncName = P.Tok.getText().drop_front().drop_back();
3210
549
    P.consumeToken(tok::string_literal);
3211
3212
549
    if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3213
0
      return true;
3214
3215
    // Parse the number of counters.
3216
549
    if (parseVerbatim("num_counters"))
3217
0
      return true;
3218
3219
549
    unsigned NumCounters;
3220
549
    if (parseInteger(NumCounters, diag::expected_sil_profiler_counter_total))
3221
0
      return true;
3222
3223
549
    if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3224
0
      return true;
3225
3226
    // Parse the PGO function hash.
3227
549
    if (parseVerbatim("hash"))
3228
0
      return true;
3229
3230
549
    uint64_t Hash;
3231
549
    if (parseInteger(Hash, diag::expected_sil_profiler_counter_hash))
3232
0
      return true;
3233
3234
549
    if (parseSILDebugLocation(InstLoc, B))
3235
0
      return true;
3236
3237
549
    ResultVal = B.createIncrementProfilerCounter(InstLoc, CounterIdx, FuncName,
3238
549
                                                 NumCounters, Hash);
3239
549
    break;
3240
549
  }
3241
3242
2.71k
  case SILInstructionKind::ProjectBoxInst: {
3243
2.71k
    if (parseTypedValueRef(Val, B) ||
3244
2.71k
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
3245
0
      return true;
3246
3247
2.71k
    if (!P.Tok.is(tok::integer_literal)) {
3248
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "integer");
3249
0
      return true;
3250
0
    }
3251
3252
2.71k
    unsigned Index;
3253
2.71k
    bool error = parseIntegerLiteral(P.Tok.getText(), 0, Index);
3254
2.71k
    assert(!error && "project_box index did not parse as integer?!");
3255
0
    (void)error;
3256
3257
2.71k
    P.consumeToken(tok::integer_literal);
3258
2.71k
    if (parseSILDebugLocation(InstLoc, B))
3259
0
      return true;
3260
3261
2.71k
    ResultVal = B.createProjectBox(InstLoc, Val, Index);
3262
2.71k
    break;
3263
2.71k
  }
3264
3265
246
  case SILInstructionKind::ProjectExistentialBoxInst: {
3266
246
    SILType Ty;
3267
246
    if (parseSILType(Ty) || parseVerbatim("in") || parseTypedValueRef(Val, B) ||
3268
246
        parseSILDebugLocation(InstLoc, B))
3269
0
      return true;
3270
246
    ResultVal = B.createProjectExistentialBox(InstLoc, Ty, Val);
3271
246
    break;
3272
246
  }
3273
3274
28.7k
  case SILInstructionKind::FunctionRefInst: {
3275
28.7k
    SILFunction *Fn;
3276
28.7k
    if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B))
3277
0
      return true;
3278
28.7k
    ResultVal = B.createFunctionRef(InstLoc, Fn);
3279
28.7k
    break;
3280
28.7k
  }
3281
18
  case SILInstructionKind::DynamicFunctionRefInst: {
3282
18
    SILFunction *Fn;
3283
18
    if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B))
3284
0
      return true;
3285
    // Set a forward reference's dynamic property for the first time.
3286
18
    if (!Fn->isDynamicallyReplaceable()) {
3287
3
      if (!Fn->empty()) {
3288
0
        P.diagnose(P.Tok, diag::expected_dynamic_func_attr);
3289
0
        return true;
3290
0
      }
3291
3
      Fn->setIsDynamic();
3292
3
    }
3293
18
    ResultVal = B.createDynamicFunctionRef(InstLoc, Fn);
3294
18
    break;
3295
18
  }
3296
9
  case SILInstructionKind::PreviousDynamicFunctionRefInst: {
3297
9
    SILFunction *Fn;
3298
9
    if (parseSILFunctionRef(InstLoc, Fn) || parseSILDebugLocation(InstLoc, B))
3299
0
      return true;
3300
9
    ResultVal = B.createPreviousDynamicFunctionRef(InstLoc, Fn);
3301
9
    break;
3302
9
  }
3303
17.3k
  case SILInstructionKind::BuiltinInst: {
3304
17.3k
    if (P.Tok.getKind() != tok::string_literal) {
3305
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "builtin name");
3306
0
      return true;
3307
0
    }
3308
17.3k
    StringRef Str = P.Tok.getText();
3309
17.3k
    Identifier Id = P.Context.getIdentifier(Str.substr(1, Str.size() - 2));
3310
17.3k
    P.consumeToken(tok::string_literal);
3311
3312
    // Find the builtin in the Builtin module
3313
17.3k
    SmallVector<ValueDecl *, 2> foundBuiltins;
3314
17.3k
    P.Context.TheBuiltinModule->lookupMember(
3315
17.3k
        foundBuiltins, P.Context.TheBuiltinModule, Id, Identifier());
3316
17.3k
    if (foundBuiltins.empty()) {
3317
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "builtin name");
3318
0
      return true;
3319
0
    }
3320
17.3k
    assert(foundBuiltins.size() == 1 && "ambiguous builtin name?!");
3321
3322
0
    auto *builtinFunc = cast<FuncDecl>(foundBuiltins[0]);
3323
17.3k
    GenericSignature genericSig = builtinFunc->getGenericSignature();
3324
3325
17.3k
    SmallVector<ParsedSubstitution, 4> parsedSubs;
3326
17.3k
    SubstitutionMap subMap;
3327
17.3k
    if (parseSubstitutions(parsedSubs))
3328
0
      return true;
3329
3330
17.3k
    if (!parsedSubs.empty()) {
3331
819
      if (!genericSig) {
3332
0
        P.diagnose(P.Tok, diag::sil_substitutions_on_non_polymorphic_type);
3333
0
        return true;
3334
0
      }
3335
819
      subMap = getApplySubstitutionsFromParsed(*this, genericSig, parsedSubs);
3336
819
      if (!subMap)
3337
0
        return true;
3338
819
    }
3339
3340
17.3k
    if (P.Tok.getKind() != tok::l_paren) {
3341
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "(");
3342
0
      return true;
3343
0
    }
3344
17.3k
    P.consumeToken(tok::l_paren);
3345
3346
17.3k
    SmallVector<SILValue, 4> Args;
3347
28.6k
    while (true) {
3348
28.6k
      if (P.consumeIf(tok::r_paren))
3349
5.50k
        break;
3350
3351
23.1k
      SILValue Val;
3352
23.1k
      if (parseTypedValueRef(Val, B))
3353
0
        return true;
3354
23.1k
      Args.push_back(Val);
3355
23.1k
      if (P.consumeIf(tok::comma))
3356
11.3k
        continue;
3357
11.8k
      if (P.consumeIf(tok::r_paren))
3358
11.8k
        break;
3359
3
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ")' or ',");
3360
3
      return true;
3361
11.8k
    }
3362
3363
17.3k
    if (P.Tok.getKind() != tok::colon) {
3364
0
      P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ":");
3365
0
      return true;
3366
0
    }
3367
17.3k
    P.consumeToken(tok::colon);
3368
3369
17.3k
    SILType ResultTy;
3370
17.3k
    if (parseSILType(ResultTy))
3371
0
      return true;
3372
3373
17.3k
    if (parseSILDebugLocation(InstLoc, B))
3374
0
      return true;
3375
17.3k
    ResultVal = B.createBuiltin(InstLoc, Id, ResultTy, subMap, Args);
3376
17.3k
    break;
3377
17.3k
  }
3378
519
  case SILInstructionKind::OpenExistentialAddrInst:
3379
519
    if (parseOpenExistAddrKind() || parseTypedValueRef(Val, B) ||
3380
519
        parseVerbatim("to") || parseSILType(Ty) ||
3381
519
        parseSILDebugLocation(InstLoc, B))
3382
0
      return true;
3383
3384
519
    ResultVal = B.createOpenExistentialAddr(InstLoc, Val, Ty, AccessKind);
3385
519
    break;
3386
3387
30
  case SILInstructionKind::OpenExistentialBoxInst:
3388
30
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) ||
3389
30
        parseSILDebugLocation(InstLoc, B))
3390
0
      return true;
3391
3392
30
    ResultVal = B.createOpenExistentialBox(InstLoc, Val, Ty);
3393
30
    break;
3394
3395
18
  case SILInstructionKind::OpenExistentialBoxValueInst: {
3396
18
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty))
3397
0
      return true;
3398
3399
18
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
3400
18
    if (parseForwardingOwnershipKind(forwardingOwnership)
3401
18
        || parseSILDebugLocation(InstLoc, B))
3402
0
      return true;
3403
18
    ResultVal =
3404
18
        B.createOpenExistentialBoxValue(InstLoc, Val, Ty, forwardingOwnership);
3405
18
    break;
3406
18
  }
3407
3408
75
  case SILInstructionKind::OpenExistentialMetatypeInst:
3409
75
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty) ||
3410
75
        parseSILDebugLocation(InstLoc, B))
3411
0
      return true;
3412
75
    ResultVal = B.createOpenExistentialMetatype(InstLoc, Val, Ty);
3413
75
    break;
3414
3415
363
  case SILInstructionKind::OpenExistentialRefInst: {
3416
363
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty))
3417
0
      return true;
3418
3419
363
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
3420
363
    if (parseForwardingOwnershipKind(forwardingOwnership)
3421
363
        || parseSILDebugLocation(InstLoc, B))
3422
0
      return true;
3423
3424
363
    ResultVal =
3425
363
        B.createOpenExistentialRef(InstLoc, Val, Ty, forwardingOwnership);
3426
363
    break;
3427
363
  }
3428
3429
18
  case SILInstructionKind::OpenExistentialValueInst: {
3430
18
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") || parseSILType(Ty))
3431
0
      return true;
3432
3433
18
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
3434
18
    if (parseForwardingOwnershipKind(forwardingOwnership)
3435
18
        || parseSILDebugLocation(InstLoc, B))
3436
0
      return true;
3437
3438
18
    ResultVal =
3439
18
        B.createOpenExistentialValue(InstLoc, Val, Ty, forwardingOwnership);
3440
18
    break;
3441
18
  }
3442
15
  case SILInstructionKind::PackLengthInst: {
3443
15
    CanPackType packType;
3444
15
    if (P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
3445
15
        parseASTPackType(packType))
3446
0
      return true;
3447
15
    ResultVal = B.createPackLength(InstLoc, packType);
3448
15
    break;
3449
15
  }
3450
123
  case SILInstructionKind::DynamicPackIndexInst: {
3451
123
    CanPackType packType;
3452
123
    if (parseValueRef(Val, SILType::getBuiltinWordType(P.Context), InstLoc, B) ||
3453
123
        parseVerbatim("of") ||
3454
123
        P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
3455
123
        parseASTPackType(packType))
3456
0
      return true;
3457
123
    ResultVal =
3458
123
        B.createDynamicPackIndex(InstLoc, Val, packType);
3459
123
    break;
3460
123
  }
3461
24
  case SILInstructionKind::PackPackIndexInst: {
3462
24
    unsigned componentIndex = 0;
3463
24
    CanPackType packType;
3464
24
    if (parseInteger(componentIndex, diag::expected_sil_constant) ||
3465
24
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
3466
24
        parseValueRef(Val, SILType::getPackIndexType(P.Context), InstLoc, B) ||
3467
24
        parseVerbatim("of") ||
3468
24
        P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
3469
24
        parseASTPackType(packType))
3470
0
      return true;
3471
24
    ResultVal =
3472
24
        B.createPackPackIndex(InstLoc, componentIndex, Val, packType);
3473
24
    break;
3474
24
  }
3475
27
  case SILInstructionKind::ScalarPackIndexInst: {
3476
27
    unsigned componentIndex = 0;
3477
27
    CanPackType packType;
3478
27
    if (parseInteger(componentIndex, diag::expected_sil_constant) ||
3479
27
        parseVerbatim("of") ||
3480
27
        P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
3481
27
        parseASTPackType(packType))
3482
0
      return true;
3483
27
    ResultVal =
3484
27
        B.createScalarPackIndex(InstLoc, componentIndex, packType);
3485
27
    break;
3486
27
  }
3487
114
  case SILInstructionKind::OpenPackElementInst: {
3488
114
    if (parseValueRef(Val, SILType::getPackIndexType(P.Context), InstLoc, B) ||
3489
114
        parseVerbatim("of"))
3490
0
      return true;
3491
3492
    // Parse the generic parameters for the environment being opened.
3493
    // This does not include the opened generic parameters.
3494
114
    GenericParamList *openedGenerics; {
3495
114
      if (!P.startsWithLess(P.Tok)) {
3496
0
        P.diagnose(P.Tok, diag::expected_generic_signature);
3497
0
        return true;
3498
0
      }
3499
114
      openedGenerics = P.maybeParseGenericParams().getPtrOrNull();
3500
114
      if (!openedGenerics)
3501
0
        return true;
3502
114
    }
3503
3504
    // Resolve a generic signature from those parameters.
3505
114
    auto openedGenericsSig = handleSILGenericParams(openedGenerics, &P.SF);
3506
114
    if (!openedGenericsSig) return true;
3507
3508
    // Parse the substitutions for the environment being opened.
3509
114
    SubstitutionMap openedSubMap; {
3510
114
      if (parseVerbatim("at"))
3511
0
        return true;
3512
3513
      // The substitutions are not contextual within the signature
3514
      // we just parsed.
3515
114
      SmallVector<ParsedSubstitution> parsedOpenedSubs;
3516
114
      if (parseSubstitutions(parsedOpenedSubs))
3517
0
        return true;
3518
3519
      // We do need those substitutions to resolve a SubstitutionMap,
3520
      // though.
3521
114
      openedSubMap =
3522
114
        getApplySubstitutionsFromParsed(*this, openedGenericsSig,
3523
114
                                        parsedOpenedSubs);
3524
114
      if (!openedSubMap)
3525
0
        return true;
3526
114
    }
3527
3528
    // Parse the shape class that should be opened.  This is a contextual
3529
    // type within the signature we just parsed.
3530
114
    CanType shapeClass;
3531
114
    SourceLoc shapeClassLoc;
3532
114
    if (!P.consumeIf(tok::comma) ||
3533
114
        parseVerbatim("shape") ||
3534
114
        P.parseToken(tok::sil_dollar,
3535
114
                     diag::expected_tok_in_sil_instr, "$") ||
3536
114
        parseASTType(shapeClass, shapeClassLoc, openedGenericsSig,
3537
114
                     openedGenerics, /*wantContextualType*/ true))
3538
0
      return true;
3539
3540
    // Map it out of context.  It should be a type pack parameter.
3541
114
    shapeClass = shapeClass->mapTypeOutOfContext()->getCanonicalType();
3542
114
    auto shapeParam = dyn_cast<GenericTypeParamType>(shapeClass);
3543
114
    if (!shapeParam || !shapeParam->isParameterPack()) {
3544
0
      P.diagnose(shapeClassLoc, diag::opened_shape_class_not_pack_param);
3545
0
      return true;
3546
0
    }
3547
3548
    // Parse the UUID for the opening.
3549
114
    UUID uuid;
3550
114
    if (!P.consumeIf(tok::comma) ||
3551
114
        parseVerbatim("uuid") ||
3552
114
        P.parseUUIDString(uuid, diag::sil_expected_uuid))
3553
0
      return true;
3554
3555
    // Build the opened-element signature, which adds the parameters for
3556
    // the opened elements to the signature we parsed above.
3557
114
    auto openedElementSig =
3558
114
      P.Context.getOpenedElementSignature(
3559
114
        openedGenericsSig.getCanonicalSignature(), shapeParam);
3560
3561
114
    auto openedEnv = GenericEnvironment::forOpenedElement(openedElementSig,
3562
114
                         uuid, shapeParam, openedSubMap);
3563
3564
114
    auto openInst = B.createOpenPackElement(InstLoc, Val, openedEnv);
3565
114
    ResultVal = openInst;
3566
3567
114
    auto &entry = OpenedPackElements[uuid];
3568
114
    if (entry.DefinitionPoint.isValid()) {
3569
0
      P.diagnose(OpcodeLoc, diag::multiple_open_pack_element);
3570
0
      P.diagnose(entry.DefinitionPoint, diag::sil_previous_instruction);
3571
114
    } else {
3572
114
      entry.DefinitionPoint = OpcodeLoc;
3573
114
      entry.Params = openedGenerics;
3574
114
      entry.Environment = openedEnv;
3575
114
    }
3576
114
    break;
3577
114
  }
3578
21
  case SILInstructionKind::PackElementGetInst: {
3579
21
    SILValue index, pack;
3580
21
    SILType elementType;
3581
21
    if (parseValueRef(index, SILType::getPackIndexType(P.Context), InstLoc, B) ||
3582
21
        parseVerbatim("of") ||
3583
21
        parseTypedValueRef(pack, B) ||
3584
21
        parseVerbatim("as") ||
3585
21
        parseSILType(elementType))
3586
0
      return true;
3587
21
    ResultVal = B.createPackElementGet(InstLoc, index, pack, elementType);
3588
21
    break;
3589
21
  }
3590
6
  case SILInstructionKind::PackElementSetInst: {
3591
6
    SILValue value, index, pack;
3592
6
    if (parseTypedValueRef(value, B) ||
3593
6
        parseVerbatim("into") ||
3594
6
        parseValueRef(index, SILType::getPackIndexType(P.Context), InstLoc, B) ||
3595
6
        parseVerbatim("of") ||
3596
6
        parseTypedValueRef(pack, B))
3597
0
      return true;
3598
6
    ResultVal = B.createPackElementSet(InstLoc, value, index, pack);
3599
6
    break;
3600
6
  }
3601
12
  case SILInstructionKind::TuplePackElementAddrInst: {
3602
12
    SILValue index, tuple;
3603
12
    SILType elementType;
3604
12
    if (parseValueRef(index, SILType::getPackIndexType(P.Context), InstLoc, B) ||
3605
12
        parseVerbatim("of") ||
3606
12
        parseTypedValueRef(tuple, B) ||
3607
12
        parseVerbatim("as") ||
3608
12
        parseSILType(elementType))
3609
0
      return true;
3610
12
    ResultVal = B.createTuplePackElementAddr(InstLoc, index, tuple, elementType);
3611
12
    break;
3612
12
  }
3613
18
  case SILInstructionKind::TuplePackExtractInst: {
3614
18
    SILValue index, tuple;
3615
18
    SILType elementType;
3616
18
    if (parseValueRef(index, SILType::getPackIndexType(P.Context), InstLoc,
3617
18
                      B) ||
3618
18
        parseVerbatim("of") || parseTypedValueRef(tuple, B) ||
3619
18
        parseVerbatim("as") || parseSILType(elementType))
3620
0
      return true;
3621
18
    ResultVal = B.createTuplePackExtract(InstLoc, index, tuple, elementType);
3622
18
    break;
3623
18
  }
3624
3625
0
#define UNARY_INSTRUCTION(ID)                                                  \
3626
18.3k
  case SILInstructionKind::ID##Inst:                                           \
3627
18.3k
    if (parseTypedValueRef(Val, B))                                            \
3628
18.3k
      return true;                                                             \
3629
18.3k
    if (parseSILDebugLocation(InstLoc, B))                                     \
3630
18.3k
      return true;                                                             \
3631
18.3k
    ResultVal = B.create##ID(InstLoc, Val);                                    \
3632
18.3k
    break;
3633
3634
0
#define REFCOUNTING_INSTRUCTION(ID)                                            \
3635
11.8k
  case SILInstructionKind::ID##Inst: {                                         \
3636
11.8k
    Atomicity atomicity = Atomicity::Atomic;                                   \
3637
11.8k
    StringRef Optional;                                                        \
3638
11.8k
    if (parseSILOptional(Optional, *this)) {                                   \
3639
96
      if (Optional == "nonatomic") {                                           \
3640
96
        atomicity = Atomicity::NonAtomic;                                      \
3641
96
      } else {                                                                 \
3642
0
        return true;                                                           \
3643
0
      }                                                                        \
3644
96
    }                                                                          \
3645
11.8k
    if (parseTypedValueRef(Val, B))                                            \
3646
11.8k
      return true;                                                             \
3647
11.8k
    if (parseSILDebugLocation(InstLoc, B))                                     \
3648
11.8k
      return true;                                                             \
3649
11.8k
    ResultVal = B.create##ID(InstLoc, Val, atomicity);                         \
3650
11.8k
  } break;
3651
3652
318
    UNARY_INSTRUCTION(ClassifyBridgeObject)
3653
192
    UNARY_INSTRUCTION(ValueToBridgeObject)
3654
1.24k
    UNARY_INSTRUCTION(FixLifetime)
3655
204
    UNARY_INSTRUCTION(EndLifetime)
3656
54
    UNARY_INSTRUCTION(CopyBlock)
3657
204
    UNARY_INSTRUCTION(IsUnique)
3658
11.7k
    UNARY_INSTRUCTION(DestroyAddr)
3659
10.6k
    UNARY_INSTRUCTION(CopyValue)
3660
0
    UNARY_INSTRUCTION(ExplicitCopyValue)
3661
9.63k
    UNARY_INSTRUCTION(EndBorrow)
3662
912
    UNARY_INSTRUCTION(DestructureStruct)
3663
1.39k
    UNARY_INSTRUCTION(DestructureTuple)
3664
30
    UNARY_INSTRUCTION(ExtractExecutor)
3665
84
    UNARY_INSTRUCTION(EndInitLetRef)
3666
54
    REFCOUNTING_INSTRUCTION(UnmanagedReleaseValue)
3667
54
    REFCOUNTING_INSTRUCTION(UnmanagedRetainValue)
3668
45
    REFCOUNTING_INSTRUCTION(UnmanagedAutoreleaseValue)
3669
10.7k
    REFCOUNTING_INSTRUCTION(StrongRetain)
3670
14.8k
    REFCOUNTING_INSTRUCTION(StrongRelease)
3671
45
    REFCOUNTING_INSTRUCTION(AutoreleaseValue)
3672
4.74k
    REFCOUNTING_INSTRUCTION(ReleaseValue)
3673
4.87k
    REFCOUNTING_INSTRUCTION(RetainValue)
3674
0
    REFCOUNTING_INSTRUCTION(ReleaseValueAddr)
3675
0
    REFCOUNTING_INSTRUCTION(RetainValueAddr)
3676
30
    UNARY_INSTRUCTION(UnownedCopyValue)
3677
30
    UNARY_INSTRUCTION(WeakCopyValue)
3678
0
#define UNCHECKED_REF_STORAGE(Name, ...)                                       \
3679
27
  UNARY_INSTRUCTION(StrongCopy##Name##Value)
3680
0
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                          \
3681
15
  UNARY_INSTRUCTION(StrongCopy##Name##Value)
3682
0
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \
3683
6
  REFCOUNTING_INSTRUCTION(StrongRetain##Name)                                  \
3684
21
  REFCOUNTING_INSTRUCTION(Name##Retain)                                        \
3685
33
  REFCOUNTING_INSTRUCTION(Name##Release)                                       \
3686
33
  UNARY_INSTRUCTION(StrongCopy##Name##Value)
3687
15
#include "swift/AST/ReferenceStorage.def"
3688
0
#undef UNARY_INSTRUCTION
3689
0
#undef REFCOUNTING_INSTRUCTION
3690
3691
216
  case SILInstructionKind::HopToExecutorInst: {
3692
216
    bool mandatory = false;
3693
216
    if (parseSILOptional(mandatory, *this, "mandatory")
3694
216
        || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
3695
0
      return true;
3696
216
    ResultVal = B.createHopToExecutor(InstLoc, Val, mandatory);
3697
216
    break;
3698
216
  }
3699
12.0k
  case SILInstructionKind::DestroyValueInst: {
3700
12.0k
    bool poisonRefs = false;
3701
12.0k
    if (parseSILOptional(poisonRefs, *this, "poison")
3702
12.0k
        || parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
3703
0
      return true;
3704
12.0k
    ResultVal = B.createDestroyValue(InstLoc, Val, poisonRefs);
3705
12.0k
    break;
3706
12.0k
  }
3707
132
  case SILInstructionKind::BeginCOWMutationInst: {
3708
132
    bool native = false;
3709
132
    if (parseSILOptional(native, *this, "native") ||
3710
132
        parseTypedValueRef(Val, B) ||
3711
132
        parseSILDebugLocation(InstLoc, B))
3712
0
      return true;
3713
132
    ResultVal = B.createBeginCOWMutation(InstLoc, Val, native);
3714
132
    break;
3715
132
  }
3716
210
  case SILInstructionKind::EndCOWMutationInst: {
3717
210
    bool keepUnique = false;
3718
210
    if (parseSILOptional(keepUnique, *this, "keep_unique") ||
3719
210
        parseTypedValueRef(Val, B) ||
3720
210
        parseSILDebugLocation(InstLoc, B))
3721
0
      return true;
3722
210
    ResultVal = B.createEndCOWMutation(InstLoc, Val, keepUnique);
3723
210
    break;
3724
210
  }
3725
39
  case SILInstructionKind::IsEscapingClosureInst: {
3726
39
    bool IsObjcVerificationType = false;
3727
39
    if (parseSILOptional(IsObjcVerificationType, *this, "objc"))
3728
0
      return true;
3729
39
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
3730
0
      return true;
3731
39
    ResultVal = B.createIsEscapingClosure(
3732
39
        InstLoc, Val,
3733
39
        IsObjcVerificationType ? IsEscapingClosureInst::ObjCEscaping
3734
39
                              : IsEscapingClosureInst::WithoutActuallyEscaping);
3735
39
    break;
3736
39
  }
3737
3738
6.29k
  case SILInstructionKind::DebugValueInst: {
3739
6.29k
    bool poisonRefs = false;
3740
6.29k
    bool hasTrace = false;
3741
6.29k
    bool usesMoveableValueDebugInfo = false;
3742
6.29k
    SILDebugVariable VarInfo;
3743
3744
    // Allow for poison and moved to be in either order.
3745
6.29k
    StringRef attributeName;
3746
6.29k
    SourceLoc attributeLoc;
3747
6.61k
    while (parseSILOptional(attributeName, attributeLoc, *this)) {
3748
318
      if (attributeName == "poison")
3749
33
        poisonRefs = true;
3750
285
      else if (attributeName == "trace")
3751
243
        hasTrace = true;
3752
42
      else if (attributeName == "moveable_value_debuginfo")
3753
42
        usesMoveableValueDebugInfo = true;
3754
0
      else {
3755
0
        P.diagnose(attributeLoc, diag::sil_invalid_attribute_for_instruction,
3756
0
                   attributeName, "debug_value");
3757
0
        return true;
3758
0
      }
3759
318
    }
3760
3761
6.29k
    if (parseTypedValueRef(Val, B) || parseSILDebugVar(VarInfo) ||
3762
6.29k
        parseSILDebugLocation(InstLoc, B))
3763
0
      return true;
3764
6.29k
    if (Val->getType().isAddress())
3765
1.28k
      assert(!poisonRefs && "debug_value w/ address value does not support poison");
3766
3767
6.29k
    if (Val->getType().isMoveOnly())
3768
213
      usesMoveableValueDebugInfo = true;
3769
3770
6.29k
    ResultVal = B.createDebugValue(InstLoc, Val, VarInfo, poisonRefs,
3771
6.29k
                                   usesMoveableValueDebugInfo, hasTrace);
3772
6.29k
    break;
3773
6.29k
  }
3774
3775
87
  case SILInstructionKind::DebugStepInst:
3776
87
    if (parseSILDebugLocation(InstLoc, B))
3777
0
      return true;
3778
87
    ResultVal = B.createDebugStep(InstLoc);
3779
87
    break;
3780
3781
711
  case SILInstructionKind::TestSpecificationInst: {
3782
    // Parse the specification string.
3783
711
    if (P.Tok.getKind() != tok::string_literal) {
3784
0
      P.diagnose(P.Tok, diag::expected_sil_specify_test_body);
3785
0
      return true;
3786
0
    }
3787
    // Drop the double quotes.
3788
711
    unsigned numQuotes = P.Tok.isMultilineString() ? 4 : 1;
3789
711
    auto ArgumentsSpecification =
3790
711
      P.Tok.getText().drop_front(numQuotes).drop_back(numQuotes).trim();
3791
711
    P.consumeToken(tok::string_literal);
3792
711
    auto *tsi = B.createTestSpecificationInst(InstLoc, ArgumentsSpecification);
3793
711
    SmallVector<StringRef, 4> components;
3794
711
    test::getTestSpecificationComponents(ArgumentsSpecification, components);
3795
2.38k
    for (auto component : components) {
3796
2.38k
      auto offset = 0;
3797
2.38k
      size_t nameStart = StringRef::npos;
3798
29.7k
      while ((nameStart = component.find_if([](char c) { return c == '%'; },
3799
2.51k
                                            offset)) != StringRef::npos) {
3800
132
        auto nameEnd = component.find_if_not(
3801
426
            [](char c) { return clang::isAsciiIdentifierContinue(c); },
3802
132
            nameStart + 1);
3803
132
        if (nameEnd == StringRef::npos)
3804
132
          nameEnd = component.size();
3805
132
        auto name = component.substr(nameStart, nameEnd);
3806
132
        component = component.drop_front(nameEnd);
3807
132
        if (nameStart + 1 == nameEnd) {
3808
0
          continue;
3809
0
        }
3810
132
        auto *&entry = LocalValues[name];
3811
132
        if (entry) {
3812
126
          tsi->setValueForName(name, entry);
3813
126
        } else {
3814
6
          TestSpecsWithRefs[name].push_back(tsi);
3815
6
        }
3816
132
      }
3817
2.38k
    }
3818
711
    ResultVal = tsi;
3819
711
    break;
3820
711
  }
3821
3822
    // unchecked_ownership_conversion <reg> : <type>, <ownership> to <ownership>
3823
123
  case SILInstructionKind::UncheckedOwnershipConversionInst: {
3824
123
    ValueOwnershipKind LHSKind = OwnershipKind::None;
3825
123
    ValueOwnershipKind RHSKind = OwnershipKind::None;
3826
123
    SourceLoc Loc;
3827
3828
123
    if (parseTypedValueRef(Val, Loc, B) ||
3829
123
        P.parseToken(tok::comma, diag::expected_sil_colon,
3830
123
                     "unchecked_ownership_conversion value ownership kind "
3831
123
                     "conversion specification") ||
3832
123
        parseSILOwnership(LHSKind) || parseVerbatim("to") ||
3833
123
        parseSILOwnership(RHSKind) || parseSILDebugLocation(InstLoc, B)) {
3834
0
      return true;
3835
0
    }
3836
3837
123
    if (Val->getOwnershipKind() != LHSKind) {
3838
0
      return true;
3839
0
    }
3840
3841
123
    ResultVal = B.createUncheckedOwnershipConversion(InstLoc, Val, RHSKind);
3842
123
    break;
3843
123
  }
3844
3845
372
  case SILInstructionKind::MoveValueInst: {
3846
372
    bool allowsDiagnostics = false;
3847
372
    bool isLexical = false;
3848
372
    bool hasPointerEscape = false;
3849
3850
372
    StringRef AttrName;
3851
372
    SourceLoc AttrLoc;
3852
678
    while (parseSILOptional(AttrName, AttrLoc, *this)) {
3853
306
      if (AttrName == "allows_diagnostics")
3854
60
        allowsDiagnostics = true;
3855
246
      else if (AttrName == "lexical")
3856
237
        isLexical = true;
3857
9
      else if (AttrName == "pointer_escape")
3858
9
        hasPointerEscape = true;
3859
0
      else {
3860
0
        P.diagnose(InstLoc.getSourceLoc(),
3861
0
                   diag::sil_invalid_attribute_for_instruction, AttrName,
3862
0
                   "move_value");
3863
0
        return true;
3864
0
      }
3865
306
    }
3866
3867
372
    if (parseTypedValueRef(Val, B))
3868
0
      return true;
3869
372
    if (parseSILDebugLocation(InstLoc, B))
3870
0
      return true;
3871
372
    auto *MVI = B.createMoveValue(InstLoc, Val, isLexical, hasPointerEscape);
3872
372
    MVI->setAllowsDiagnostics(allowsDiagnostics);
3873
372
    ResultVal = MVI;
3874
372
    break;
3875
372
  }
3876
3877
39
  case SILInstructionKind::DropDeinitInst: {
3878
39
    if (parseTypedValueRef(Val, B))
3879
0
      return true;
3880
39
    if (parseSILDebugLocation(InstLoc, B))
3881
0
      return true;
3882
39
    ResultVal = B.createDropDeinit(InstLoc, Val);
3883
39
    break;
3884
39
  }
3885
3886
543
  case SILInstructionKind::MarkUnresolvedNonCopyableValueInst: {
3887
543
    StringRef AttrName;
3888
543
    if (!parseSILOptional(AttrName, *this)) {
3889
0
      auto diag = diag::sil_markmustcheck_requires_attribute;
3890
0
      P.diagnose(InstLoc.getSourceLoc(), diag);
3891
0
      return true;
3892
0
    }
3893
3894
543
    using CheckKind = MarkUnresolvedNonCopyableValueInst::CheckKind;
3895
543
    CheckKind CKind =
3896
543
        llvm::StringSwitch<CheckKind>(AttrName)
3897
543
            .Case("consumable_and_assignable",
3898
543
                  CheckKind::ConsumableAndAssignable)
3899
543
            .Case("no_consume_or_assign", CheckKind::NoConsumeOrAssign)
3900
543
            .Case("assignable_but_not_consumable",
3901
543
                  CheckKind::AssignableButNotConsumable)
3902
543
            .Case("initable_but_not_consumable",
3903
543
                  CheckKind::InitableButNotConsumable)
3904
543
            .Default(CheckKind::Invalid);
3905
3906
543
    if (CKind == CheckKind::Invalid) {
3907
0
      auto diag = diag::sil_markmustcheck_invalid_attribute;
3908
0
      P.diagnose(InstLoc.getSourceLoc(), diag, AttrName);
3909
0
      return true;
3910
0
    }
3911
3912
543
    if (parseTypedValueRef(Val, B))
3913
0
      return true;
3914
543
    if (parseSILDebugLocation(InstLoc, B))
3915
0
      return true;
3916
3917
543
    auto *MVI = B.createMarkUnresolvedNonCopyableValueInst(InstLoc, Val, CKind);
3918
543
    ResultVal = MVI;
3919
543
    break;
3920
543
  }
3921
3922
0
  case SILInstructionKind::MarkUnresolvedReferenceBindingInst: {
3923
0
    StringRef AttrName;
3924
0
    if (!parseSILOptional(AttrName, *this)) {
3925
0
      auto diag = diag::sil_markuncheckedreferencebinding_requires_attribute;
3926
0
      P.diagnose(InstLoc.getSourceLoc(), diag);
3927
0
      return true;
3928
0
    }
3929
3930
0
    using Kind = MarkUnresolvedReferenceBindingInst::Kind;
3931
0
    Kind CKind = llvm::StringSwitch<Kind>(AttrName)
3932
0
                     .Case("inout", Kind::InOut)
3933
0
                     .Default(Kind::Invalid);
3934
3935
0
    if (CKind == Kind::Invalid) {
3936
0
      auto diag = diag::sil_markuncheckedreferencebinding_invalid_attribute;
3937
0
      P.diagnose(InstLoc.getSourceLoc(), diag, AttrName);
3938
0
      return true;
3939
0
    }
3940
3941
0
    if (parseTypedValueRef(Val, B))
3942
0
      return true;
3943
0
    if (parseSILDebugLocation(InstLoc, B))
3944
0
      return true;
3945
3946
0
    auto *MVI = B.createMarkUnresolvedReferenceBindingInst(InstLoc, Val, CKind);
3947
0
    ResultVal = MVI;
3948
0
    break;
3949
0
  }
3950
3951
123
  case SILInstructionKind::CopyableToMoveOnlyWrapperValueInst: {
3952
123
    StringRef AttrName;
3953
123
    if (!parseSILOptional(AttrName, *this)) {
3954
0
      auto diag = diag::sil_moveonlytocopyable_requires_attribute;
3955
0
      P.diagnose(InstLoc.getSourceLoc(), diag);
3956
0
      return true;
3957
0
    }
3958
3959
123
    OwnershipKind OwnershipKind =
3960
123
        llvm::StringSwitch<ValueOwnershipKind>(AttrName)
3961
123
            .Case("owned", OwnershipKind::Owned)
3962
123
            .Case("guaranteed", OwnershipKind::Guaranteed)
3963
123
            .Default(OwnershipKind::None);
3964
3965
123
    if (OwnershipKind == OwnershipKind::None) {
3966
0
      auto diag = diag::sil_moveonlytocopyable_invalid_attribute;
3967
0
      P.diagnose(InstLoc.getSourceLoc(), diag, AttrName);
3968
0
      return true;
3969
0
    }
3970
3971
123
    if (parseTypedValueRef(Val, B))
3972
0
      return true;
3973
123
    if (parseSILDebugLocation(InstLoc, B))
3974
0
      return true;
3975
3976
123
    if (!Val->getType().isObject()) {
3977
3
      P.diagnose(InstLoc.getSourceLoc(),
3978
3
                 diag::sil_operand_not_object, "operand", OpcodeName);
3979
3
      return true;
3980
3
    }
3981
3982
120
    if (Val->getType().isMoveOnlyWrapped()) {
3983
3
      P.diagnose(InstLoc.getSourceLoc(),
3984
3
                 diag::sil_operand_has_incorrect_moveonlywrapped,
3985
3
                 "operand", OpcodeName, 1);
3986
3
      return true;
3987
3
    }
3988
3989
117
    if (OwnershipKind == OwnershipKind::Owned)
3990
105
      ResultVal = B.createOwnedCopyableToMoveOnlyWrapperValue(InstLoc, Val);
3991
12
    else
3992
12
      ResultVal =
3993
12
          B.createGuaranteedCopyableToMoveOnlyWrapperValue(InstLoc, Val);
3994
117
    break;
3995
120
  }
3996
3997
156
  case SILInstructionKind::MoveOnlyWrapperToCopyableValueInst: {
3998
156
    StringRef AttrName;
3999
156
    if (!parseSILOptional(AttrName, *this)) {
4000
0
      auto diag = diag::sil_moveonlytocopyable_requires_attribute;
4001
0
      P.diagnose(InstLoc.getSourceLoc(), diag);
4002
0
      return true;
4003
0
    }
4004
4005
156
    OwnershipKind OwnershipKind =
4006
156
        llvm::StringSwitch<ValueOwnershipKind>(AttrName)
4007
156
            .Case("owned", OwnershipKind::Owned)
4008
156
            .Case("guaranteed", OwnershipKind::Guaranteed)
4009
156
            .Default(OwnershipKind::None);
4010
4011
156
    if (OwnershipKind == OwnershipKind::None) {
4012
0
      auto diag = diag::sil_moveonlytocopyable_invalid_attribute;
4013
0
      P.diagnose(InstLoc.getSourceLoc(), diag, AttrName);
4014
0
      return true;
4015
0
    }
4016
4017
156
    if (parseTypedValueRef(Val, B))
4018
0
      return true;
4019
156
    if (parseSILDebugLocation(InstLoc, B))
4020
0
      return true;
4021
4022
156
    if (!Val->getType().isObject()) {
4023
3
      P.diagnose(InstLoc.getSourceLoc(),
4024
3
                 diag::sil_operand_not_object, "operand", OpcodeName);
4025
3
      return true;
4026
3
    }
4027
4028
153
    if (!Val->getType().isMoveOnlyWrapped()) {
4029
3
      P.diagnose(InstLoc.getSourceLoc(),
4030
3
                 diag::sil_operand_has_incorrect_moveonlywrapped,
4031
3
                 "operand", OpcodeName, 0);
4032
3
      return true;
4033
3
    }
4034
4035
150
    if (OwnershipKind == OwnershipKind::Owned)
4036
48
      ResultVal = B.createOwnedMoveOnlyWrapperToCopyableValue(InstLoc, Val);
4037
102
    else
4038
102
      ResultVal =
4039
102
          B.createGuaranteedMoveOnlyWrapperToCopyableValue(InstLoc, Val);
4040
150
    break;
4041
153
  }
4042
4043
11.4k
  case SILInstructionKind::LoadInst: {
4044
11.4k
    llvm::Optional<LoadOwnershipQualifier> Qualifier;
4045
11.4k
    SourceLoc AddrLoc;
4046
11.4k
    auto parseLoadOwnership = [](StringRef Str) {
4047
6.91k
      return llvm::StringSwitch<llvm::Optional<LoadOwnershipQualifier>>(Str)
4048
6.91k
          .Case("take", LoadOwnershipQualifier::Take)
4049
6.91k
          .Case("copy", LoadOwnershipQualifier::Copy)
4050
6.91k
          .Case("trivial", LoadOwnershipQualifier::Trivial)
4051
6.91k
          .Default(llvm::None);
4052
6.91k
    };
4053
11.4k
    if (parseSILQualifier<LoadOwnershipQualifier>(Qualifier, parseLoadOwnership)
4054
11.4k
        || parseTypedValueRef(Val, AddrLoc, B)
4055
11.4k
        || parseSILDebugLocation(InstLoc, B)) {
4056
0
      return true;
4057
0
    }
4058
11.4k
    if (!Qualifier)
4059
4.55k
      Qualifier = LoadOwnershipQualifier::Unqualified;
4060
11.4k
    ResultVal = B.createLoad(InstLoc, Val, Qualifier.value());
4061
11.4k
    break;
4062
11.4k
  }
4063
4064
819
  case SILInstructionKind::LoadBorrowInst: {
4065
819
    SourceLoc AddrLoc;
4066
4067
819
    if (parseTypedValueRef(Val, AddrLoc, B) ||
4068
819
        parseSILDebugLocation(InstLoc, B))
4069
0
      return true;
4070
4071
819
    ResultVal = B.createLoadBorrow(InstLoc, Val);
4072
819
    break;
4073
819
  }
4074
4075
3.65k
  case SILInstructionKind::BeginBorrowInst: {
4076
3.65k
    SourceLoc AddrLoc;
4077
4078
3.65k
    bool isLexical = false;
4079
3.65k
    bool hasPointerEscape = false;
4080
4081
3.65k
    StringRef AttrName;
4082
3.65k
    SourceLoc AttrLoc;
4083
3.93k
    while (parseSILOptional(AttrName, AttrLoc, *this)) {
4084
288
      if (AttrName == "lexical")
4085
276
        isLexical = true;
4086
12
      else if (AttrName == "pointer_escape")
4087
12
        hasPointerEscape = true;
4088
0
      else {
4089
0
        P.diagnose(InstLoc.getSourceLoc(),
4090
0
                   diag::sil_invalid_attribute_for_instruction, AttrName,
4091
0
                   "begin_borrow");
4092
0
        return true;
4093
0
      }
4094
288
    }
4095
4096
3.65k
    if (parseTypedValueRef(Val, AddrLoc, B) ||
4097
3.65k
        parseSILDebugLocation(InstLoc, B))
4098
0
      return true;
4099
4100
3.65k
    ResultVal = B.createBeginBorrow(InstLoc, Val, isLexical, hasPointerEscape);
4101
3.65k
    break;
4102
3.65k
  }
4103
4104
0
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)             \
4105
27
  case SILInstructionKind::Load##Name##Inst: {                                 \
4106
27
    bool isTake = false;                                                       \
4107
27
    SourceLoc addrLoc;                                                         \
4108
27
    if (parseSILOptional(isTake, *this, "take") ||                             \
4109
27
        parseTypedValueRef(Val, addrLoc, B) ||                                 \
4110
27
        parseSILDebugLocation(InstLoc, B))                                     \
4111
27
      return true;                                                             \
4112
27
    if (!Val->getType().is<Name##StorageType>()) {                             \
4113
0
      P.diagnose(addrLoc, diag::sil_operand_not_ref_storage_address, "source", \
4114
0
                 OpcodeName, ReferenceOwnership::Name);                        \
4115
0
    }                                                                          \
4116
27
    ResultVal = B.createLoad##Name(InstLoc, Val, IsTake_t(isTake));            \
4117
27
    break;                                                                     \
4118
27
  }
4119
3.65k
#include "swift/AST/ReferenceStorage.def"
4120
4121
18
  case SILInstructionKind::CopyBlockWithoutEscapingInst: {
4122
18
    SILValue Closure;
4123
18
    if (parseTypedValueRef(Val, B) || parseVerbatim("withoutEscaping") ||
4124
18
        parseTypedValueRef(Closure, B) || parseSILDebugLocation(InstLoc, B))
4125
0
      return true;
4126
4127
18
    ResultVal = B.createCopyBlockWithoutEscaping(InstLoc, Val, Closure);
4128
18
    break;
4129
18
  }
4130
4131
285
  case SILInstructionKind::MarkDependenceInst: {
4132
285
    SILValue Base;
4133
285
    if (parseTypedValueRef(Val, B) || parseVerbatim("on") ||
4134
285
        parseTypedValueRef(Base, B))
4135
0
      return true;
4136
4137
285
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4138
285
    if (parseForwardingOwnershipKind(forwardingOwnership)
4139
285
        || parseSILDebugLocation(InstLoc, B))
4140
0
      return true;
4141
4142
285
    ResultVal = B.createMarkDependence(InstLoc, Val, Base, forwardingOwnership);
4143
285
    break;
4144
285
  }
4145
4146
111
  case SILInstructionKind::BeginDeallocRefInst: {
4147
111
    SILValue allocation;
4148
111
    if (parseTypedValueRef(Val, B) || parseVerbatim("of") ||
4149
111
        parseTypedValueRef(allocation, B) ||
4150
111
        parseSILDebugLocation(InstLoc, B))
4151
0
      return true;
4152
4153
111
    ResultVal = B.createBeginDeallocRef(InstLoc, Val, allocation);
4154
111
    break;
4155
111
  }
4156
4157
372
  case SILInstructionKind::KeyPathInst: {
4158
372
    SmallVector<KeyPathPatternComponent, 4> components;
4159
372
    SILType Ty;
4160
372
    if (parseSILType(Ty) ||
4161
372
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
4162
0
      return true;
4163
4164
372
    GenericParamList *patternParams = nullptr;
4165
372
    GenericSignature patternSig;
4166
372
    CanType rootType;
4167
372
    StringRef objcString;
4168
372
    SmallVector<SILType, 4> operandTypes;
4169
372
    {
4170
372
      patternParams = P.maybeParseGenericParams().getPtrOrNull();
4171
372
      patternSig = handleSILGenericParams(patternParams, &P.SF);
4172
4173
372
      if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
4174
0
        return true;
4175
4176
861
      while (true) {
4177
861
        Identifier componentKind;
4178
861
        SourceLoc componentLoc;
4179
861
        if (parseSILIdentifier(componentKind, componentLoc,
4180
861
                               diag::sil_keypath_expected_component_kind))
4181
0
          return true;
4182
4183
861
        if (componentKind.str() == "root") {
4184
372
          if (P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr,
4185
372
                           "$") ||
4186
372
              parseASTType(rootType, patternSig, patternParams))
4187
0
            return true;
4188
489
        } else if (componentKind.str() == "objc") {
4189
12
          auto tok = P.Tok;
4190
12
          if (P.parseToken(tok::string_literal, diag::expected_tok_in_sil_instr,
4191
12
                           "string literal"))
4192
0
            return true;
4193
4194
12
          auto objcStringValue = tok.getText().drop_front().drop_back();
4195
12
          objcString =
4196
12
              StringRef(P.Context.AllocateCopy<char>(objcStringValue.begin(),
4197
12
                                                     objcStringValue.end()),
4198
12
                        objcStringValue.size());
4199
477
        } else {
4200
477
          KeyPathPatternComponent component;
4201
477
          if (parseKeyPathPatternComponent(component, operandTypes,
4202
477
                                           componentLoc, componentKind, InstLoc,
4203
477
                                           patternSig, patternParams))
4204
0
            return true;
4205
477
          components.push_back(component);
4206
477
        }
4207
4208
861
        if (!P.consumeIf(tok::semi))
4209
372
          break;
4210
861
      }
4211
4212
372
      if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")") ||
4213
372
          parseSILDebugLocation(InstLoc, B))
4214
0
        return true;
4215
372
    }
4216
4217
372
    if (rootType.isNull())
4218
0
      P.diagnose(InstLoc.getSourceLoc(), diag::sil_keypath_no_root);
4219
4220
372
    SmallVector<ParsedSubstitution, 4> parsedSubs;
4221
372
    if (parseSubstitutions(parsedSubs, ContextGenericSig, ContextGenericParams))
4222
0
      return true;
4223
4224
372
    SubstitutionMap subMap;
4225
372
    if (!parsedSubs.empty()) {
4226
129
      if (!patternSig) {
4227
0
        P.diagnose(InstLoc.getSourceLoc(),
4228
0
                   diag::sil_substitutions_on_non_polymorphic_type);
4229
0
        return true;
4230
0
      }
4231
4232
129
      subMap = getApplySubstitutionsFromParsed(*this, patternSig, parsedSubs);
4233
129
      if (!subMap)
4234
0
        return true;
4235
129
    }
4236
4237
372
    SmallVector<SILValue, 4> operands;
4238
4239
372
    if (P.consumeIf(tok::l_paren)) {
4240
90
      while (true) {
4241
90
        SILValue v;
4242
4243
90
        if (operands.size() >= operandTypes.size() ||
4244
90
            !operandTypes[operands.size()]) {
4245
0
          P.diagnose(P.Tok, diag::sil_keypath_no_use_of_operand_in_pattern,
4246
0
                     operands.size());
4247
0
          return true;
4248
0
        }
4249
4250
90
        auto ty = operandTypes[operands.size()].subst(SILMod, subMap);
4251
4252
90
        if (parseValueRef(v, ty, RegularLocation(P.Tok.getLoc()), B))
4253
0
          return true;
4254
90
        operands.push_back(v);
4255
4256
90
        if (P.consumeIf(tok::comma))
4257
39
          continue;
4258
51
        if (P.consumeIf(tok::r_paren))
4259
51
          break;
4260
0
        return true;
4261
51
      }
4262
51
    }
4263
4264
372
    if (parseSILDebugLocation(InstLoc, B))
4265
0
      return true;
4266
4267
372
    CanGenericSignature canSig;
4268
372
    if (patternSig) {
4269
129
      canSig = patternSig.getCanonicalSignature();
4270
129
    }
4271
372
    CanType leafType;
4272
372
    if (!components.empty())
4273
366
      leafType = components.back().getComponentType();
4274
6
    else
4275
6
      leafType = rootType;
4276
372
    auto pattern = KeyPathPattern::get(B.getModule(), canSig, rootType,
4277
372
                                       leafType, components, objcString);
4278
4279
372
    ResultVal = B.createKeyPath(InstLoc, pattern, subMap, operands, Ty);
4280
372
    break;
4281
372
  }
4282
4283
    // Conversion instructions.
4284
1.66k
  case SILInstructionKind::UncheckedRefCastInst:
4285
2.27k
  case SILInstructionKind::UncheckedAddrCastInst:
4286
2.59k
  case SILInstructionKind::UncheckedTrivialBitCastInst:
4287
3.02k
  case SILInstructionKind::UncheckedBitwiseCastInst:
4288
3.05k
  case SILInstructionKind::UncheckedValueCastInst:
4289
4.04k
  case SILInstructionKind::UpcastInst:
4290
5.15k
  case SILInstructionKind::AddressToPointerInst:
4291
5.26k
  case SILInstructionKind::BridgeObjectToRefInst:
4292
5.38k
  case SILInstructionKind::BridgeObjectToWordInst:
4293
5.57k
  case SILInstructionKind::RefToRawPointerInst:
4294
5.71k
  case SILInstructionKind::RawPointerToRefInst:
4295
5.71k
#define LOADABLE_REF_STORAGE(Name, ...)                                        \
4296
11.7k
  case SILInstructionKind::RefTo##Name##Inst:                                  \
4297
11.8k
  case SILInstructionKind::Name##ToRefInst:
4298
23.6k
#include "swift/AST/ReferenceStorage.def"
4299
23.6k
  case SILInstructionKind::ThinToThickFunctionInst:
4300
6.86k
  case SILInstructionKind::ThickToObjCMetatypeInst:
4301
6.90k
  case SILInstructionKind::ObjCToThickMetatypeInst:
4302
7.30k
  case SILInstructionKind::ConvertFunctionInst:
4303
7.79k
  case SILInstructionKind::ConvertEscapeToNoEscapeInst:
4304
7.84k
  case SILInstructionKind::ObjCExistentialMetatypeToObjectInst:
4305
7.90k
  case SILInstructionKind::ObjCMetatypeToObjectInst: {
4306
7.90k
    SILType Ty;
4307
7.90k
    Identifier ToToken;
4308
7.90k
    SourceLoc ToLoc;
4309
7.90k
    bool not_guaranteed = false;
4310
7.90k
    bool without_actually_escaping = false;
4311
7.90k
    bool needsStackProtection = false;
4312
7.90k
    if (Opcode == SILInstructionKind::ConvertEscapeToNoEscapeInst) {
4313
486
      StringRef attrName;
4314
486
      if (parseSILOptional(attrName, *this)) {
4315
173
        if (attrName.equals("not_guaranteed"))
4316
173
          not_guaranteed = true;
4317
0
        else
4318
0
          return true;
4319
173
      }
4320
7.90k
    } if (Opcode == SILInstructionKind::AddressToPointerInst) {
4321
1.11k
      if (parseSILOptional(needsStackProtection, *this, "stack_protection"))
4322
0
        return true;
4323
1.11k
    }
4324
  
4325
7.90k
    if (parseTypedValueRef(Val, B) ||
4326
7.90k
        parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
4327
7.90k
                           "to"))
4328
0
      return true;
4329
4330
7.90k
    if (ToToken.str() != "to") {
4331
0
      P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
4332
0
      return true;
4333
0
    }
4334
7.90k
    if (Opcode == SILInstructionKind::ConvertFunctionInst) {
4335
398
      StringRef attrName;
4336
398
      if (parseSILOptional(attrName, *this)) {
4337
12
        if (attrName.equals("without_actually_escaping"))
4338
12
          without_actually_escaping = true;
4339
0
        else
4340
0
          return true;
4341
12
      }
4342
398
    }
4343
7.90k
    if (parseSILType(Ty))
4344
0
      return true;
4345
4346
7.90k
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4347
7.90k
    if (ForwardingInstruction::isa(Opcode)) {
4348
3.96k
      if (parseForwardingOwnershipKind(forwardingOwnership))
4349
0
        return true;
4350
3.96k
    }
4351
4352
7.90k
    if (parseSILDebugLocation(InstLoc, B)) {
4353
0
      return true;
4354
0
    }
4355
4356
7.90k
    switch (Opcode) {
4357
0
    default:
4358
0
      llvm_unreachable("Out of sync with parent switch");
4359
1.66k
    case SILInstructionKind::UncheckedRefCastInst:
4360
1.66k
      ResultVal =
4361
1.66k
          B.createUncheckedRefCast(InstLoc, Val, Ty, forwardingOwnership);
4362
1.66k
      break;
4363
606
    case SILInstructionKind::UncheckedAddrCastInst:
4364
606
      ResultVal = B.createUncheckedAddrCast(InstLoc, Val, Ty);
4365
606
      break;
4366
324
    case SILInstructionKind::UncheckedTrivialBitCastInst:
4367
324
      ResultVal = B.createUncheckedTrivialBitCast(InstLoc, Val, Ty);
4368
324
      break;
4369
426
    case SILInstructionKind::UncheckedBitwiseCastInst:
4370
426
      ResultVal = B.createUncheckedBitwiseCast(InstLoc, Val, Ty);
4371
426
      break;
4372
30
    case SILInstructionKind::UncheckedValueCastInst:
4373
30
      ResultVal =
4374
30
          B.createUncheckedValueCast(InstLoc, Val, Ty, forwardingOwnership);
4375
30
      break;
4376
990
    case SILInstructionKind::UpcastInst:
4377
990
      ResultVal = B.createUpcast(InstLoc, Val, Ty, forwardingOwnership);
4378
990
      break;
4379
398
    case SILInstructionKind::ConvertFunctionInst:
4380
398
      ResultVal = B.createConvertFunction(
4381
398
          InstLoc, Val, Ty, without_actually_escaping, forwardingOwnership);
4382
398
      break;
4383
486
    case SILInstructionKind::ConvertEscapeToNoEscapeInst:
4384
486
      ResultVal =
4385
486
          B.createConvertEscapeToNoEscape(InstLoc, Val, Ty, !not_guaranteed);
4386
486
      break;
4387
1.11k
    case SILInstructionKind::AddressToPointerInst:
4388
1.11k
      ResultVal = B.createAddressToPointer(InstLoc, Val, Ty, needsStackProtection);
4389
1.11k
      break;
4390
111
    case SILInstructionKind::BridgeObjectToRefInst:
4391
111
      ResultVal =
4392
111
          B.createBridgeObjectToRef(InstLoc, Val, Ty, forwardingOwnership);
4393
111
      break;
4394
117
    case SILInstructionKind::BridgeObjectToWordInst:
4395
117
      ResultVal = B.createBridgeObjectToWord(InstLoc, Val);
4396
117
      break;
4397
186
    case SILInstructionKind::RefToRawPointerInst:
4398
186
      ResultVal = B.createRefToRawPointer(InstLoc, Val, Ty);
4399
186
      break;
4400
141
    case SILInstructionKind::RawPointerToRefInst:
4401
141
      ResultVal = B.createRawPointerToRef(InstLoc, Val, Ty);
4402
141
      break;
4403
0
#define LOADABLE_REF_STORAGE(Name, ...)                                        \
4404
201
  case SILInstructionKind::RefTo##Name##Inst:                                  \
4405
201
    ResultVal = B.createRefTo##Name(InstLoc, Val, Ty);                         \
4406
201
    break;                                                                     \
4407
117
  case SILInstructionKind::Name##ToRefInst:                                    \
4408
117
    ResultVal = B.create##Name##ToRef(InstLoc, Val, Ty);                       \
4409
117
    break;
4410
141
#include "swift/AST/ReferenceStorage.def"
4411
768
    case SILInstructionKind::ThinToThickFunctionInst:
4412
768
      ResultVal =
4413
768
          B.createThinToThickFunction(InstLoc, Val, Ty, forwardingOwnership);
4414
768
      break;
4415
63
    case SILInstructionKind::ThickToObjCMetatypeInst:
4416
63
      ResultVal = B.createThickToObjCMetatype(InstLoc, Val, Ty);
4417
63
      break;
4418
48
    case SILInstructionKind::ObjCToThickMetatypeInst:
4419
48
      ResultVal = B.createObjCToThickMetatype(InstLoc, Val, Ty);
4420
48
      break;
4421
60
    case SILInstructionKind::ObjCMetatypeToObjectInst:
4422
60
      ResultVal = B.createObjCMetatypeToObject(InstLoc, Val, Ty);
4423
60
      break;
4424
54
    case SILInstructionKind::ObjCExistentialMetatypeToObjectInst:
4425
54
      ResultVal = B.createObjCExistentialMetatypeToObject(InstLoc, Val, Ty);
4426
54
      break;
4427
7.90k
    }
4428
7.90k
    break;
4429
7.90k
  }
4430
7.90k
  case SILInstructionKind::PointerToAddressInst: {
4431
1.32k
    SILType Ty;
4432
1.32k
    Identifier ToToken;
4433
1.32k
    SourceLoc ToLoc;
4434
1.32k
    StringRef attr;
4435
1.32k
    if (parseTypedValueRef(Val, B) ||
4436
1.32k
        parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
4437
1.32k
                           "to"))
4438
0
      return true;
4439
4440
1.32k
    bool isStrict = false;
4441
1.32k
    bool isInvariant = false;
4442
1.32k
    llvm::MaybeAlign alignment;
4443
1.32k
    uint64_t parsedValue = 0;
4444
2.44k
    while (parseSILOptional(attr, parsedValue, ToLoc, *this)) {
4445
1.11k
      if (attr.empty())
4446
0
        return true;
4447
4448
1.11k
      if (attr.equals("strict"))
4449
1.05k
        isStrict = true;
4450
4451
1.11k
      if (attr.equals("invariant"))
4452
6
        isInvariant = true;
4453
4454
1.11k
      if (attr.equals("align"))
4455
57
        alignment = llvm::Align(parsedValue);
4456
1.11k
    }
4457
4458
1.32k
    if (parseSILType(Ty) || parseSILDebugLocation(InstLoc, B))
4459
0
      return true;
4460
4461
1.32k
    if (ToToken.str() != "to") {
4462
0
      P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
4463
0
      return true;
4464
0
    }
4465
4466
1.32k
    ResultVal = B.createPointerToAddress(InstLoc, Val, Ty, isStrict,
4467
1.32k
                                         isInvariant, alignment);
4468
1.32k
    break;
4469
1.32k
  }
4470
60
  case SILInstructionKind::RefToBridgeObjectInst: {
4471
60
    SILValue BitsVal;
4472
60
    if (parseTypedValueRef(Val, B) ||
4473
60
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4474
60
        parseTypedValueRef(BitsVal, B))
4475
0
      return true;
4476
4477
60
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4478
60
    if (parseForwardingOwnershipKind(forwardingOwnership)
4479
60
        || parseSILDebugLocation(InstLoc, B))
4480
0
      return true;
4481
4482
60
    ResultVal =
4483
60
        B.createRefToBridgeObject(InstLoc, Val, BitsVal, forwardingOwnership);
4484
60
    break;
4485
60
  }
4486
4487
459
  case SILInstructionKind::CheckedCastAddrBranchInst: {
4488
459
    Identifier consumptionKindToken;
4489
459
    SourceLoc consumptionKindLoc;
4490
459
    if (parseSILIdentifier(consumptionKindToken, consumptionKindLoc,
4491
459
                           diag::expected_tok_in_sil_instr,
4492
459
                           "cast consumption kind")) {
4493
0
      return true;
4494
0
    }
4495
    // NOTE: BorrowAlways is not a supported cast kind for address types, so we
4496
    // purposely do not parse it here.
4497
459
    auto kind = llvm::StringSwitch<llvm::Optional<CastConsumptionKind>>(
4498
459
                    consumptionKindToken.str())
4499
459
                    .Case("take_always", CastConsumptionKind::TakeAlways)
4500
459
                    .Case("take_on_success", CastConsumptionKind::TakeOnSuccess)
4501
459
                    .Case("copy_on_success", CastConsumptionKind::CopyOnSuccess)
4502
459
                    .Default(llvm::None);
4503
4504
459
    if (!kind) {
4505
0
      P.diagnose(consumptionKindLoc, diag::expected_tok_in_sil_instr,
4506
0
                 "cast consumption kind");
4507
0
      return true;
4508
0
    }
4509
459
    auto consumptionKind = kind.value();
4510
4511
459
    if (parseSourceAndDestAddress() || parseConditionalBranchDestinations() ||
4512
459
        parseSILDebugLocation(InstLoc, B))
4513
0
      return true;
4514
4515
459
    ResultVal = B.createCheckedCastAddrBranch(
4516
459
        InstLoc, consumptionKind, SourceAddr, SourceType, DestAddr, TargetType,
4517
459
        getBBForReference(SuccessBBName, SuccessBBLoc),
4518
459
        getBBForReference(FailureBBName, FailureBBLoc));
4519
459
    break;
4520
459
  }
4521
33
  case SILInstructionKind::UncheckedRefCastAddrInst:
4522
33
    if (parseSourceAndDestAddress() || parseSILDebugLocation(InstLoc, B))
4523
0
      return true;
4524
4525
33
    ResultVal = B.createUncheckedRefCastAddr(InstLoc, SourceAddr, SourceType,
4526
33
                                             DestAddr, TargetType);
4527
33
    break;
4528
4529
411
  case SILInstructionKind::UnconditionalCheckedCastAddrInst:
4530
411
    if (parseSourceAndDestAddress() || parseSILDebugLocation(InstLoc, B))
4531
0
      return true;
4532
4533
411
    ResultVal = B.createUnconditionalCheckedCastAddr(
4534
411
        InstLoc, SourceAddr, SourceType, DestAddr, TargetType);
4535
411
    break;
4536
4537
372
  case SILInstructionKind::UnconditionalCheckedCastInst: {
4538
372
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") ||
4539
372
        parseASTType(TargetType))
4540
0
      return true;
4541
4542
372
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4543
372
    if (parseForwardingOwnershipKind(forwardingOwnership)
4544
372
        || parseSILDebugLocation(InstLoc, B))
4545
0
      return true;
4546
4547
372
    auto opaque = Lowering::AbstractionPattern::getOpaque();
4548
372
    ResultVal = B.createUnconditionalCheckedCast(
4549
372
        InstLoc, Val, F->getLoweredType(opaque, TargetType), TargetType,
4550
372
        forwardingOwnership);
4551
372
    break;
4552
372
  }
4553
4554
561
  case SILInstructionKind::CheckedCastBranchInst: {
4555
561
    bool isExact = false;
4556
561
    if (Opcode == SILInstructionKind::CheckedCastBranchInst &&
4557
561
        parseSILOptional(isExact, *this, "exact"))
4558
0
      return true;
4559
4560
561
    if (parseASTType(SourceType) || parseVerbatim("in"))
4561
0
      return true;
4562
4563
561
    if (parseTypedValueRef(Val, B) || parseVerbatim("to") ||
4564
561
        parseASTType(TargetType) || parseConditionalBranchDestinations())
4565
0
      return true;
4566
4567
561
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4568
561
    if (parseForwardingOwnershipKind(forwardingOwnership)
4569
561
        || parseSILDebugLocation(InstLoc, B)) {
4570
0
      return true;
4571
0
    }
4572
4573
561
    auto opaque = Lowering::AbstractionPattern::getOpaque();
4574
561
    ResultVal = B.createCheckedCastBranch(
4575
561
        InstLoc, isExact, Val, SourceType,
4576
561
        F->getLoweredType(opaque, TargetType), TargetType,
4577
561
        getBBForReference(SuccessBBName, SuccessBBLoc),
4578
561
        getBBForReference(FailureBBName, FailureBBLoc), forwardingOwnership);
4579
561
    break;
4580
561
  }
4581
500
  case SILInstructionKind::MarkUninitializedInst: {
4582
500
    if (P.parseToken(tok::l_square, diag::expected_tok_in_sil_instr, "["))
4583
0
      return true;
4584
4585
500
    Identifier KindId;
4586
500
    SourceLoc KindLoc = P.Tok.getLoc();
4587
500
    if (P.consumeIf(tok::kw_var))
4588
213
      KindId = P.Context.getIdentifier("var");
4589
287
    else if (P.parseIdentifier(KindId, KindLoc, /*diagnoseDollarPrefix=*/false,
4590
287
                               diag::expected_tok_in_sil_instr, "kind"))
4591
0
      return true;
4592
4593
500
    if (P.parseToken(tok::r_square, diag::expected_tok_in_sil_instr, "]"))
4594
0
      return true;
4595
4596
500
    MarkUninitializedInst::Kind Kind;
4597
500
    if (KindId.str() == "var")
4598
213
      Kind = MarkUninitializedInst::Var;
4599
287
    else if (KindId.str() == "rootself")
4600
194
      Kind = MarkUninitializedInst::RootSelf;
4601
93
    else if (KindId.str() == "crossmodulerootself")
4602
0
      Kind = MarkUninitializedInst::CrossModuleRootSelf;
4603
93
    else if (KindId.str() == "derivedself")
4604
30
      Kind = MarkUninitializedInst::DerivedSelf;
4605
63
    else if (KindId.str() == "derivedselfonly")
4606
0
      Kind = MarkUninitializedInst::DerivedSelfOnly;
4607
63
    else if (KindId.str() == "delegatingself")
4608
45
      Kind = MarkUninitializedInst::DelegatingSelf;
4609
18
    else if (KindId.str() == "delegatingselfallocated")
4610
15
      Kind = MarkUninitializedInst::DelegatingSelfAllocated;
4611
3
    else if (KindId.str() == "out")
4612
3
      Kind = MarkUninitializedInst::Out;
4613
0
    else {
4614
0
      P.diagnose(KindLoc, diag::expected_tok_in_sil_instr,
4615
0
                 "var, rootself, crossmodulerootself, derivedself, "
4616
0
                 "derivedselfonly, delegatingself, or delegatingselfallocated");
4617
0
      return true;
4618
0
    }
4619
4620
500
    if (parseTypedValueRef(Val, B))
4621
0
      return true;
4622
4623
500
    ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
4624
500
    if (parseForwardingOwnershipKind(forwardingOwnership)
4625
500
        || parseSILDebugLocation(InstLoc, B))
4626
0
      return true;
4627
4628
500
    ResultVal =
4629
500
        B.createMarkUninitialized(InstLoc, Val, Kind, forwardingOwnership);
4630
500
    break;
4631
500
  }
4632
4633
66
  case SILInstructionKind::MarkFunctionEscapeInst: {
4634
66
    SmallVector<SILValue, 4> OpList;
4635
72
    do {
4636
72
      if (parseTypedValueRef(Val, B))
4637
0
        return true;
4638
72
      OpList.push_back(Val);
4639
72
    } while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma));
4640
4641
66
    if (parseSILDebugLocation(InstLoc, B))
4642
0
      return true;
4643
66
    ResultVal = B.createMarkFunctionEscape(InstLoc, OpList);
4644
66
    break;
4645
66
  }
4646
4647
557
  case SILInstructionKind::AssignInst:
4648
13.3k
  case SILInstructionKind::StoreInst: {
4649
13.3k
    UnresolvedValueName From;
4650
13.3k
    SourceLoc ToLoc, AddrLoc;
4651
13.3k
    Identifier ToToken;
4652
13.3k
    SILValue AddrVal;
4653
13.3k
    llvm::Optional<StoreOwnershipQualifier> StoreQualifier;
4654
13.3k
    llvm::Optional<AssignOwnershipQualifier> AssignQualifier;
4655
13.3k
    bool IsStore = Opcode == SILInstructionKind::StoreInst;
4656
13.3k
    bool IsAssign = Opcode == SILInstructionKind::AssignInst;
4657
13.3k
    if (parseValueName(From) ||
4658
13.3k
        parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
4659
13.3k
                           "to"))
4660
0
      return true;
4661
4662
13.3k
    auto parseStoreOwnership = [](StringRef Str) {
4663
7.40k
      return llvm::StringSwitch<llvm::Optional<StoreOwnershipQualifier>>(Str)
4664
7.40k
          .Case("init", StoreOwnershipQualifier::Init)
4665
7.40k
          .Case("assign", StoreOwnershipQualifier::Assign)
4666
7.40k
          .Case("trivial", StoreOwnershipQualifier::Trivial)
4667
7.40k
          .Default(llvm::None);
4668
7.40k
    };
4669
13.3k
    if (IsStore
4670
13.3k
        && parseSILQualifier<StoreOwnershipQualifier>(StoreQualifier,
4671
12.7k
                                                      parseStoreOwnership))
4672
0
      return true;
4673
4674
13.3k
    auto parseAssignOwnership = [](StringRef Str) {
4675
51
      return llvm::StringSwitch<llvm::Optional<AssignOwnershipQualifier>>(Str)
4676
51
          .Case("reassign", AssignOwnershipQualifier::Reassign)
4677
51
          .Case("reinit", AssignOwnershipQualifier::Reinit)
4678
51
          .Case("init", AssignOwnershipQualifier::Init)
4679
51
          .Default(llvm::None);
4680
51
    };
4681
13.3k
    if (IsAssign
4682
13.3k
        && parseSILQualifier<AssignOwnershipQualifier>(AssignQualifier,
4683
557
                                                       parseAssignOwnership))
4684
0
      return true;
4685
4686
13.3k
    if (parseTypedValueRef(AddrVal, AddrLoc, B) ||
4687
13.3k
        parseSILDebugLocation(InstLoc, B))
4688
0
      return true;
4689
4690
13.3k
    if (ToToken.str() != "to") {
4691
0
      P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
4692
0
      return true;
4693
0
    }
4694
4695
13.3k
    if (!AddrVal->getType().isAddress()) {
4696
0
      P.diagnose(AddrLoc, diag::sil_operand_not_address, "destination",
4697
0
                 OpcodeName);
4698
0
      return true;
4699
0
    }
4700
4701
13.3k
    SILType ValType = AddrVal->getType().getObjectType();
4702
4703
13.3k
    if (IsStore) {
4704
12.7k
      if (!StoreQualifier)
4705
5.38k
        StoreQualifier = StoreOwnershipQualifier::Unqualified;
4706
12.7k
      ResultVal =
4707
12.7k
          B.createStore(InstLoc, getLocalValue(From, ValType, InstLoc, B),
4708
12.7k
                        AddrVal, StoreQualifier.value());
4709
12.7k
    } else {
4710
557
      assert(IsAssign);
4711
557
      if (!AssignQualifier)
4712
506
        AssignQualifier = AssignOwnershipQualifier::Unknown;
4713
4714
557
      ResultVal =
4715
557
          B.createAssign(InstLoc, getLocalValue(From, ValType, InstLoc, B),
4716
557
                         AddrVal, AssignQualifier.value());
4717
557
    }
4718
4719
0
    break;
4720
13.3k
  }
4721
4722
15
  case SILInstructionKind::AssignByWrapperInst: {
4723
15
    SILValue Src, DestAddr, InitFn, SetFn;
4724
15
    SourceLoc DestLoc;
4725
15
    AssignByWrapperInst::Mode mode;
4726
4727
15
    if (parseTypedValueRef(Src, B) || parseVerbatim("to") ||
4728
15
        parseAssignByWrapperMode(mode, *this) ||
4729
15
        parseTypedValueRef(DestAddr, DestLoc, B) ||
4730
15
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4731
15
        parseVerbatim("init") || parseTypedValueRef(InitFn, B) ||
4732
15
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4733
15
        parseVerbatim("set") || parseTypedValueRef(SetFn, B) ||
4734
15
        parseSILDebugLocation(InstLoc, B))
4735
0
      return true;
4736
4737
15
    if (!DestAddr->getType().isAddress()) {
4738
0
      P.diagnose(DestLoc, diag::sil_operand_not_address, "destination",
4739
0
                 OpcodeName);
4740
0
      return true;
4741
0
    }
4742
4743
15
    ResultVal = B.createAssignByWrapper(InstLoc, Src, DestAddr,
4744
15
                                        InitFn, SetFn, mode);
4745
15
    break;
4746
15
  }
4747
4748
21
  case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst: {
4749
21
    SILValue addrVal;
4750
21
    SourceLoc addrLoc;
4751
21
    if (parseTypedValueRef(addrVal, addrLoc, B))
4752
0
      return true;
4753
4754
21
    if (parseSILDebugLocation(InstLoc, B))
4755
0
      return true;
4756
4757
21
    if (!addrVal->getType().isAddress()) {
4758
3
      P.diagnose(addrLoc, diag::sil_operand_not_address, "operand", OpcodeName);
4759
3
      return true;
4760
3
    }
4761
4762
18
    if (!addrVal->getType().isMoveOnlyWrapped()) {
4763
3
      P.diagnose(addrLoc, diag::sil_operand_has_incorrect_moveonlywrapped,
4764
3
                 "operand", OpcodeName, 0);
4765
3
      return true;
4766
3
    }
4767
4768
15
    ResultVal = B.createMoveOnlyWrapperToCopyableAddr(InstLoc, addrVal);
4769
15
    break;
4770
18
  }
4771
12
  case SILInstructionKind::MoveOnlyWrapperToCopyableBoxInst: {
4772
12
    SILValue addrVal;
4773
12
    SourceLoc addrLoc;
4774
12
    if (parseTypedValueRef(addrVal, addrLoc, B))
4775
0
      return true;
4776
4777
12
    if (parseSILDebugLocation(InstLoc, B))
4778
0
      return true;
4779
4780
12
    if (!addrVal->getType().is<SILBoxType>()) {
4781
0
      P.diagnose(addrLoc, diag::sil_box_expected, OpcodeName);
4782
0
      return true;
4783
0
    }
4784
4785
12
    if (!addrVal->getType().isBoxedMoveOnlyWrappedType(
4786
12
            addrVal->getFunction())) {
4787
0
      P.diagnose(addrLoc, diag::sil_operand_has_incorrect_moveonlywrapped,
4788
0
                 "operand", OpcodeName, 0);
4789
0
      return true;
4790
0
    }
4791
4792
12
    ResultVal = B.createMoveOnlyWrapperToCopyableBox(InstLoc, addrVal);
4793
12
    break;
4794
12
  }
4795
18
  case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst: {
4796
18
    SILValue addrVal;
4797
18
    SourceLoc addrLoc;
4798
18
    if (parseTypedValueRef(addrVal, addrLoc, B))
4799
0
      return true;
4800
4801
18
    if (parseSILDebugLocation(InstLoc, B))
4802
0
      return true;
4803
4804
18
    if (!addrVal->getType().isAddress()) {
4805
3
      P.diagnose(addrLoc, diag::sil_operand_not_address, "operand", OpcodeName);
4806
3
      return true;
4807
3
    }
4808
4809
15
    if (addrVal->getType().isMoveOnlyWrapped()) {
4810
3
      P.diagnose(addrLoc, diag::sil_operand_has_incorrect_moveonlywrapped,
4811
3
                 "operand", OpcodeName, 1);
4812
3
      return true;
4813
3
    }
4814
4815
12
    ResultVal = B.createCopyableToMoveOnlyWrapperAddr(InstLoc, addrVal);
4816
12
    break;
4817
15
  }
4818
4819
9
  case SILInstructionKind::AssignOrInitInst: {
4820
9
    ValueDecl *Prop;
4821
9
    SILValue Self, Src, InitFn, SetFn;
4822
9
    AssignOrInitInst::Mode Mode;
4823
9
    llvm::SmallVector<unsigned, 2> assignments;
4824
4825
9
    if (parseAssignOrInitMode(Mode, *this) ||
4826
9
        parseAssignOrInitAssignments(assignments, *this) ||
4827
9
        parseSILDottedPath(Prop) ||
4828
9
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4829
9
        parseVerbatim("self") || parseTypedValueRef(Self, B) ||
4830
9
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4831
9
        parseVerbatim("value") || parseTypedValueRef(Src, B) ||
4832
9
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4833
9
        parseVerbatim("init") || parseTypedValueRef(InitFn, B) ||
4834
9
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4835
9
        parseVerbatim("set") || parseTypedValueRef(SetFn, B) ||
4836
9
        parseSILDebugLocation(InstLoc, B))
4837
0
      return true;
4838
4839
9
    auto *AI = B.createAssignOrInit(InstLoc, cast<VarDecl>(Prop), Self, Src,
4840
9
                                    InitFn, SetFn, Mode);
4841
4842
9
    for (unsigned index : assignments)
4843
0
      AI->markAsInitialized(index);
4844
4845
9
    ResultVal = AI;
4846
9
    break;
4847
9
  }
4848
4849
4.19k
  case SILInstructionKind::BeginAccessInst:
4850
4.25k
  case SILInstructionKind::BeginUnpairedAccessInst:
4851
8.60k
  case SILInstructionKind::EndAccessInst:
4852
8.65k
  case SILInstructionKind::EndUnpairedAccessInst: {
4853
8.65k
    ParsedEnum<SILAccessKind> kind;
4854
8.65k
    ParsedEnum<SILAccessEnforcement> enforcement;
4855
8.65k
    ParsedEnum<bool> aborting;
4856
8.65k
    ParsedEnum<bool> noNestedConflict;
4857
8.65k
    ParsedEnum<bool> fromBuiltin;
4858
4859
8.65k
    bool isBeginAccess =
4860
8.65k
        (Opcode == SILInstructionKind::BeginAccessInst ||
4861
8.65k
         Opcode == SILInstructionKind::BeginUnpairedAccessInst);
4862
8.65k
    bool wantsEnforcement =
4863
8.65k
        (isBeginAccess || Opcode == SILInstructionKind::EndUnpairedAccessInst);
4864
4865
17.5k
    while (P.consumeIf(tok::l_square)) {
4866
8.92k
      Identifier ident;
4867
8.92k
      SourceLoc identLoc;
4868
8.92k
      if (parseSILIdentifier(ident, identLoc,
4869
8.92k
                             diag::expected_in_attribute_list)) {
4870
0
        if (P.consumeIf(tok::r_square)) {
4871
0
          continue;
4872
0
        } else {
4873
0
          return true;
4874
0
        }
4875
0
      }
4876
8.92k
      StringRef attr = ident.str();
4877
4878
8.92k
      auto setEnforcement = [&](SILAccessEnforcement value) {
4879
4.30k
        maybeSetEnum(wantsEnforcement, enforcement, value, attr, identLoc);
4880
4.30k
      };
4881
8.92k
      auto setKind = [&](SILAccessKind value) {
4882
4.25k
        maybeSetEnum(isBeginAccess, kind, value, attr, identLoc);
4883
4.25k
      };
4884
8.92k
      auto setAborting = [&](bool value) {
4885
0
        maybeSetEnum(!isBeginAccess, aborting, value, attr, identLoc);
4886
0
      };
4887
8.92k
      auto setNoNestedConflict = [&](bool value) {
4888
336
        maybeSetEnum(isBeginAccess, noNestedConflict, value, attr, identLoc);
4889
336
      };
4890
8.92k
      auto setFromBuiltin = [&](bool value) {
4891
27
        maybeSetEnum(Opcode != SILInstructionKind::EndAccessInst, fromBuiltin,
4892
27
                     value, attr, identLoc);
4893
27
      };
4894
4895
8.92k
      if (attr == "unknown") {
4896
1.33k
        setEnforcement(SILAccessEnforcement::Unknown);
4897
7.58k
      } else if (attr == "static") {
4898
969
        setEnforcement(SILAccessEnforcement::Static);
4899
6.61k
      } else if (attr == "dynamic") {
4900
1.95k
        setEnforcement(SILAccessEnforcement::Dynamic);
4901
4.65k
      } else if (attr == "unsafe") {
4902
42
        setEnforcement(SILAccessEnforcement::Unsafe);
4903
4.61k
      } else if (attr == "signed") {
4904
0
        setEnforcement(SILAccessEnforcement::Signed);
4905
4.61k
      } else if (attr == "init") {
4906
6
        setKind(SILAccessKind::Init);
4907
4.61k
      } else if (attr == "read") {
4908
1.83k
        setKind(SILAccessKind::Read);
4909
2.77k
      } else if (attr == "modify") {
4910
2.34k
        setKind(SILAccessKind::Modify);
4911
2.34k
      } else if (attr == "deinit") {
4912
72
        setKind(SILAccessKind::Deinit);
4913
363
      } else if (attr == "abort") {
4914
0
        setAborting(true);
4915
363
      } else if (attr == "no_nested_conflict") {
4916
336
        setNoNestedConflict(true);
4917
336
      } else if (attr == "builtin") {
4918
27
        setFromBuiltin(true);
4919
27
      } else {
4920
0
        P.diagnose(identLoc, diag::unknown_attribute, attr);
4921
0
      }
4922
4923
8.92k
      if (!P.consumeIf(tok::r_square))
4924
0
        return true;
4925
8.92k
    }
4926
4927
8.65k
    if (isBeginAccess && !kind.isSet()) {
4928
0
      P.diagnose(OpcodeLoc, diag::sil_expected_access_kind, OpcodeName);
4929
0
      kind.Value = SILAccessKind::Read;
4930
0
    }
4931
4932
8.65k
    if (wantsEnforcement && !enforcement.isSet()) {
4933
0
      P.diagnose(OpcodeLoc, diag::sil_expected_access_enforcement, OpcodeName);
4934
0
      enforcement.Value = SILAccessEnforcement::Unsafe;
4935
0
    }
4936
4937
8.65k
    if (!isBeginAccess && !aborting.isSet())
4938
4.40k
      aborting.Value = false;
4939
4940
8.65k
    if (isBeginAccess && !noNestedConflict.isSet())
4941
3.91k
      noNestedConflict.Value = false;
4942
4943
8.65k
    if (!fromBuiltin.isSet())
4944
8.62k
      fromBuiltin.Value = false;
4945
4946
8.65k
    SILValue addrVal;
4947
8.65k
    SourceLoc addrLoc;
4948
8.65k
    if (parseTypedValueRef(addrVal, addrLoc, B))
4949
0
      return true;
4950
4951
8.65k
    SILValue bufferVal;
4952
8.65k
    SourceLoc bufferLoc;
4953
8.65k
    if (Opcode == SILInstructionKind::BeginUnpairedAccessInst &&
4954
8.65k
        (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
4955
63
         parseTypedValueRef(bufferVal, bufferLoc, B)))
4956
0
      return true;
4957
4958
8.65k
    if (parseSILDebugLocation(InstLoc, B))
4959
0
      return true;
4960
4961
8.65k
    if (!addrVal->getType().isAddress()) {
4962
0
      P.diagnose(addrLoc, diag::sil_operand_not_address, "operand", OpcodeName);
4963
0
      return true;
4964
0
    }
4965
4966
8.65k
    if (Opcode == SILInstructionKind::BeginAccessInst) {
4967
4.19k
      ResultVal = B.createBeginAccess(InstLoc, addrVal, *kind, *enforcement,
4968
4.19k
                                      *noNestedConflict, *fromBuiltin);
4969
4.46k
    } else if (Opcode == SILInstructionKind::EndAccessInst) {
4970
4.34k
      ResultVal = B.createEndAccess(InstLoc, addrVal, *aborting);
4971
4.34k
    } else if (Opcode == SILInstructionKind::BeginUnpairedAccessInst) {
4972
63
      ResultVal = B.createBeginUnpairedAccess(InstLoc, addrVal, bufferVal,
4973
63
                                              *kind, *enforcement,
4974
63
                                              *noNestedConflict, *fromBuiltin);
4975
63
    } else {
4976
54
      ResultVal = B.createEndUnpairedAccess(InstLoc, addrVal, *enforcement,
4977
54
                                            *aborting, *fromBuiltin);
4978
54
    }
4979
8.65k
    break;
4980
8.65k
  }
4981
4982
0
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)             \
4983
102
  case SILInstructionKind::Store##Name##Inst:
4984
8.65k
#include "swift/AST/ReferenceStorage.def"
4985
387
  case SILInstructionKind::StoreBorrowInst: {
4986
387
    UnresolvedValueName from;
4987
387
    bool isRefStorage = false;
4988
387
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)             \
4989
774
  isRefStorage |= Opcode == SILInstructionKind::Store##Name##Inst;
4990
387
#include "swift/AST/ReferenceStorage.def"
4991
4992
387
    SourceLoc toLoc, addrLoc;
4993
387
    Identifier toToken;
4994
387
    SILValue addrVal;
4995
387
    bool isInit = false;
4996
387
    if (parseValueName(from) ||
4997
387
        parseSILIdentifier(toToken, toLoc, diag::expected_tok_in_sil_instr,
4998
387
                           "to") ||
4999
387
        (isRefStorage && parseSILOptional(isInit, *this, "init")) ||
5000
387
        parseTypedValueRef(addrVal, addrLoc, B) ||
5001
387
        parseSILDebugLocation(InstLoc, B))
5002
0
      return true;
5003
5004
387
    if (toToken.str() != "to") {
5005
0
      P.diagnose(toLoc, diag::expected_tok_in_sil_instr, "to");
5006
0
      return true;
5007
0
    }
5008
5009
387
    if (!addrVal->getType().isAddress()) {
5010
0
      P.diagnose(addrLoc, diag::sil_operand_not_address, "destination",
5011
0
                 OpcodeName);
5012
0
      return true;
5013
0
    }
5014
5015
387
    if (Opcode == SILInstructionKind::StoreBorrowInst) {
5016
330
      SILType valueTy = addrVal->getType().getObjectType();
5017
330
      ResultVal = B.createStoreBorrow(
5018
330
          InstLoc, getLocalValue(from, valueTy, InstLoc, B), addrVal);
5019
330
      break;
5020
330
    }
5021
5022
57
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)             \
5023
69
  if (Opcode == SILInstructionKind::Store##Name##Inst) {                       \
5024
57
    auto refType = addrVal->getType().getAs<Name##StorageType>();              \
5025
57
    if (!refType) {                                                            \
5026
0
      P.diagnose(addrLoc, diag::sil_operand_not_ref_storage_address,           \
5027
0
                 "destination", OpcodeName, ReferenceOwnership::Name);         \
5028
0
      return true;                                                             \
5029
0
    }                                                                          \
5030
57
    auto valueTy = SILType::getPrimitiveObjectType(refType.getReferentType()); \
5031
57
    ResultVal =                                                                \
5032
57
        B.createStore##Name(InstLoc, getLocalValue(from, valueTy, InstLoc, B), \
5033
57
                            addrVal, IsInitialization_t(isInit));              \
5034
57
    break;                                                                     \
5035
57
  }
5036
387
#include "swift/AST/ReferenceStorage.def"
5037
5038
0
    break;
5039
69
  }
5040
30
  case SILInstructionKind::AllocPackInst: {
5041
30
    SILType Ty;
5042
30
    if (parseSILType(Ty))
5043
0
      return true;
5044
5045
30
    ResultVal = B.createAllocPack(InstLoc, Ty);
5046
30
    break;
5047
30
  }
5048
12
  case SILInstructionKind::AllocPackMetadataInst: {
5049
12
    SILType Ty;
5050
12
    if (parseSILType(Ty))
5051
0
      return true;
5052
5053
12
    ResultVal = B.createAllocPackMetadata(InstLoc, Ty);
5054
12
    break;
5055
12
  }
5056
11.5k
  case SILInstructionKind::AllocStackInst: {
5057
11.5k
    bool hasDynamicLifetime = false;
5058
11.5k
    bool isLexical = false;
5059
11.5k
    bool usesMoveableValueDebugInfo = false;
5060
5061
11.5k
    StringRef attributeName;
5062
11.5k
    SourceLoc attributeLoc;
5063
12.4k
    while (parseSILOptional(attributeName, attributeLoc, *this)) {
5064
912
      if (attributeName == "dynamic_lifetime")
5065
72
        hasDynamicLifetime = true;
5066
840
      else if (attributeName == "lexical")
5067
810
        isLexical = true;
5068
30
      else if (attributeName == "moveable_value_debuginfo")
5069
30
        usesMoveableValueDebugInfo = true;
5070
0
      else {
5071
0
        P.diagnose(attributeLoc, diag::sil_invalid_attribute_for_instruction,
5072
0
                   attributeName, "alloc_stack");
5073
0
        return true;
5074
0
      }
5075
912
    }
5076
5077
11.5k
    SILType Ty;
5078
11.5k
    if (parseSILType(Ty))
5079
0
      return true;
5080
5081
11.5k
    SILDebugVariable VarInfo;
5082
11.5k
    if (parseSILDebugVar(VarInfo) || parseSILDebugLocation(InstLoc, B))
5083
0
      return true;
5084
5085
11.5k
    if (Ty.isMoveOnly())
5086
360
      usesMoveableValueDebugInfo = true;
5087
5088
    // It doesn't make sense to attach a debug var info if the name is empty
5089
11.5k
    if (VarInfo.Name.size())
5090
1.05k
      ResultVal = B.createAllocStack(InstLoc, Ty, VarInfo, hasDynamicLifetime,
5091
1.05k
                                     isLexical, usesMoveableValueDebugInfo);
5092
10.5k
    else
5093
10.5k
      ResultVal = B.createAllocStack(InstLoc, Ty, {}, hasDynamicLifetime,
5094
10.5k
                                     isLexical, usesMoveableValueDebugInfo);
5095
11.5k
    break;
5096
11.5k
  }
5097
6.97k
  case SILInstructionKind::MetatypeInst: {
5098
6.97k
    SILType Ty;
5099
6.97k
    if (parseSILType(Ty))
5100
0
      return true;
5101
5102
6.97k
    assert(Opcode == SILInstructionKind::MetatypeInst);
5103
6.97k
    if (parseSILDebugLocation(InstLoc, B))
5104
0
      return true;
5105
6.97k
    ResultVal = B.createMetatype(InstLoc, Ty);
5106
6.97k
    break;
5107
6.97k
  }
5108
2.35k
  case SILInstructionKind::AllocRefInst:
5109
2.50k
  case SILInstructionKind::AllocRefDynamicInst: {
5110
2.50k
    bool IsObjC = false;
5111
2.50k
    bool OnStack = false;
5112
2.50k
    bool isBare = false;
5113
2.50k
    SmallVector<SILType, 2> ElementTypes;
5114
2.50k
    SmallVector<SILValue, 2> ElementCounts;
5115
3.00k
    while (P.consumeIf(tok::l_square)) {
5116
495
      Identifier Id;
5117
495
      parseSILIdentifier(Id, diag::expected_in_attribute_list);
5118
495
      StringRef Optional = Id.str();
5119
495
      if (Optional == "objc") {
5120
27
        IsObjC = true;
5121
468
      } else if (Optional == "stack") {
5122
258
        OnStack = true;
5123
258
      } else if (Optional == "bare" && Opcode == SILInstructionKind::AllocRefInst) {
5124
12
        isBare = true;
5125
198
      } else if (Optional == "tail_elems") {
5126
198
        SILType ElemTy;
5127
198
        if (parseSILType(ElemTy) || !P.Tok.isAnyOperator() ||
5128
198
            P.Tok.getText() != "*")
5129
0
          return true;
5130
198
        P.consumeToken();
5131
5132
198
        SILValue ElemCount;
5133
198
        if (parseTypedValueRef(ElemCount, B))
5134
0
          return true;
5135
5136
198
        ElementTypes.push_back(ElemTy);
5137
198
        ElementCounts.push_back(ElemCount);
5138
198
      } else {
5139
0
        return true;
5140
0
      }
5141
495
      P.parseToken(tok::r_square, diag::expected_in_attribute_list);
5142
495
    }
5143
2.50k
    SILValue Metadata;
5144
2.50k
    if (Opcode == SILInstructionKind::AllocRefDynamicInst) {
5145
147
      if (parseTypedValueRef(Metadata, B) ||
5146
147
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
5147
0
        return true;
5148
147
    }
5149
5150
2.50k
    SILType ObjectType;
5151
2.50k
    if (parseSILType(ObjectType))
5152
0
      return true;
5153
5154
2.50k
    if (parseSILDebugLocation(InstLoc, B))
5155
0
      return true;
5156
5157
2.50k
    if (IsObjC && !ElementTypes.empty()) {
5158
0
      P.diagnose(P.Tok, diag::sil_objc_with_tail_elements);
5159
0
      return true;
5160
0
    }
5161
2.50k
    if (Opcode == SILInstructionKind::AllocRefDynamicInst) {
5162
147
      ResultVal = B.createAllocRefDynamic(InstLoc, Metadata, ObjectType, IsObjC,
5163
147
                                          OnStack,
5164
147
                                          ElementTypes, ElementCounts);
5165
2.35k
    } else {
5166
2.35k
      ResultVal = B.createAllocRef(InstLoc, ObjectType, IsObjC, OnStack, isBare,
5167
2.35k
                                   ElementTypes, ElementCounts);
5168
2.35k
    }
5169
2.50k
    break;
5170
2.50k
  }
5171
5172
12.1k
  case SILInstructionKind::DeallocStackInst:
5173
12.1k
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5174
0
      return true;
5175
12.1k
    ResultVal = B.createDeallocStack(InstLoc, Val);
5176
12.1k
    break;
5177
285
  case SILInstructionKind::DeallocStackRefInst:
5178
285
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5179
0
      return true;
5180
285
    ResultVal = B.createDeallocStackRef(InstLoc, Val);
5181
285
    break;
5182
30
  case SILInstructionKind::DeallocPackInst:
5183
30
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5184
0
      return true;
5185
30
    ResultVal = B.createDeallocPack(InstLoc, Val);
5186
30
    break;
5187
12
  case SILInstructionKind::DeallocPackMetadataInst:
5188
12
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5189
0
      return true;
5190
12
    ResultVal = B.createDeallocPackMetadata(InstLoc, Val);
5191
12
    break;
5192
462
  case SILInstructionKind::DeallocRefInst: {
5193
462
    if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5194
0
      return true;
5195
462
    ResultVal = B.createDeallocRef(InstLoc, Val);
5196
462
    break;
5197
462
  }
5198
42
  case SILInstructionKind::DeallocPartialRefInst: {
5199
42
    SILValue Metatype, Instance;
5200
42
    if (parseTypedValueRef(Instance, B) ||
5201
42
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5202
42
        parseTypedValueRef(Metatype, B) || parseSILDebugLocation(InstLoc, B))
5203
0
      return true;
5204
5205
42
    ResultVal = B.createDeallocPartialRef(InstLoc, Instance, Metatype);
5206
42
    break;
5207
42
  }
5208
114
    case SILInstructionKind::DeallocBoxInst:
5209
114
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5210
0
        return true;
5211
5212
114
      ResultVal = B.createDeallocBox(InstLoc, Val);
5213
114
      break;
5214
114
    case SILInstructionKind::ValueMetatypeInst:
5215
225
    case SILInstructionKind::ExistentialMetatypeInst: {
5216
225
      SILType Ty;
5217
225
      if (parseSILType(Ty) ||
5218
225
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5219
225
          parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5220
0
        return true;
5221
225
      switch (Opcode) {
5222
0
      default:
5223
0
        llvm_unreachable("Out of sync with parent switch");
5224
114
      case SILInstructionKind::ValueMetatypeInst:
5225
114
        ResultVal = B.createValueMetatype(InstLoc, Ty, Val);
5226
114
        break;
5227
111
      case SILInstructionKind::ExistentialMetatypeInst:
5228
111
        ResultVal = B.createExistentialMetatype(InstLoc, Ty, Val);
5229
111
        break;
5230
0
      case SILInstructionKind::DeallocBoxInst:
5231
0
        ResultVal = B.createDeallocBox(InstLoc, Val);
5232
0
        break;
5233
225
      }
5234
225
      break;
5235
225
    }
5236
225
    case SILInstructionKind::DeallocExistentialBoxInst: {
5237
24
      CanType ConcreteTy;
5238
24
      if (parseTypedValueRef(Val, B) ||
5239
24
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5240
24
          P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
5241
24
          parseASTType(ConcreteTy) || parseSILDebugLocation(InstLoc, B))
5242
0
        return true;
5243
5244
24
      ResultVal = B.createDeallocExistentialBox(InstLoc, ConcreteTy, Val);
5245
24
      break;
5246
24
    }
5247
25.0k
    case SILInstructionKind::TupleInst: {
5248
      // Tuple instructions have two different syntaxes, one for simple tuple
5249
      // types, one for complicated ones.
5250
25.0k
      if (P.Tok.isNot(tok::sil_dollar)) {
5251
        // If there is no type, parse the simple form.
5252
24.9k
        if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
5253
0
          return true;
5254
5255
        // TODO: Check for a type here.  This is how tuples with "interesting"
5256
        // types are described.
5257
5258
        // This form is used with tuples that have elements with no names or
5259
        // default values.
5260
24.9k
        SmallVector<TupleTypeElt, 4> TypeElts;
5261
24.9k
        if (P.Tok.isNot(tok::r_paren)) {
5262
3.65k
          do {
5263
3.65k
            if (parseTypedValueRef(Val, B))
5264
0
              return true;
5265
3.65k
            OpList.push_back(Val);
5266
3.65k
            TypeElts.push_back(Val->getType().getRawASTType());
5267
3.65k
          } while (P.consumeIf(tok::comma));
5268
1.64k
        }
5269
24.9k
        HadError |=
5270
24.9k
            P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")");
5271
5272
24.9k
        auto Ty = TupleType::get(TypeElts, P.Context);
5273
24.9k
        auto Ty2 = SILType::getPrimitiveObjectType(Ty->getCanonicalType());
5274
5275
24.9k
        ValueOwnershipKind forwardingOwnership =
5276
24.9k
            F && F->hasOwnership() ? mergeSILValueOwnership(OpList)
5277
24.9k
                                   : ValueOwnershipKind(OwnershipKind::None);
5278
5279
24.9k
        if (parseForwardingOwnershipKind(forwardingOwnership)
5280
24.9k
            || parseSILDebugLocation(InstLoc, B))
5281
0
          return true;
5282
5283
24.9k
        ResultVal = B.createTuple(InstLoc, Ty2, OpList, forwardingOwnership);
5284
24.9k
        break;
5285
24.9k
      }
5286
5287
      // Otherwise, parse the fully general form.
5288
54
      SILType Ty;
5289
54
      if (parseSILType(Ty) ||
5290
54
          P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
5291
0
        return true;
5292
5293
54
      TupleType *TT = Ty.getAs<TupleType>();
5294
54
      if (TT == nullptr) {
5295
0
        P.diagnose(OpcodeLoc, diag::expected_tuple_type_in_tuple);
5296
0
        return true;
5297
0
      }
5298
5299
54
      SmallVector<TupleTypeElt, 4> TypeElts;
5300
54
      if (P.Tok.isNot(tok::r_paren)) {
5301
72
        do {
5302
72
          if (TypeElts.size() > TT->getNumElements()) {
5303
0
            P.diagnose(P.Tok, diag::sil_tuple_inst_wrong_value_count,
5304
0
                       TT->getNumElements());
5305
0
            return true;
5306
0
          }
5307
72
          Type EltTy = TT->getElement(TypeElts.size()).getType();
5308
72
          if (parseValueRef(
5309
72
                  Val,
5310
72
                  SILType::getPrimitiveObjectType(EltTy->getCanonicalType()),
5311
72
                  RegularLocation(P.Tok.getLoc()), B))
5312
0
            return true;
5313
72
          OpList.push_back(Val);
5314
72
          TypeElts.push_back(Val->getType().getRawASTType());
5315
72
        } while (P.consumeIf(tok::comma));
5316
54
      }
5317
54
      HadError |= P.parseToken(tok::r_paren,
5318
54
                               diag::expected_tok_in_sil_instr,")");
5319
5320
54
      if (TypeElts.size() != TT->getNumElements()) {
5321
0
        P.diagnose(OpcodeLoc, diag::sil_tuple_inst_wrong_value_count,
5322
0
                   TT->getNumElements());
5323
0
        return true;
5324
0
      }
5325
5326
54
      if (parseSILDebugLocation(InstLoc, B))
5327
0
        return true;
5328
54
      ResultVal = B.createTuple(InstLoc, Ty, OpList);
5329
54
      break;
5330
54
    }
5331
96
    case SILInstructionKind::TupleAddrConstructorInst: {
5332
      // First parse [init] or [assign].
5333
96
      StringRef InitOrAssign;
5334
96
      SILValue DestValue;
5335
96
      SourceLoc WithLoc, DestToken;
5336
96
      Identifier WithToken;
5337
5338
96
      if (!parseSILOptional(InitOrAssign, *this) ||
5339
96
          parseTypedValueRef(DestValue, DestToken, B) ||
5340
96
          parseSILIdentifier(WithToken, WithLoc,
5341
96
                             diag::expected_tok_in_sil_instr, "with"))
5342
0
        return true;
5343
5344
96
      auto IsInit =
5345
96
          llvm::StringSwitch<std::optional<IsInitialization_t>>(InitOrAssign)
5346
96
              .Case("init", IsInitialization_t::IsInitialization)
5347
96
              .Case("assign", IsInitialization_t::IsNotInitialization)
5348
96
              .Default({});
5349
96
      if (!IsInit) {
5350
0
        P.diagnose(WithLoc, diag::expected_tok_in_sil_instr,
5351
0
                   "[init] | [assign]");
5352
0
        return true;
5353
0
      }
5354
5355
96
      if (WithToken.str() != "with") {
5356
0
        P.diagnose(WithLoc, diag::expected_tok_in_sil_instr, "with");
5357
0
        return true;
5358
0
      }
5359
5360
      // If there is no type, parse the simple form.
5361
96
      if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "(")) {
5362
0
        P.diagnose(WithLoc, diag::expected_tok_in_sil_instr, "(");
5363
0
        return true;
5364
0
      }
5365
5366
      // Then parse our tuple element list.
5367
96
      SmallVector<TupleTypeElt, 4> TypeElts;
5368
96
      if (P.Tok.isNot(tok::r_paren)) {
5369
204
        do {
5370
204
          if (parseTypedValueRef(Val, B))
5371
0
            return true;
5372
204
          OpList.push_back(Val);
5373
204
          TypeElts.push_back(Val->getType().getRawASTType());
5374
204
        } while (P.consumeIf(tok::comma));
5375
96
      }
5376
5377
96
      if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")")) {
5378
0
        P.diagnose(WithLoc, diag::expected_tok_in_sil_instr, ")");
5379
0
        return true;
5380
0
      }
5381
5382
96
      if (parseSILDebugLocation(InstLoc, B))
5383
0
        return true;
5384
5385
96
      ResultVal =
5386
96
          B.createTupleAddrConstructor(InstLoc, DestValue, OpList, *IsInit);
5387
96
      break;
5388
96
    }
5389
3.01k
    case SILInstructionKind::EnumInst: {
5390
3.01k
      SILType Ty;
5391
3.01k
      SILDeclRef Elt;
5392
3.01k
      SILValue Operand;
5393
3.01k
      if (parseSILType(Ty) ||
5394
3.01k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5395
3.01k
          parseSILDeclRef(Elt))
5396
0
        return true;
5397
5398
3.01k
      if (P.Tok.is(tok::comma) && !peekSILDebugLocation(P)) {
5399
1.76k
        P.consumeToken(tok::comma);
5400
1.76k
        if (parseTypedValueRef(Operand, B))
5401
0
          return true;
5402
1.76k
      }
5403
5404
3.01k
      if (parseSILDebugLocation(InstLoc, B))
5405
0
        return true;
5406
5407
3.01k
      ValueOwnershipKind forwardingOwnership =
5408
3.01k
          Operand ? Operand->getOwnershipKind()
5409
3.01k
                  : ValueOwnershipKind(OwnershipKind::None);
5410
5411
3.01k
      if (parseForwardingOwnershipKind(forwardingOwnership)
5412
3.01k
          || parseSILDebugLocation(InstLoc, B))
5413
0
        return true;
5414
5415
3.01k
      ResultVal =
5416
3.01k
          B.createEnum(InstLoc, Operand, cast<EnumElementDecl>(Elt.getDecl()),
5417
3.01k
                       Ty, forwardingOwnership);
5418
3.01k
      break;
5419
3.01k
    }
5420
438
    case SILInstructionKind::InitEnumDataAddrInst:
5421
1.01k
    case SILInstructionKind::UncheckedEnumDataInst:
5422
1.34k
    case SILInstructionKind::UncheckedTakeEnumDataAddrInst: {
5423
1.34k
      SILValue Operand;
5424
1.34k
      SILDeclRef EltRef;
5425
1.34k
      if (parseTypedValueRef(Operand, B) ||
5426
1.34k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5427
1.34k
          parseSILDeclRef(EltRef))
5428
0
        return true;
5429
5430
1.34k
      ValueOwnershipKind forwardingOwnership = Operand->getOwnershipKind();
5431
1.34k
      if (Opcode == SILInstructionKind::UncheckedEnumDataInst)
5432
579
        parseForwardingOwnershipKind(forwardingOwnership);
5433
5434
1.34k
      if (parseSILDebugLocation(InstLoc, B))
5435
0
        return true;
5436
1.34k
      EnumElementDecl *Elt = cast<EnumElementDecl>(EltRef.getDecl());
5437
1.34k
      auto ResultTy = Operand->getType().getEnumElementType(
5438
1.34k
          Elt, SILMod, B.getTypeExpansionContext());
5439
5440
1.34k
      switch (Opcode) {
5441
438
      case swift::SILInstructionKind::InitEnumDataAddrInst:
5442
438
        ResultVal = B.createInitEnumDataAddr(InstLoc, Operand, Elt, ResultTy);
5443
438
        break;
5444
327
      case swift::SILInstructionKind::UncheckedTakeEnumDataAddrInst:
5445
327
        ResultVal =
5446
327
            B.createUncheckedTakeEnumDataAddr(InstLoc, Operand, Elt, ResultTy);
5447
327
        break;
5448
579
      case swift::SILInstructionKind::UncheckedEnumDataInst: {
5449
579
        ResultVal = B.createUncheckedEnumData(InstLoc, Operand, Elt, ResultTy,
5450
579
                                              forwardingOwnership);
5451
579
        break;
5452
0
      }
5453
0
      default:
5454
0
        llvm_unreachable("switch out of sync");
5455
1.34k
      }
5456
1.34k
      break;
5457
1.34k
    }
5458
1.34k
    case SILInstructionKind::InjectEnumAddrInst: {
5459
636
      SILValue Operand;
5460
636
      SILDeclRef EltRef;
5461
636
      if (parseTypedValueRef(Operand, B) ||
5462
636
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5463
636
          parseSILDeclRef(EltRef) || parseSILDebugLocation(InstLoc, B))
5464
0
        return true;
5465
5466
636
      EnumElementDecl *Elt = cast<EnumElementDecl>(EltRef.getDecl());
5467
636
      ResultVal = B.createInjectEnumAddr(InstLoc, Operand, Elt);
5468
636
      break;
5469
636
    }
5470
1.12k
    case SILInstructionKind::TupleElementAddrInst:
5471
4.99k
    case SILInstructionKind::TupleExtractInst: {
5472
4.99k
      SourceLoc NameLoc;
5473
4.99k
      if (parseTypedValueRef(Val, B) ||
5474
4.99k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
5475
0
        return true;
5476
5477
4.99k
      unsigned Field = 0;
5478
4.99k
      TupleType *TT = Val->getType().castTo<TupleType>();
5479
4.99k
      if (P.Tok.isNot(tok::integer_literal) ||
5480
4.99k
          parseIntegerLiteral(P.Tok.getText(), 10, Field) ||
5481
4.99k
          Field >= TT->getNumElements()) {
5482
0
        P.diagnose(P.Tok, diag::sil_tuple_inst_wrong_field);
5483
0
        return true;
5484
0
      }
5485
4.99k
      P.consumeToken(tok::integer_literal);
5486
4.99k
      ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
5487
5488
4.99k
      if (Opcode == SILInstructionKind::TupleExtractInst) {
5489
3.87k
        if (parseForwardingOwnershipKind(forwardingOwnership))
5490
0
          return true;
5491
3.87k
      }
5492
5493
4.99k
      if (parseSILDebugLocation(InstLoc, B))
5494
0
        return true;
5495
4.99k
      auto ResultTy = TT->getElement(Field).getType()->getCanonicalType();
5496
4.99k
      if (Opcode == SILInstructionKind::TupleElementAddrInst)
5497
1.12k
        ResultVal = B.createTupleElementAddr(
5498
1.12k
            InstLoc, Val, Field, SILType::getPrimitiveAddressType(ResultTy));
5499
3.87k
      else {
5500
3.87k
        ResultVal = B.createTupleExtract(
5501
3.87k
            InstLoc, Val, Field, SILType::getPrimitiveObjectType(ResultTy),
5502
3.87k
            forwardingOwnership);
5503
3.87k
      }
5504
4.99k
      break;
5505
4.99k
    }
5506
42.0k
    case SILInstructionKind::ReturnInst: {
5507
42.0k
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5508
0
        return true;
5509
42.0k
      ResultVal = B.createReturn(InstLoc, Val);
5510
42.0k
      break;
5511
42.0k
    }
5512
576
    case SILInstructionKind::ThrowInst: {
5513
576
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
5514
0
        return true;
5515
576
      ResultVal = B.createThrow(InstLoc, Val);
5516
576
      break;
5517
576
    }
5518
6
    case SILInstructionKind::ThrowAddrInst: {
5519
6
      if (parseSILDebugLocation(InstLoc, B))
5520
0
        return true;
5521
6
      ResultVal = B.createThrowAddr(InstLoc);
5522
6
      break;
5523
6
    }
5524
331
    case SILInstructionKind::UnwindInst: {
5525
331
      if (parseSILDebugLocation(InstLoc, B))
5526
0
        return true;
5527
331
      ResultVal = B.createUnwind(InstLoc);
5528
331
      break;
5529
331
    }
5530
343
    case SILInstructionKind::YieldInst: {
5531
343
      SmallVector<SILValue, 6> values;
5532
5533
      // Parse a parenthesized (unless length-1), comma-separated list
5534
      // of yielded values.
5535
343
      if (P.consumeIf(tok::l_paren)) {
5536
39
        if (!P.Tok.is(tok::r_paren)) {
5537
54
          do {
5538
54
            if (parseTypedValueRef(Val, B))
5539
0
              return true;
5540
54
            values.push_back(Val);
5541
54
          } while (P.consumeIf(tok::comma));
5542
27
        }
5543
5544
39
        if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")"))
5545
0
          return true;
5546
5547
304
      } else {
5548
304
        if (parseTypedValueRef(Val, B))
5549
0
          return true;
5550
304
        values.push_back(Val);
5551
304
      }
5552
5553
343
      Identifier resumeName, unwindName;
5554
343
      SourceLoc resumeLoc, unwindLoc;
5555
343
      if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5556
343
          parseVerbatim("resume") ||
5557
343
          parseSILIdentifier(resumeName, resumeLoc,
5558
343
                             diag::expected_sil_block_name) ||
5559
343
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5560
343
          parseVerbatim("unwind") ||
5561
343
          parseSILIdentifier(unwindName, unwindLoc,
5562
343
                             diag::expected_sil_block_name) ||
5563
343
          parseSILDebugLocation(InstLoc, B))
5564
0
        return true;
5565
5566
343
      auto resumeBB = getBBForReference(resumeName, resumeLoc);
5567
343
      auto unwindBB = getBBForReference(unwindName, unwindLoc);
5568
343
      ResultVal = B.createYield(InstLoc, values, resumeBB, unwindBB);
5569
343
      break;
5570
343
    }
5571
177k
    case SILInstructionKind::BranchInst: {
5572
177k
      Identifier BBName;
5573
177k
      SourceLoc NameLoc;
5574
177k
      if (parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name))
5575
0
        return true;
5576
5577
177k
      SmallVector<SILValue, 6> Args;
5578
177k
      if (parseSILBBArgsAtBranch(Args, B))
5579
3
        return true;
5580
5581
177k
      if (parseSILDebugLocation(InstLoc, B))
5582
0
        return true;
5583
5584
      // Note, the basic block here could be a reference to an undefined
5585
      // basic block, which will be parsed later on.
5586
177k
      ResultVal =
5587
177k
          B.createBranch(InstLoc, getBBForReference(BBName, NameLoc), Args);
5588
177k
      break;
5589
177k
    }
5590
10.0k
    case SILInstructionKind::CondBranchInst: {
5591
10.0k
      UnresolvedValueName Cond;
5592
10.0k
      Identifier BBName, BBName2;
5593
10.0k
      SourceLoc NameLoc, NameLoc2;
5594
10.0k
      SmallVector<SILValue, 6> Args, Args2;
5595
10.0k
      if (parseValueName(Cond) ||
5596
10.0k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5597
10.0k
          parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name) ||
5598
10.0k
          parseSILBBArgsAtBranch(Args, B) ||
5599
10.0k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5600
10.0k
          parseSILIdentifier(BBName2, NameLoc2,
5601
10.0k
                             diag::expected_sil_block_name) ||
5602
10.0k
          parseSILBBArgsAtBranch(Args2, B) || parseSILDebugLocation(InstLoc, B))
5603
0
        return true;
5604
5605
10.0k
      auto I1Ty = SILType::getBuiltinIntegerType(1, SILMod.getASTContext());
5606
10.0k
      SILValue CondVal = getLocalValue(Cond, I1Ty, InstLoc, B);
5607
10.0k
      ResultVal = B.createCondBranch(
5608
10.0k
          InstLoc, CondVal, getBBForReference(BBName, NameLoc), Args,
5609
10.0k
          getBBForReference(BBName2, NameLoc2), Args2);
5610
10.0k
      break;
5611
10.0k
    }
5612
2.25k
    case SILInstructionKind::UnreachableInst:
5613
2.25k
      if (parseSILDebugLocation(InstLoc, B))
5614
0
        return true;
5615
2.25k
      ResultVal = B.createUnreachable(InstLoc);
5616
2.25k
      break;
5617
5618
962
    case SILInstructionKind::ClassMethodInst:
5619
989
    case SILInstructionKind::SuperMethodInst:
5620
1.22k
    case SILInstructionKind::ObjCMethodInst:
5621
1.23k
    case SILInstructionKind::ObjCSuperMethodInst: {
5622
1.23k
      SILDeclRef Member;
5623
1.23k
      SILType MethodTy;
5624
1.23k
      SourceLoc TyLoc;
5625
1.23k
      if (parseTypedValueRef(Val, B) ||
5626
1.23k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
5627
0
        return true;
5628
5629
1.23k
      if (parseSILDeclRef(Member, true))
5630
0
        return true;
5631
5632
1.23k
      if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5633
1.23k
          parseSILType(MethodTy, TyLoc) || parseSILDebugLocation(InstLoc, B))
5634
0
        return true;
5635
5636
1.23k
      switch (Opcode) {
5637
0
      default:
5638
0
        llvm_unreachable("Out of sync with parent switch");
5639
962
      case SILInstructionKind::ClassMethodInst:
5640
962
        ResultVal = B.createClassMethod(InstLoc, Val, Member, MethodTy);
5641
962
        break;
5642
27
      case SILInstructionKind::SuperMethodInst:
5643
27
        ResultVal = B.createSuperMethod(InstLoc, Val, Member, MethodTy);
5644
27
        break;
5645
234
      case SILInstructionKind::ObjCMethodInst:
5646
234
        ResultVal = B.createObjCMethod(InstLoc, Val, Member, MethodTy);
5647
234
        break;
5648
15
      case SILInstructionKind::ObjCSuperMethodInst:
5649
15
        ResultVal = B.createObjCSuperMethod(InstLoc, Val, Member, MethodTy);
5650
15
        break;
5651
1.23k
      }
5652
1.23k
      break;
5653
1.23k
    }
5654
1.23k
    case SILInstructionKind::WitnessMethodInst: {
5655
1.13k
      CanType LookupTy;
5656
1.13k
      SILDeclRef Member;
5657
1.13k
      SILType MethodTy;
5658
1.13k
      SourceLoc TyLoc;
5659
1.13k
      if (P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
5660
1.13k
          parseASTType(LookupTy) ||
5661
1.13k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ","))
5662
0
        return true;
5663
1.13k
      if (parseSILDeclRef(Member, true))
5664
0
        return true;
5665
      // Optional operand.
5666
1.13k
      SILValue Operand;
5667
1.13k
      if (P.Tok.is(tok::comma)) {
5668
474
        P.consumeToken(tok::comma);
5669
474
        if (parseTypedValueRef(Operand, B))
5670
0
          return true;
5671
474
      }
5672
1.13k
      if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
5673
1.13k
          parseSILType(MethodTy, TyLoc) || parseSILDebugLocation(InstLoc, B))
5674
0
        return true;
5675
5676
      // If LookupTy is a non-archetype, look up its conformance.
5677
1.13k
      ProtocolDecl *proto =
5678
1.13k
          dyn_cast<ProtocolDecl>(Member.getDecl()->getDeclContext());
5679
1.13k
      if (!proto) {
5680
0
        P.diagnose(TyLoc, diag::sil_witness_method_not_protocol);
5681
0
        return true;
5682
0
      }
5683
1.13k
      auto conformance =
5684
1.13k
          P.SF.getParentModule()->lookupConformance(LookupTy, proto);
5685
1.13k
      if (conformance.isInvalid()) {
5686
0
        P.diagnose(TyLoc, diag::sil_witness_method_type_does_not_conform);
5687
0
        return true;
5688
0
      }
5689
5690
1.13k
      ResultVal = B.createWitnessMethod(InstLoc, LookupTy, conformance, Member,
5691
1.13k
                                        MethodTy);
5692
1.13k
      break;
5693
1.13k
    }
5694
3.25k
    case SILInstructionKind::CopyAddrInst: {
5695
3.25k
      bool IsTake = false, IsInit = false;
5696
3.25k
      UnresolvedValueName SrcLName;
5697
3.25k
      SILValue DestLVal;
5698
3.25k
      SourceLoc ToLoc, DestLoc;
5699
3.25k
      Identifier ToToken;
5700
3.25k
      if (parseSILOptional(IsTake, *this, "take") || parseValueName(SrcLName) ||
5701
3.25k
          parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
5702
3.25k
                             "to") ||
5703
3.25k
          parseSILOptional(IsInit, *this, "init") ||
5704
3.25k
          parseTypedValueRef(DestLVal, DestLoc, B) ||
5705
3.25k
          parseSILDebugLocation(InstLoc, B))
5706
0
        return true;
5707
5708
3.25k
      if (ToToken.str() != "to") {
5709
0
        P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
5710
0
        return true;
5711
0
      }
5712
5713
3.25k
      if (!DestLVal->getType().isAddress()) {
5714
0
        P.diagnose(DestLoc, diag::sil_invalid_instr_operands);
5715
0
        return true;
5716
0
      }
5717
5718
3.25k
      SILValue SrcLVal =
5719
3.25k
          getLocalValue(SrcLName, DestLVal->getType(), InstLoc, B);
5720
3.25k
      ResultVal = B.createCopyAddr(InstLoc, SrcLVal, DestLVal, IsTake_t(IsTake),
5721
3.25k
                                   IsInitialization_t(IsInit));
5722
3.25k
      break;
5723
3.25k
    }
5724
54
    case SILInstructionKind::ExplicitCopyAddrInst: {
5725
54
      bool IsTake = false, IsInit = false;
5726
54
      UnresolvedValueName SrcLName;
5727
54
      SILValue DestLVal;
5728
54
      SourceLoc ToLoc, DestLoc;
5729
54
      Identifier ToToken;
5730
54
      if (parseSILOptional(IsTake, *this, "take") || parseValueName(SrcLName) ||
5731
54
          parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
5732
54
                             "to") ||
5733
54
          parseSILOptional(IsInit, *this, "init") ||
5734
54
          parseTypedValueRef(DestLVal, DestLoc, B) ||
5735
54
          parseSILDebugLocation(InstLoc, B))
5736
0
        return true;
5737
5738
54
      if (ToToken.str() != "to") {
5739
0
        P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
5740
0
        return true;
5741
0
      }
5742
5743
54
      if (!DestLVal->getType().isAddress()) {
5744
0
        P.diagnose(DestLoc, diag::sil_invalid_instr_operands);
5745
0
        return true;
5746
0
      }
5747
5748
54
      SILValue SrcLVal =
5749
54
          getLocalValue(SrcLName, DestLVal->getType(), InstLoc, B);
5750
54
      ResultVal =
5751
54
          B.createExplicitCopyAddr(InstLoc, SrcLVal, DestLVal, IsTake_t(IsTake),
5752
54
                                   IsInitialization_t(IsInit));
5753
54
      break;
5754
54
    }
5755
12
    case SILInstructionKind::MarkUnresolvedMoveAddrInst: {
5756
12
      UnresolvedValueName SrcLName;
5757
12
      SILValue DestLVal;
5758
12
      SourceLoc ToLoc, DestLoc;
5759
12
      Identifier ToToken;
5760
12
      if (parseValueName(SrcLName) ||
5761
12
          parseSILIdentifier(ToToken, ToLoc, diag::expected_tok_in_sil_instr,
5762
12
                             "to") ||
5763
12
          parseTypedValueRef(DestLVal, DestLoc, B) ||
5764
12
          parseSILDebugLocation(InstLoc, B))
5765
0
        return true;
5766
5767
12
      if (ToToken.str() != "to") {
5768
0
        P.diagnose(ToLoc, diag::expected_tok_in_sil_instr, "to");
5769
0
        return true;
5770
0
      }
5771
5772
12
      if (!DestLVal->getType().isAddress()) {
5773
0
        P.diagnose(DestLoc, diag::sil_invalid_instr_operands);
5774
0
        return true;
5775
0
      }
5776
5777
12
      SILValue SrcLVal =
5778
12
          getLocalValue(SrcLName, DestLVal->getType(), InstLoc, B);
5779
12
      ResultVal = B.createMarkUnresolvedMoveAddr(InstLoc, SrcLVal, DestLVal);
5780
12
      break;
5781
12
    }
5782
5783
54
    case SILInstructionKind::BindMemoryInst: {
5784
54
      SILValue IndexVal;
5785
54
      SILType EltTy;
5786
54
      if (parseTypedValueRef(Val, B)
5787
54
          || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")
5788
54
          || parseTypedValueRef(IndexVal, B)
5789
54
          || parseVerbatim("to")
5790
54
          || parseSILType(EltTy)
5791
54
          || parseSILDebugLocation(InstLoc, B))
5792
0
        return true;
5793
5794
54
      ResultVal = B.createBindMemory(InstLoc, Val, IndexVal, EltTy);
5795
54
      break;
5796
54
    }
5797
21
    case SILInstructionKind::RebindMemoryInst: {
5798
21
      SILValue InToken;
5799
21
      if (parseTypedValueRef(Val, B)
5800
21
          || parseVerbatim("to")
5801
21
          || parseTypedValueRef(InToken, B)
5802
21
          || parseSILDebugLocation(InstLoc, B))
5803
0
        return true;
5804
5805
21
      ResultVal = B.createRebindMemory(InstLoc, Val, InToken);
5806
21
      break;
5807
21
    }
5808
27
    case SILInstructionKind::ObjectInst:
5809
10.4k
    case SILInstructionKind::StructInst: {
5810
10.4k
      SILType Ty;
5811
10.4k
      if (parseSILType(Ty) ||
5812
10.4k
          P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
5813
0
        return true;
5814
5815
      // Parse a list of SILValue.
5816
10.4k
      bool OpsAreTailElems = false;
5817
10.4k
      unsigned NumBaseElems = 0;
5818
10.4k
      if (P.Tok.isNot(tok::r_paren)) {
5819
12.7k
        do {
5820
12.7k
          if (Opcode == SILInstructionKind::ObjectInst) {
5821
60
            if (parseSILOptional(OpsAreTailElems, *this, "tail_elems"))
5822
0
              return true;
5823
60
          }
5824
12.7k
          if (parseTypedValueRef(Val, B))
5825
0
            return true;
5826
12.7k
          OpList.push_back(Val);
5827
12.7k
          if (!OpsAreTailElems)
5828
12.7k
            NumBaseElems = OpList.size();
5829
12.7k
        } while (P.consumeIf(tok::comma));
5830
10.3k
      }
5831
10.4k
      if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")"))
5832
0
        return true;
5833
5834
10.4k
      ValueOwnershipKind forwardingOwnership =
5835
10.4k
          F && F->hasOwnership() ? mergeSILValueOwnership(OpList)
5836
10.4k
                                 : ValueOwnershipKind(OwnershipKind::None);
5837
10.4k
      if (parseForwardingOwnershipKind(forwardingOwnership)
5838
10.4k
          || parseSILDebugLocation(InstLoc, B)) {
5839
0
        return true;
5840
0
      }
5841
10.4k
      if (Opcode == SILInstructionKind::StructInst) {
5842
10.4k
        ResultVal = B.createStruct(InstLoc, Ty, OpList, forwardingOwnership);
5843
10.4k
      } else {
5844
27
        ResultVal = B.createObject(InstLoc, Ty, OpList, NumBaseElems,
5845
27
                                   forwardingOwnership);
5846
27
      }
5847
10.4k
      break;
5848
10.4k
    }
5849
4.64k
    case SILInstructionKind::StructElementAddrInst:
5850
11.6k
    case SILInstructionKind::StructExtractInst: {
5851
11.6k
      ValueDecl *FieldV;
5852
11.6k
      SourceLoc NameLoc = P.Tok.getLoc();
5853
11.6k
      if (parseTypedValueRef(Val, B) ||
5854
11.6k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5855
11.6k
          parseSILDottedPath(FieldV))
5856
3
        return true;
5857
5858
11.6k
      ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
5859
11.6k
      if (Opcode == SILInstructionKind::StructExtractInst) {
5860
6.99k
        if (parseForwardingOwnershipKind(forwardingOwnership))
5861
0
          return true;
5862
6.99k
      }
5863
5864
11.6k
      if (parseSILDebugLocation(InstLoc, B))
5865
0
        return true;
5866
11.6k
      if (!FieldV || !isa<VarDecl>(FieldV)) {
5867
0
        P.diagnose(NameLoc, diag::sil_struct_inst_wrong_field);
5868
0
        return true;
5869
0
      }
5870
11.6k
      VarDecl *Field = cast<VarDecl>(FieldV);
5871
5872
      // FIXME: substitution means this type should be explicit to improve
5873
      // performance.
5874
11.6k
      auto ResultTy = Val->getType().getFieldType(Field, SILMod,
5875
11.6k
                                                  B.getTypeExpansionContext());
5876
11.6k
      if (Opcode == SILInstructionKind::StructElementAddrInst)
5877
4.64k
        ResultVal = B.createStructElementAddr(InstLoc, Val, Field,
5878
4.64k
                                              ResultTy.getAddressType());
5879
6.99k
      else {
5880
6.99k
        ResultVal = B.createStructExtract(
5881
6.99k
            InstLoc, Val, Field, ResultTy.getObjectType(), forwardingOwnership);
5882
6.99k
      }
5883
11.6k
      break;
5884
11.6k
    }
5885
2.53k
    case SILInstructionKind::RefElementAddrInst: {
5886
2.53k
      ValueDecl *FieldV;
5887
2.53k
      SourceLoc NameLoc;
5888
2.53k
      bool IsImmutable = false;
5889
2.53k
      if (parseSILOptional(IsImmutable, *this, "immutable") ||
5890
2.53k
          parseTypedValueRef(Val, B) ||
5891
2.53k
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5892
2.53k
          parseSILDottedPath(FieldV) || parseSILDebugLocation(InstLoc, B))
5893
0
        return true;
5894
2.53k
      if (!FieldV || !isa<VarDecl>(FieldV)) {
5895
0
        P.diagnose(NameLoc, diag::sil_ref_inst_wrong_field);
5896
0
        return true;
5897
0
      }
5898
2.53k
      VarDecl *Field = cast<VarDecl>(FieldV);
5899
2.53k
      auto ResultTy = Val->getType().getFieldType(Field, SILMod,
5900
2.53k
                                                  B.getTypeExpansionContext());
5901
2.53k
      ResultVal = B.createRefElementAddr(InstLoc, Val, Field, ResultTy,
5902
2.53k
                                         IsImmutable);
5903
2.53k
      break;
5904
2.53k
    }
5905
417
    case SILInstructionKind::RefTailAddrInst: {
5906
417
      SourceLoc NameLoc;
5907
417
      SILType ResultObjTy;
5908
417
      bool IsImmutable = false;
5909
417
      if (parseSILOptional(IsImmutable, *this, "immutable") ||
5910
417
          parseTypedValueRef(Val, B) ||
5911
417
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5912
417
          parseSILType(ResultObjTy) || parseSILDebugLocation(InstLoc, B))
5913
0
        return true;
5914
417
      SILType ResultTy = ResultObjTy.getAddressType();
5915
417
      ResultVal = B.createRefTailAddr(InstLoc, Val, ResultTy, IsImmutable);
5916
417
      break;
5917
417
    }
5918
945
    case SILInstructionKind::IndexAddrInst: {
5919
945
      SILValue IndexVal;
5920
945
      bool needsStackProtection = false;
5921
945
      if (parseSILOptional(needsStackProtection, *this, "stack_protection") ||
5922
945
          parseTypedValueRef(Val, B) ||
5923
945
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5924
945
          parseTypedValueRef(IndexVal, B) || parseSILDebugLocation(InstLoc, B))
5925
0
        return true;
5926
945
      ResultVal = B.createIndexAddr(InstLoc, Val, IndexVal, needsStackProtection);
5927
945
      break;
5928
945
    }
5929
18
    case SILInstructionKind::TailAddrInst: {
5930
18
      SILValue IndexVal;
5931
18
      SILType ResultObjTy;
5932
18
      if (parseTypedValueRef(Val, B) ||
5933
18
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5934
18
          parseTypedValueRef(IndexVal, B) ||
5935
18
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5936
18
          parseSILType(ResultObjTy) || parseSILDebugLocation(InstLoc, B))
5937
0
        return true;
5938
18
      SILType ResultTy = ResultObjTy.getAddressType();
5939
18
      ResultVal = B.createTailAddr(InstLoc, Val, IndexVal, ResultTy);
5940
18
      break;
5941
18
    }
5942
165
    case SILInstructionKind::IndexRawPointerInst: {
5943
165
      SILValue IndexVal;
5944
165
      if (parseTypedValueRef(Val, B) ||
5945
165
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
5946
165
          parseTypedValueRef(IndexVal, B) || parseSILDebugLocation(InstLoc, B))
5947
0
        return true;
5948
165
      ResultVal = B.createIndexRawPointer(InstLoc, Val, IndexVal);
5949
165
      break;
5950
165
    }
5951
21
    case SILInstructionKind::ObjCProtocolInst: {
5952
21
      Identifier ProtocolName;
5953
21
      SILType Ty;
5954
21
      if (P.parseToken(tok::pound, diag::expected_sil_constant) ||
5955
21
          parseSILIdentifier(ProtocolName, diag::expected_sil_constant) ||
5956
21
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
5957
21
          parseSILType(Ty) || parseSILDebugLocation(InstLoc, B))
5958
0
        return true;
5959
      // Find the decl for the protocol name.
5960
21
      ValueDecl *VD;
5961
21
      SmallVector<ValueDecl *, 4> CurModuleResults;
5962
      // Perform a module level lookup on the first component of the
5963
      // fully-qualified name.
5964
21
      P.SF.getParentModule()->lookupValue(
5965
21
          ProtocolName, NLKind::UnqualifiedLookup, CurModuleResults);
5966
21
      assert(CurModuleResults.size() == 1);
5967
0
      VD = CurModuleResults[0];
5968
21
      ResultVal = B.createObjCProtocol(InstLoc, cast<ProtocolDecl>(VD), Ty);
5969
21
      break;
5970
21
    }
5971
150
    case SILInstructionKind::AllocGlobalInst: {
5972
150
      Identifier GlobalName;
5973
150
      SourceLoc IdLoc;
5974
150
      if (P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
5975
150
          parseSILIdentifier(GlobalName, IdLoc,
5976
150
                             diag::expected_sil_value_name) ||
5977
150
          parseSILDebugLocation(InstLoc, B))
5978
0
        return true;
5979
5980
      // Go through list of global variables in the SILModule.
5981
150
      SILGlobalVariable *global = SILMod.lookUpGlobalVariable(GlobalName.str());
5982
150
      if (!global) {
5983
0
        P.diagnose(IdLoc, diag::sil_global_variable_not_found, GlobalName);
5984
0
        return true;
5985
0
      }
5986
5987
150
      ResultVal = B.createAllocGlobal(InstLoc, global);
5988
150
      break;
5989
150
    }
5990
1.15k
    case SILInstructionKind::GlobalAddrInst:
5991
1.19k
    case SILInstructionKind::GlobalValueInst: {
5992
1.19k
      Identifier GlobalName;
5993
1.19k
      SourceLoc IdLoc;
5994
1.19k
      SILType Ty;
5995
1.19k
      bool isBare = false;
5996
1.19k
      if (P.consumeIf(tok::l_square)) {
5997
12
        Identifier Id;
5998
12
        parseSILIdentifier(Id, diag::expected_in_attribute_list);
5999
12
        StringRef Optional = Id.str();
6000
12
        if (Optional == "bare" && Opcode == SILInstructionKind::GlobalValueInst) {
6001
12
          isBare = true;
6002
12
        } else {
6003
0
          return true;
6004
0
        }
6005
12
        P.parseToken(tok::r_square, diag::expected_in_attribute_list);
6006
12
      }
6007
6008
1.19k
      if (P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
6009
1.19k
          parseSILIdentifier(GlobalName, IdLoc,
6010
1.19k
                             diag::expected_sil_value_name) ||
6011
1.19k
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
6012
1.19k
          parseSILType(Ty) || parseSILDebugLocation(InstLoc, B))
6013
0
        return true;
6014
6015
      // Go through list of global variables in the SILModule.
6016
1.19k
      SILGlobalVariable *global = SILMod.lookUpGlobalVariable(GlobalName.str());
6017
1.19k
      if (!global) {
6018
0
        P.diagnose(IdLoc, diag::sil_global_variable_not_found, GlobalName);
6019
0
        return true;
6020
0
      }
6021
6022
1.19k
      SILType expectedType = (Opcode == SILInstructionKind::GlobalAddrInst
6023
1.19k
                                  ? global->getLoweredType().getAddressType()
6024
1.19k
                                  : global->getLoweredType());
6025
1.19k
      if (expectedType != Ty) {
6026
0
        P.diagnose(IdLoc, diag::sil_value_use_type_mismatch, GlobalName.str(),
6027
0
                   global->getLoweredType().getRawASTType(),
6028
0
                   Ty.getRawASTType());
6029
0
        return true;
6030
0
      }
6031
6032
1.19k
      if (Opcode == SILInstructionKind::GlobalAddrInst) {
6033
1.15k
        ResultVal = B.createGlobalAddr(InstLoc, global);
6034
1.15k
      } else {
6035
42
        ResultVal = B.createGlobalValue(InstLoc, global, isBare);
6036
42
      }
6037
1.19k
      break;
6038
1.19k
    }
6039
9
    case SILInstructionKind::BaseAddrForOffsetInst: {
6040
9
      SILType Ty;
6041
9
      if (parseSILType(Ty))
6042
0
        return true;
6043
9
      if (parseSILDebugLocation(InstLoc, B))
6044
0
        return true;
6045
9
      ResultVal = B.createBaseAddrForOffset(InstLoc, Ty);
6046
9
      break;
6047
9
    }
6048
327
    case SILInstructionKind::SelectEnumInst:
6049
408
    case SILInstructionKind::SelectEnumAddrInst: {
6050
408
      if (parseTypedValueRef(Val, B))
6051
0
        return true;
6052
6053
408
      SmallVector<std::pair<EnumElementDecl *, UnresolvedValueName>, 4>
6054
408
          CaseValueNames;
6055
408
      llvm::Optional<UnresolvedValueName> DefaultValueName;
6056
1.10k
      while (P.consumeIf(tok::comma)) {
6057
873
        Identifier BBName;
6058
873
        SourceLoc BBLoc;
6059
        // Parse 'default' sil-value.
6060
873
        UnresolvedValueName tmp;
6061
873
        if (P.consumeIf(tok::kw_default)) {
6062
177
          if (parseValueName(tmp))
6063
0
            return true;
6064
177
          DefaultValueName = tmp;
6065
177
          break;
6066
177
        }
6067
6068
        // Parse 'case' sil-decl-ref ':' sil-value.
6069
696
        if (P.consumeIf(tok::kw_case)) {
6070
696
          SILDeclRef ElemRef;
6071
696
          if (parseSILDeclRef(ElemRef))
6072
0
            return true;
6073
696
          assert(ElemRef.hasDecl() && isa<EnumElementDecl>(ElemRef.getDecl()));
6074
0
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":");
6075
696
          parseValueName(tmp);
6076
696
          CaseValueNames.push_back(
6077
696
              std::make_pair(cast<EnumElementDecl>(ElemRef.getDecl()), tmp));
6078
696
          continue;
6079
696
        }
6080
6081
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default");
6082
0
        return true;
6083
696
      }
6084
6085
      // Parse the type of the result operands.
6086
408
      SILType ResultType;
6087
408
      if (P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
6088
408
          parseSILType(ResultType))
6089
0
        return true;
6090
6091
408
      ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
6092
408
      if (Opcode == SILInstructionKind::SelectEnumInst) {
6093
327
        if (parseForwardingOwnershipKind(forwardingOwnership))
6094
0
          return true;
6095
327
      }
6096
408
      if (parseSILDebugLocation(InstLoc, B))
6097
0
        return true;
6098
6099
      // Resolve the results.
6100
408
      SmallVector<std::pair<EnumElementDecl *, SILValue>, 4> CaseValues;
6101
408
      SILValue DefaultValue;
6102
408
      if (DefaultValueName)
6103
177
        DefaultValue = getLocalValue(*DefaultValueName, ResultType, InstLoc, B);
6104
408
      for (auto &caseName : CaseValueNames)
6105
696
        CaseValues.push_back(std::make_pair(
6106
696
            caseName.first,
6107
696
            getLocalValue(caseName.second, ResultType, InstLoc, B)));
6108
6109
408
      if (Opcode == SILInstructionKind::SelectEnumInst) {
6110
327
        ResultVal = B.createSelectEnum(InstLoc, Val, ResultType, DefaultValue,
6111
327
                                       CaseValues, llvm::None,
6112
327
                                       ProfileCounter());
6113
327
      } else
6114
81
        ResultVal = B.createSelectEnumAddr(InstLoc, Val, ResultType,
6115
81
                                           DefaultValue, CaseValues);
6116
408
      break;
6117
408
    }
6118
6119
1.87k
    case SILInstructionKind::SwitchEnumInst:
6120
2.07k
    case SILInstructionKind::SwitchEnumAddrInst: {
6121
2.07k
      if (parseTypedValueRef(Val, B))
6122
0
        return true;
6123
6124
2.07k
      SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 4> CaseBBs;
6125
2.07k
      SILBasicBlock *DefaultBB = nullptr;
6126
2.07k
      ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
6127
6.63k
      while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma)) {
6128
4.59k
        parsedComma = true;
6129
6130
4.59k
        Identifier BBName;
6131
4.59k
        SourceLoc BBLoc;
6132
        // Parse 'case' sil-decl-ref ':' sil-identifier.
6133
4.59k
        if (P.consumeIf(tok::kw_case)) {
6134
4.28k
          parsedComma = false;
6135
4.28k
          if (DefaultBB) {
6136
0
            P.diagnose(P.Tok, diag::case_after_default);
6137
0
            return true;
6138
0
          }
6139
4.28k
          SILDeclRef ElemRef;
6140
4.28k
          if (parseSILDeclRef(ElemRef))
6141
0
            return true;
6142
4.28k
          assert(ElemRef.hasDecl() && isa<EnumElementDecl>(ElemRef.getDecl()));
6143
0
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":");
6144
4.28k
          parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name);
6145
4.28k
          CaseBBs.push_back({cast<EnumElementDecl>(ElemRef.getDecl()),
6146
4.28k
                             getBBForReference(BBName, BBLoc)});
6147
4.28k
          continue;
6148
4.28k
        }
6149
6150
        // Parse 'default' sil-identifier.
6151
318
        if (P.consumeIf(tok::kw_default)) {
6152
279
          parsedComma = false;
6153
279
          parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name);
6154
279
          DefaultBB = getBBForReference(BBName, BBLoc);
6155
279
          continue;
6156
279
        }
6157
39
        break;
6158
318
      }
6159
2.07k
      if (Opcode == SILInstructionKind::SwitchEnumInst
6160
2.07k
          && parseForwardingOwnershipKind(forwardingOwnership)) {
6161
0
        return true;
6162
0
      }
6163
2.07k
      if (parseSILDebugLocation(InstLoc, B))
6164
0
        return true;
6165
6166
2.07k
      if (parsedComma || (CaseBBs.empty() && !DefaultBB)) {
6167
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default");
6168
0
        return true;
6169
0
      }
6170
6171
2.07k
      if (Opcode == SILInstructionKind::SwitchEnumInst) {
6172
1.87k
        ResultVal =
6173
1.87k
            B.createSwitchEnum(InstLoc, Val, DefaultBB, CaseBBs, llvm::None,
6174
1.87k
                               ProfileCounter(), forwardingOwnership);
6175
1.87k
      } else
6176
201
        ResultVal = B.createSwitchEnumAddr(InstLoc, Val, DefaultBB, CaseBBs);
6177
2.07k
      break;
6178
2.07k
    }
6179
87
    case SILInstructionKind::SwitchValueInst: {
6180
87
      if (parseTypedValueRef(Val, B))
6181
0
        return true;
6182
6183
87
      SmallVector<std::pair<SILValue, SILBasicBlock *>, 4> CaseBBs;
6184
87
      SILBasicBlock *DefaultBB = nullptr;
6185
222
      while (!peekSILDebugLocation(P) && P.consumeIf(tok::comma)) {
6186
168
        Identifier BBName;
6187
168
        SourceLoc BBLoc;
6188
168
        SILValue CaseVal;
6189
6190
        // Parse 'default' sil-identifier.
6191
168
        if (P.consumeIf(tok::kw_default)) {
6192
33
          parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name);
6193
33
          DefaultBB = getBBForReference(BBName, BBLoc);
6194
33
          break;
6195
33
        }
6196
6197
        // Parse 'case' value-ref ':' sil-identifier.
6198
135
        if (P.consumeIf(tok::kw_case)) {
6199
135
          if (parseValueRef(CaseVal, Val->getType(),
6200
135
                            RegularLocation(P.Tok.getLoc()), B)) {
6201
            // TODO: Issue a proper error message here
6202
0
            P.diagnose(P.Tok, diag::expected_tok_in_sil_instr,
6203
0
                       "reference to a value");
6204
0
            return true;
6205
0
          }
6206
6207
135
          auto intTy = Val->getType().getAs<BuiltinIntegerType>();
6208
135
          auto functionTy = Val->getType().getAs<SILFunctionType>();
6209
135
          if (!intTy && !functionTy) {
6210
0
            P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type);
6211
0
            return true;
6212
0
          }
6213
6214
135
          if (intTy) {
6215
            // If it is a switch on an integer type, check that all case values
6216
            // are integer literals or undef.
6217
117
            if (!isa<SILUndef>(CaseVal)) {
6218
111
              auto *IL = dyn_cast<IntegerLiteralInst>(CaseVal);
6219
111
              if (!IL) {
6220
0
                P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type);
6221
0
                return true;
6222
0
              }
6223
111
              APInt CaseValue = IL->getValue();
6224
6225
111
              if (CaseValue.getBitWidth() != intTy->getGreatestWidth())
6226
0
                CaseVal = B.createIntegerLiteral(
6227
0
                    IL->getLoc(), Val->getType(),
6228
0
                    CaseValue.zextOrTrunc(intTy->getGreatestWidth()));
6229
111
            }
6230
117
          }
6231
6232
135
          if (functionTy) {
6233
            // If it is a switch on a function type, check that all case values
6234
            // are function references or undef.
6235
18
            if (!isa<SILUndef>(CaseVal)) {
6236
12
              auto *FR = dyn_cast<FunctionRefInst>(CaseVal);
6237
12
              if (!FR) {
6238
0
                if (auto *CF = dyn_cast<ConvertFunctionInst>(CaseVal)) {
6239
0
                  FR = dyn_cast<FunctionRefInst>(CF->getOperand());
6240
0
                }
6241
0
              }
6242
12
              if (!FR) {
6243
0
                P.diagnose(P.Tok, diag::sil_integer_literal_not_integer_type);
6244
0
                return true;
6245
0
              }
6246
12
            }
6247
18
          }
6248
6249
135
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":");
6250
135
          parseSILIdentifier(BBName, BBLoc, diag::expected_sil_block_name);
6251
135
          CaseBBs.push_back({CaseVal, getBBForReference(BBName, BBLoc)});
6252
135
          continue;
6253
135
        }
6254
6255
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, "case or default");
6256
0
        return true;
6257
135
      }
6258
87
      if (parseSILDebugLocation(InstLoc, B))
6259
0
        return true;
6260
87
      ResultVal = B.createSwitchValue(InstLoc, Val, DefaultBB, CaseBBs);
6261
87
      break;
6262
87
    }
6263
30
    case SILInstructionKind::DeinitExistentialAddrInst: {
6264
30
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
6265
0
        return true;
6266
30
      ResultVal = B.createDeinitExistentialAddr(InstLoc, Val);
6267
30
      break;
6268
30
    }
6269
9
    case SILInstructionKind::DeinitExistentialValueInst: {
6270
9
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
6271
0
        return true;
6272
9
      ResultVal = B.createDeinitExistentialValue(InstLoc, Val);
6273
9
      break;
6274
9
    }
6275
486
    case SILInstructionKind::InitExistentialAddrInst: {
6276
486
      CanType Ty;
6277
486
      SourceLoc TyLoc;
6278
486
      if (parseTypedValueRef(Val, B) ||
6279
486
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6280
486
          P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
6281
486
          parseASTType(Ty, TyLoc) || parseSILDebugLocation(InstLoc, B))
6282
0
        return true;
6283
6284
      // Lower the type at the abstraction level of the existential.
6285
486
      auto archetype =
6286
486
          OpenedArchetypeType::get(Val->getType().getASTType(),
6287
486
                                   B.getFunction().getGenericSignature())
6288
486
              ->getCanonicalType();
6289
6290
486
      auto &F = B.getFunction();
6291
486
      SILType LoweredTy =
6292
486
          F.getLoweredType(Lowering::AbstractionPattern(archetype), Ty)
6293
486
              .getAddressType();
6294
6295
      // Collect conformances for the type.
6296
486
      ArrayRef<ProtocolConformanceRef> conformances =
6297
486
          collectExistentialConformances(P, Ty, TyLoc,
6298
486
                                         Val->getType().getASTType());
6299
6300
486
      ResultVal = B.createInitExistentialAddr(InstLoc, Val, Ty, LoweredTy,
6301
486
                                              conformances);
6302
486
      break;
6303
486
    }
6304
21
    case SILInstructionKind::InitExistentialValueInst: {
6305
21
      CanType FormalConcreteTy;
6306
21
      SILType ExistentialTy;
6307
21
      SourceLoc TyLoc;
6308
6309
21
      if (parseTypedValueRef(Val, B) ||
6310
21
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6311
21
          P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
6312
21
          parseASTType(FormalConcreteTy, TyLoc) ||
6313
21
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6314
21
          parseSILType(ExistentialTy) || parseSILDebugLocation(InstLoc, B))
6315
0
        return true;
6316
6317
21
      ArrayRef<ProtocolConformanceRef> conformances =
6318
21
          collectExistentialConformances(P, FormalConcreteTy, TyLoc,
6319
21
                                         ExistentialTy.getASTType());
6320
6321
21
      ResultVal = B.createInitExistentialValue(
6322
21
          InstLoc, ExistentialTy, FormalConcreteTy, Val, conformances);
6323
21
      break;
6324
21
    }
6325
249
    case SILInstructionKind::AllocExistentialBoxInst: {
6326
249
      SILType ExistentialTy;
6327
249
      CanType ConcreteFormalTy;
6328
249
      SourceLoc TyLoc;
6329
6330
249
      if (parseSILType(ExistentialTy) ||
6331
249
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6332
249
          P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
6333
249
          parseASTType(ConcreteFormalTy, TyLoc) ||
6334
249
          parseSILDebugLocation(InstLoc, B))
6335
0
        return true;
6336
6337
      // Collect conformances for the type.
6338
249
      ArrayRef<ProtocolConformanceRef> conformances =
6339
249
          collectExistentialConformances(P, ConcreteFormalTy, TyLoc,
6340
249
                                         ExistentialTy.getASTType());
6341
6342
249
      ResultVal = B.createAllocExistentialBox(InstLoc, ExistentialTy,
6343
249
                                              ConcreteFormalTy, conformances);
6344
6345
249
      break;
6346
249
    }
6347
336
    case SILInstructionKind::InitExistentialRefInst: {
6348
336
      CanType FormalConcreteTy;
6349
336
      SILType ExistentialTy;
6350
336
      SourceLoc TyLoc;
6351
6352
336
      if (parseTypedValueRef(Val, B) ||
6353
336
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
6354
336
          P.parseToken(tok::sil_dollar, diag::expected_tok_in_sil_instr, "$") ||
6355
336
          parseASTType(FormalConcreteTy, TyLoc) ||
6356
336
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6357
336
          parseSILType(ExistentialTy))
6358
0
        return true;
6359
6360
336
      ValueOwnershipKind forwardingOwnership = Val->getOwnershipKind();
6361
336
      if (parseForwardingOwnershipKind(forwardingOwnership)
6362
336
          || parseSILDebugLocation(InstLoc, B))
6363
0
        return true;
6364
6365
336
      ArrayRef<ProtocolConformanceRef> conformances =
6366
336
          collectExistentialConformances(P, FormalConcreteTy, TyLoc,
6367
336
                                         ExistentialTy.getASTType());
6368
6369
      // FIXME: Conformances in InitExistentialRefInst is currently not included
6370
      // in SIL.rst.
6371
336
      ResultVal =
6372
336
          B.createInitExistentialRef(InstLoc, ExistentialTy, FormalConcreteTy,
6373
336
                                     Val, conformances, forwardingOwnership);
6374
336
      break;
6375
336
    }
6376
492
    case SILInstructionKind::InitExistentialMetatypeInst: {
6377
492
      SourceLoc TyLoc;
6378
492
      SILType ExistentialTy;
6379
492
      if (parseTypedValueRef(Val, B) ||
6380
492
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6381
492
          parseSILType(ExistentialTy, TyLoc) ||
6382
492
          parseSILDebugLocation(InstLoc, B))
6383
0
        return true;
6384
6385
492
      auto baseExType = ExistentialTy.getASTType();
6386
492
      auto formalConcreteType = Val->getType().getASTType();
6387
984
      while (auto instExType = dyn_cast<ExistentialMetatypeType>(baseExType)) {
6388
492
        baseExType = instExType.getInstanceType();
6389
492
        formalConcreteType =
6390
492
            cast<MetatypeType>(formalConcreteType).getInstanceType();
6391
492
      }
6392
6393
492
      ArrayRef<ProtocolConformanceRef> conformances =
6394
492
          collectExistentialConformances(P, formalConcreteType, TyLoc,
6395
492
                                         baseExType);
6396
6397
492
      ResultVal = B.createInitExistentialMetatype(InstLoc, Val, ExistentialTy,
6398
492
                                                  conformances);
6399
492
      break;
6400
492
    }
6401
48
    case SILInstructionKind::DynamicMethodBranchInst: {
6402
48
      SILDeclRef Member;
6403
48
      Identifier BBName, BBName2;
6404
48
      SourceLoc NameLoc, NameLoc2;
6405
48
      if (parseTypedValueRef(Val, B) ||
6406
48
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6407
48
          parseSILDeclRef(Member) ||
6408
48
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6409
48
          parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name) ||
6410
48
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6411
48
          parseSILIdentifier(BBName2, NameLoc2,
6412
48
                             diag::expected_sil_block_name) ||
6413
48
          parseSILDebugLocation(InstLoc, B))
6414
0
        return true;
6415
6416
48
      ResultVal = B.createDynamicMethodBranch(
6417
48
          InstLoc, Val, Member, getBBForReference(BBName, NameLoc),
6418
48
          getBBForReference(BBName2, NameLoc2));
6419
48
      break;
6420
48
    }
6421
51
    case SILInstructionKind::ProjectBlockStorageInst: {
6422
51
      if (parseTypedValueRef(Val, B) || parseSILDebugLocation(InstLoc, B))
6423
0
        return true;
6424
6425
51
      ResultVal = B.createProjectBlockStorage(InstLoc, Val);
6426
51
      break;
6427
51
    }
6428
48
    case SILInstructionKind::InitBlockStorageHeaderInst: {
6429
48
      Identifier invoke, type;
6430
48
      SourceLoc invokeLoc, typeLoc;
6431
6432
48
      UnresolvedValueName invokeName;
6433
48
      SILType invokeTy;
6434
48
      GenericSignature invokeGenericSig;
6435
48
      GenericParamList *invokeGenericParams = nullptr;
6436
6437
48
      SILType blockType;
6438
48
      SmallVector<ParsedSubstitution, 4> parsedSubs;
6439
6440
48
      if (parseTypedValueRef(Val, B) ||
6441
48
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6442
48
          parseSILIdentifier(invoke, invokeLoc, diag::expected_tok_in_sil_instr,
6443
48
                             "invoke") ||
6444
48
          parseValueName(invokeName) || parseSubstitutions(parsedSubs) ||
6445
48
          P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
6446
48
          parseSILType(invokeTy, invokeGenericSig, invokeGenericParams) ||
6447
48
          P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
6448
48
          parseSILIdentifier(type, typeLoc, diag::expected_tok_in_sil_instr,
6449
48
                             "type") ||
6450
48
          parseSILType(blockType) || parseSILDebugLocation(InstLoc, B))
6451
0
        return true;
6452
6453
48
      if (invoke.str() != "invoke") {
6454
0
        P.diagnose(invokeLoc, diag::expected_tok_in_sil_instr, "invoke");
6455
0
        return true;
6456
0
      }
6457
48
      if (type.str() != "type") {
6458
0
        P.diagnose(invokeLoc, diag::expected_tok_in_sil_instr, "type");
6459
0
        return true;
6460
0
      }
6461
6462
48
      auto invokeVal = getLocalValue(invokeName, invokeTy, InstLoc, B);
6463
6464
48
      SubstitutionMap subMap;
6465
48
      if (!parsedSubs.empty()) {
6466
0
        if (!invokeGenericSig) {
6467
0
          P.diagnose(typeLoc, diag::sil_substitutions_on_non_polymorphic_type);
6468
0
          return true;
6469
0
        }
6470
6471
0
        subMap = getApplySubstitutionsFromParsed(*this, invokeGenericSig,
6472
0
                                                 parsedSubs);
6473
0
        if (!subMap)
6474
0
          return true;
6475
0
      }
6476
6477
48
      ResultVal = B.createInitBlockStorageHeader(InstLoc, Val, invokeVal,
6478
48
                                                 blockType, subMap);
6479
48
      break;
6480
48
    }
6481
140
    case SILInstructionKind::DifferentiableFunctionInst: {
6482
      // e.g. differentiable_function [parameters 0 1 2] [results 0] %0 : $T
6483
      //
6484
      // e.g. differentiable_function [parameters 0 1 2] [results 0] %0 : $T
6485
      //          with_derivative {%1 : $T, %2 : $T}
6486
      //                           ^~ jvp   ^~ vjp
6487
      // Parse `[parameters <integer_literal>...]`.
6488
140
      SmallVector<unsigned, 8> rawParameterIndices;
6489
140
      if (parseIndexList(P, "parameters", rawParameterIndices,
6490
140
                         diag::sil_autodiff_expected_parameter_index))
6491
0
        return true;
6492
140
      SmallVector<unsigned, 2> rawResultIndices;
6493
140
      if (parseIndexList(P, "results", rawResultIndices,
6494
140
                         diag::sil_autodiff_expected_result_index))
6495
0
        return true;
6496
      // Parse the original function value.
6497
140
      SILValue original;
6498
140
      SourceLoc originalOperandLoc;
6499
140
      if (parseTypedValueRef(original, originalOperandLoc, B))
6500
0
        return true;
6501
140
      auto fnType = original->getType().getAs<SILFunctionType>();
6502
140
      if (!fnType) {
6503
0
        P.diagnose(originalOperandLoc,
6504
0
                   diag::sil_inst_autodiff_expected_function_type_operand);
6505
0
        return true;
6506
0
      }
6507
140
      llvm::Optional<std::pair<SILValue, SILValue>> derivativeFunctions =
6508
140
          llvm::None;
6509
      // Parse an optional operand list
6510
      //   `with_derivative { <operand> , <operand> }`.
6511
140
      if (P.Tok.is(tok::identifier) && P.Tok.getText() == "with_derivative") {
6512
108
        P.consumeToken(tok::identifier);
6513
        // Parse derivative function values as an operand list.
6514
        // FIXME(rxwei): Change this to *not* require a type signature once
6515
        // we can infer derivative function types.
6516
108
        derivativeFunctions = std::make_pair(SILValue(), SILValue());
6517
108
        if (P.parseToken(
6518
108
                tok::l_brace,
6519
108
                diag::sil_inst_autodiff_operand_list_expected_lbrace) ||
6520
108
            parseTypedValueRef(derivativeFunctions->first, B) ||
6521
108
            P.parseToken(tok::comma,
6522
108
                         diag::sil_inst_autodiff_operand_list_expected_comma) ||
6523
108
            parseTypedValueRef(derivativeFunctions->second, B) ||
6524
108
            P.parseToken(tok::r_brace,
6525
108
                         diag::sil_inst_autodiff_operand_list_expected_rbrace))
6526
0
          return true;
6527
108
      }
6528
6529
140
      ValueOwnershipKind forwardingOwnership(OwnershipKind::None);
6530
140
      if (parseForwardingOwnershipKind(forwardingOwnership)
6531
140
          || parseSILDebugLocation(InstLoc, B))
6532
0
        return true;
6533
140
      auto *parameterIndices = IndexSubset::get(
6534
140
          P.Context, fnType->getNumParameters(), rawParameterIndices);
6535
140
      auto *resultIndices = IndexSubset::get(
6536
140
          P.Context,
6537
140
          fnType->getNumResults() + fnType->getNumIndirectMutatingParameters(),
6538
140
          rawResultIndices);
6539
140
      if (forwardingOwnership != OwnershipKind::None) {
6540
0
        ResultVal = B.createDifferentiableFunction(
6541
0
            InstLoc, parameterIndices, resultIndices, original,
6542
0
            derivativeFunctions, forwardingOwnership);
6543
140
      } else {
6544
140
        ResultVal = B.createDifferentiableFunction(InstLoc, parameterIndices,
6545
140
                                                   resultIndices, original,
6546
140
                                                   derivativeFunctions);
6547
140
      }
6548
140
      break;
6549
140
    }
6550
32
    case SILInstructionKind::LinearFunctionInst: {
6551
      // e.g. linear_function [parameters 0 1 2] %0 : $T
6552
      // e.g. linear_function [parameters 0 1 2] %0 : $T with_transpose %1 : $T
6553
      // Parse `[parameters <integer_literal>...]`.
6554
32
      SmallVector<unsigned, 8> rawParameterIndices;
6555
32
      if (parseIndexList(P, "parameters", rawParameterIndices,
6556
32
                         diag::sil_autodiff_expected_parameter_index))
6557
0
        return true;
6558
      // Parse the original function value.
6559
32
      SILValue original;
6560
32
      SourceLoc originalOperandLoc;
6561
32
      if (parseTypedValueRef(original, originalOperandLoc, B))
6562
0
        return true;
6563
32
      auto fnType = original->getType().getAs<SILFunctionType>();
6564
32
      if (!fnType) {
6565
0
        P.diagnose(originalOperandLoc,
6566
0
                   diag::sil_inst_autodiff_expected_function_type_operand);
6567
0
        return true;
6568
0
      }
6569
      // Parse an optional transpose function.
6570
32
      llvm::Optional<SILValue> transpose = llvm::None;
6571
32
      if (P.Tok.is(tok::identifier) && P.Tok.getText() == "with_transpose") {
6572
12
        P.consumeToken(tok::identifier);
6573
12
        transpose = SILValue();
6574
12
        if (parseTypedValueRef(*transpose, B))
6575
0
          return true;
6576
12
      }
6577
6578
32
      ValueOwnershipKind forwardingOwnership(OwnershipKind::None);
6579
32
      if (parseForwardingOwnershipKind(forwardingOwnership)
6580
32
          || parseSILDebugLocation(InstLoc, B))
6581
0
        return true;
6582
6583
32
      auto *parameterIndicesSubset = IndexSubset::get(
6584
32
          P.Context, fnType->getNumParameters(), rawParameterIndices);
6585
6586
32
      if (forwardingOwnership != OwnershipKind::None) {
6587
0
        ResultVal =
6588
0
            B.createLinearFunction(InstLoc, parameterIndicesSubset, original,
6589
0
                                   forwardingOwnership, transpose);
6590
32
      } else {
6591
32
        ResultVal = B.createLinearFunction(InstLoc, parameterIndicesSubset,
6592
32
                                           original, transpose);
6593
32
      }
6594
32
      break;
6595
32
    }
6596
144
    case SILInstructionKind::DifferentiableFunctionExtractInst: {
6597
      // Parse the rest of the instruction: an extractee, a differentiable
6598
      // function operand, an optional explicit extractee type, and a debug
6599
      // location.
6600
144
      NormalDifferentiableFunctionTypeComponent extractee;
6601
144
      StringRef extracteeNames[3] = {"original", "jvp", "vjp"};
6602
144
      SILValue functionOperand;
6603
144
      SourceLoc lastLoc;
6604
144
      if (P.parseToken(
6605
144
              tok::l_square,
6606
144
              diag::sil_inst_autodiff_expected_differentiable_extractee_kind) ||
6607
144
          parseSILIdentifierSwitch(
6608
144
              extractee, extracteeNames,
6609
144
              diag::sil_inst_autodiff_expected_differentiable_extractee_kind) ||
6610
144
          P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare,
6611
144
                       "extractee kind"))
6612
0
        return true;
6613
144
      if (parseTypedValueRef(functionOperand, B))
6614
0
        return true;
6615
      // Parse an optional explicit extractee type.
6616
144
      llvm::Optional<SILType> extracteeType = llvm::None;
6617
144
      if (P.consumeIf(tok::kw_as)) {
6618
0
        extracteeType = SILType();
6619
0
        if (parseSILType(*extracteeType))
6620
0
          return true;
6621
0
      }
6622
6623
144
      ValueOwnershipKind forwardingOwnership =
6624
144
          functionOperand->getOwnershipKind();
6625
144
      if (parseForwardingOwnershipKind(forwardingOwnership)
6626
144
          || parseSILDebugLocation(InstLoc, B))
6627
0
        return true;
6628
6629
144
      ResultVal = B.createDifferentiableFunctionExtract(
6630
144
          InstLoc, extractee, functionOperand, forwardingOwnership,
6631
144
          extracteeType);
6632
144
      break;
6633
144
    }
6634
24
    case SILInstructionKind::LinearFunctionExtractInst: {
6635
      // Parse the rest of the instruction: an extractee, a linear function
6636
      // operand, and a debug location.
6637
24
      LinearDifferentiableFunctionTypeComponent extractee;
6638
24
      StringRef extracteeNames[2] = {"original", "transpose"};
6639
24
      SILValue functionOperand;
6640
24
      SourceLoc lastLoc;
6641
24
      if (P.parseToken(tok::l_square,
6642
24
              diag::sil_inst_autodiff_expected_linear_extractee_kind) ||
6643
24
          parseSILIdentifierSwitch(extractee, extracteeNames,
6644
24
              diag::sil_inst_autodiff_expected_linear_extractee_kind) ||
6645
24
          P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare,
6646
24
                       "extractee kind"))
6647
0
        return true;
6648
24
      if (parseTypedValueRef(functionOperand, B))
6649
0
        return true;
6650
6651
24
      ValueOwnershipKind forwardingOwnership =
6652
24
          functionOperand->getOwnershipKind();
6653
24
      if (parseForwardingOwnershipKind(forwardingOwnership)
6654
24
          || parseSILDebugLocation(InstLoc, B))
6655
0
        return true;
6656
24
      ResultVal = B.createLinearFunctionExtract(
6657
24
          InstLoc, extractee, functionOperand, forwardingOwnership);
6658
24
      break;
6659
24
    }
6660
208
    case SILInstructionKind::DifferentiabilityWitnessFunctionInst: {
6661
      // e.g. differentiability_witness_function
6662
      //      [jvp] [parameters 0 1] [results 0] <T where T: Differentiable>
6663
      //      @foo : <T> $(T) -> T
6664
208
      DifferentiabilityWitnessFunctionKind witnessKind;
6665
208
      StringRef witnessKindNames[3] = {"jvp", "vjp", "transpose"};
6666
208
      if (P.parseToken(
6667
208
              tok::l_square,
6668
208
              diag::
6669
208
                  sil_inst_autodiff_expected_differentiability_witness_kind) ||
6670
208
          parseSILIdentifierSwitch(
6671
208
              witnessKind, witnessKindNames,
6672
208
              diag::
6673
208
                  sil_inst_autodiff_expected_differentiability_witness_kind) ||
6674
208
          P.parseToken(tok::r_square, diag::sil_autodiff_expected_rsquare,
6675
208
                       "differentiability witness function kind"))
6676
0
        return true;
6677
208
      SourceLoc keyStartLoc = P.Tok.getLoc();
6678
208
      DifferentiabilityKind diffKind;
6679
208
      AutoDiffConfig config;
6680
208
      SILFunction *originalFn = nullptr;
6681
208
      if (parseSILDifferentiabilityWitnessConfigAndFunction(
6682
208
              P, *this, InstLoc, diffKind, config, originalFn))
6683
0
        return true;
6684
208
      auto *witness = SILMod.lookUpDifferentiabilityWitness(
6685
208
          {originalFn->getName(), diffKind, config});
6686
208
      if (!witness) {
6687
0
        P.diagnose(keyStartLoc, diag::sil_diff_witness_undefined);
6688
0
        return true;
6689
0
      }
6690
      // Parse an optional explicit function type.
6691
208
      llvm::Optional<SILType> functionType = llvm::None;
6692
208
      if (P.consumeIf(tok::kw_as)) {
6693
0
        functionType = SILType();
6694
0
        if (parseSILType(*functionType))
6695
0
          return true;
6696
0
      }
6697
208
      ResultVal = B.createDifferentiabilityWitnessFunction(
6698
208
          InstLoc, witnessKind, witness, functionType);
6699
208
      break;
6700
208
    }
6701
60
    case SILInstructionKind::AwaitAsyncContinuationInst: {
6702
      // 'await_async_continuation' operand, 'resume' bb, 'error' bb
6703
60
      Identifier ResumeBBName, ErrorBBName{};
6704
60
      SourceLoc ResumeNameLoc, ErrorNameLoc{};
6705
60
      if (parseTypedValueRef(Val, B)
6706
60
          || P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")
6707
60
          || P.parseSpecificIdentifier("resume", diag::expected_tok_in_sil_instr, "resume")
6708
60
          || parseSILIdentifier(ResumeBBName, ResumeNameLoc, diag::expected_sil_block_name)) {
6709
0
        return true;
6710
0
      }
6711
      
6712
60
      if (P.consumeIf(tok::comma)) {
6713
30
          if (P.parseSpecificIdentifier("error", diag::expected_tok_in_sil_instr, "error")
6714
30
              || parseSILIdentifier(ErrorBBName, ErrorNameLoc, diag::expected_sil_block_name)
6715
30
              || parseSILDebugLocation(InstLoc, B)) {
6716
0
            return true;
6717
0
          }
6718
30
      }
6719
      
6720
60
      SILBasicBlock *resumeBB, *errorBB = nullptr;
6721
60
      resumeBB = getBBForReference(ResumeBBName, ResumeNameLoc);
6722
60
      if (!ErrorBBName.empty()) {
6723
30
        errorBB = getBBForReference(ErrorBBName, ErrorNameLoc);
6724
30
      }
6725
60
      ResultVal = B.createAwaitAsyncContinuation(InstLoc, Val, resumeBB, errorBB);
6726
60
      break;
6727
60
    }
6728
30
    case SILInstructionKind::GetAsyncContinuationInst:
6729
60
    case SILInstructionKind::GetAsyncContinuationAddrInst: {
6730
      // 'get_async_continuation'      '[throws]'? type
6731
      // 'get_async_continuation_addr' '[throws]'? type ',' operand
6732
60
      bool throws = false;
6733
60
      if (P.consumeIf(tok::l_square)) {
6734
30
        if (P.parseToken(tok::kw_throws, diag::expected_tok_in_sil_instr, "throws")
6735
30
            || P.parseToken(tok::r_square, diag::expected_tok_in_sil_instr, "]"))
6736
0
          return true;
6737
        
6738
30
        throws = true;
6739
30
      }
6740
      
6741
60
      CanType resumeTy;
6742
60
      if (parseASTType(resumeTy)) {
6743
0
        return true;
6744
0
      }
6745
      
6746
60
      SILValue resumeBuffer;
6747
60
      if (Opcode == SILInstructionKind::GetAsyncContinuationAddrInst) {
6748
30
        if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",")
6749
30
            || parseTypedValueRef(resumeBuffer, B)) {
6750
0
          return true;
6751
0
        }
6752
30
      }
6753
      
6754
60
      if (parseSILDebugLocation(InstLoc, B))
6755
0
        return true;
6756
      
6757
60
      if (Opcode == SILInstructionKind::GetAsyncContinuationAddrInst) {
6758
30
        ResultVal = B.createGetAsyncContinuationAddr(InstLoc, resumeBuffer,
6759
30
                                                     resumeTy, throws);
6760
30
      } else {
6761
30
        ResultVal = B.createGetAsyncContinuation(InstLoc, resumeTy, throws);
6762
30
      }
6763
60
      break;
6764
60
    }
6765
9
    case SILInstructionKind::HasSymbolInst: {
6766
      // 'has_symbol' sil-decl-ref
6767
9
      SILDeclRef declRef;
6768
9
      if (parseSILDeclRef(declRef))
6769
0
        return true;
6770
6771
9
      ResultVal = B.createHasSymbol(InstLoc, declRef.getDecl());
6772
9
      break;
6773
9
    }
6774
6775
557k
    }
6776
6777
557k
    return false;
6778
557k
}
6779
6780
/// sil-instruction-result ::= sil-value-name '='
6781
/// sil-instruction-result ::= '(' sil-value-name? ')'
6782
/// sil-instruction-result ::= '(' sil-value-name (',' sil-value-name)* ')'
6783
/// sil-instruction-source-info ::= (',' sil-scope-ref)? (',' sil-loc)?
6784
/// sil-instruction-def ::=
6785
///   (sil-instruction-result '=')? sil-instruction sil-instruction-source-info
6786
557k
bool SILParser::parseSILInstruction(SILBuilder &B) {
6787
  // We require SIL instructions to be at the start of a line to assist
6788
  // recovery.
6789
557k
  if (!P.Tok.isAtStartOfLine()) {
6790
0
    P.diagnose(P.Tok, diag::expected_sil_instr_start_of_line);
6791
0
    return true;
6792
0
  }
6793
6794
557k
  if (!B.hasValidInsertionPoint()) {
6795
3
    P.diagnose(P.Tok, diag::expected_sil_block_name);
6796
3
    return true;
6797
3
  }
6798
6799
557k
  SmallVector<Located<StringRef>, 4> resultNames;
6800
557k
  SourceLoc resultClauseBegin;
6801
6802
  // If the instruction has a name '%foo =', parse it.
6803
557k
  if (P.Tok.is(tok::sil_local_name)) {
6804
228k
    resultClauseBegin = P.Tok.getLoc();
6805
228k
    resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()});
6806
228k
    P.consumeToken(tok::sil_local_name);
6807
6808
    // If the instruction has a '(%foo, %bar) = ', parse it.
6809
328k
  } else if (P.consumeIf(tok::l_paren)) {
6810
1.49k
    resultClauseBegin = P.PreviousLoc;
6811
6812
1.49k
    if (!P.consumeIf(tok::r_paren)) {
6813
3.01k
      while (true) {
6814
3.01k
        if (!P.Tok.is(tok::sil_local_name)) {
6815
0
          P.diagnose(P.Tok, diag::expected_sil_value_name);
6816
0
          return true;
6817
0
        }
6818
6819
3.01k
        resultNames.push_back({P.Tok.getText(), P.Tok.getLoc()});
6820
3.01k
        P.consumeToken(tok::sil_local_name);
6821
6822
3.01k
        if (P.consumeIf(tok::comma))
6823
1.53k
          continue;
6824
1.47k
        if (P.consumeIf(tok::r_paren))
6825
1.47k
          break;
6826
6827
0
        P.diagnose(P.Tok, diag::expected_tok_in_sil_instr, ",");
6828
0
        return true;
6829
1.47k
      }
6830
1.47k
    }
6831
1.49k
  }
6832
6833
557k
  if (resultClauseBegin.isValid()) {
6834
230k
    if (P.parseToken(tok::equal, diag::expected_equal_in_sil_instr))
6835
0
      return true;
6836
230k
  }
6837
6838
557k
  SILInstructionKind Opcode;
6839
557k
  SourceLoc OpcodeLoc;
6840
557k
  StringRef OpcodeName;
6841
6842
  // Parse the opcode name.
6843
557k
  if (parseSILOpcode(Opcode, OpcodeLoc, OpcodeName))
6844
0
    return true;
6845
6846
  // Perform opcode specific parsing.
6847
557k
  SILInstruction *ResultVal;
6848
557k
  if (parseSpecificSILInstruction(B, Opcode, OpcodeLoc, OpcodeName, ResultVal))
6849
33
    return true;
6850
6851
  // Match the results clause if we had one.
6852
557k
  if (resultClauseBegin.isValid()) {
6853
230k
    auto results = ResultVal->getResults();
6854
230k
    if (results.size() != resultNames.size()) {
6855
0
      P.diagnose(resultClauseBegin, diag::wrong_result_count_in_sil_instr,
6856
0
                 results.size());
6857
230k
    } else {
6858
231k
      for (size_t i : indices(results)) {
6859
231k
        setLocalValue(results[i], resultNames[i].Item, resultNames[i].Loc);
6860
231k
      }
6861
230k
    }
6862
230k
  }
6863
6864
557k
  return false;
6865
557k
}
6866
6867
bool SILParser::parseCallInstruction(SILLocation InstLoc,
6868
                                     SILInstructionKind Opcode, SILBuilder &B,
6869
35.9k
                                     SILInstruction *&ResultVal) {
6870
35.9k
  UnresolvedValueName FnName;
6871
35.9k
  SmallVector<UnresolvedValueName, 4> ArgNames;
6872
6873
35.9k
  auto PartialApplyConvention = ParameterConvention::Direct_Owned;
6874
35.9k
  ApplyOptions ApplyOpts;
6875
35.9k
  bool IsNoEscape = false;
6876
35.9k
  StringRef AttrName;
6877
6878
37.9k
  while (parseSILOptional(AttrName, *this)) {
6879
2.06k
    if (AttrName.equals("nothrow"))
6880
57
      ApplyOpts |= ApplyFlags::DoesNotThrow;
6881
2.00k
    else if (AttrName.equals("noasync"))
6882
15
      ApplyOpts |= ApplyFlags::DoesNotAwait;
6883
1.99k
    else if (AttrName.equals("callee_guaranteed"))
6884
1.78k
      PartialApplyConvention = ParameterConvention::Direct_Guaranteed;
6885
210
    else if (AttrName.equals("on_stack"))
6886
210
      IsNoEscape = true;
6887
0
    else
6888
0
      return true;
6889
2.06k
  }
6890
  
6891
35.9k
  if (parseValueName(FnName))
6892
0
    return true;
6893
35.9k
  SmallVector<ParsedSubstitution, 4> parsedSubs;
6894
35.9k
  if (parseSubstitutions(parsedSubs))
6895
0
    return true;
6896
    
6897
35.9k
  if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
6898
0
    return true;
6899
6900
35.9k
  if (P.Tok.isNot(tok::r_paren)) {
6901
43.9k
    do {
6902
43.9k
      UnresolvedValueName Arg;
6903
43.9k
      if (parseValueName(Arg)) return true;
6904
43.9k
      ArgNames.push_back(Arg);
6905
43.9k
    } while (P.consumeIf(tok::comma));
6906
28.4k
  }
6907
6908
35.9k
  SILType Ty;
6909
35.9k
  SourceLoc TypeLoc;
6910
35.9k
  GenericSignature GenericSig;
6911
35.9k
  GenericParamList *GenericParams = nullptr;
6912
35.9k
  if (P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")") ||
6913
35.9k
      P.parseToken(tok::colon, diag::expected_tok_in_sil_instr, ":") ||
6914
35.9k
      parseSILType(Ty, TypeLoc, GenericSig, GenericParams))
6915
0
    return true;
6916
6917
35.9k
  auto FTI = Ty.getAs<SILFunctionType>();
6918
35.9k
  if (!FTI) {
6919
0
    P.diagnose(TypeLoc, diag::expected_sil_type_kind, "be a function");
6920
0
    return true;
6921
0
  }
6922
6923
35.9k
  SubstitutionMap subs;
6924
35.9k
  if (!parsedSubs.empty()) {
6925
6.34k
    if (!GenericSig) {
6926
0
      P.diagnose(TypeLoc, diag::sil_substitutions_on_non_polymorphic_type);
6927
0
      return true;
6928
0
    }
6929
6.34k
    subs = getApplySubstitutionsFromParsed(*this, GenericSig, parsedSubs);
6930
6.34k
    if (!subs)
6931
0
      return true;
6932
6.34k
  }
6933
6934
35.9k
  SILValue FnVal = getLocalValue(FnName, Ty, InstLoc, B);
6935
6936
35.9k
  SILType FnTy = FnVal->getType();
6937
35.9k
  CanSILFunctionType substFTI = FTI;
6938
35.9k
  if (!subs.empty()) {
6939
6.34k
    auto silFnTy = FnTy.castTo<SILFunctionType>();
6940
6.34k
    substFTI =
6941
6.34k
        silFnTy->substGenericArgs(SILMod, subs, B.getTypeExpansionContext());
6942
6.34k
    FnTy = SILType::getPrimitiveObjectType(substFTI);
6943
6.34k
  }
6944
35.9k
  SILFunctionConventions substConv(substFTI, B.getModule());
6945
6946
  // Validate the operand count.
6947
35.9k
  if (substConv.getNumSILArguments() != ArgNames.size() &&
6948
35.9k
      Opcode != SILInstructionKind::PartialApplyInst) {
6949
0
    P.diagnose(TypeLoc, diag::expected_sil_type_kind,
6950
0
               "to have the same number of arg names as arg types");
6951
0
    return true;
6952
0
  }
6953
6954
  // Validate the coroutine kind.
6955
35.9k
  if (Opcode == SILInstructionKind::ApplyInst ||
6956
35.9k
      Opcode == SILInstructionKind::TryApplyInst) {
6957
32.4k
    if (FTI->getCoroutineKind() != SILCoroutineKind::None) {
6958
0
      P.diagnose(TypeLoc, diag::expected_sil_type_kind,
6959
0
                 "to not be a coroutine");
6960
0
      return true;
6961
0
    }
6962
32.4k
  } else if (Opcode == SILInstructionKind::BeginApplyInst) {
6963
480
    if (FTI->getCoroutineKind() != SILCoroutineKind::YieldOnce) {
6964
0
      P.diagnose(TypeLoc, diag::expected_sil_type_kind,
6965
0
                 "to be a yield_once coroutine");
6966
0
      return true;
6967
0
    }
6968
3.02k
  } else {
6969
3.02k
    assert(Opcode == SILInstructionKind::PartialApplyInst);
6970
    // partial_apply accepts all kinds of function
6971
3.02k
  }
6972
6973
35.9k
  switch (Opcode) {
6974
0
  default: llvm_unreachable("Unexpected case");
6975
31.3k
  case SILInstructionKind::ApplyInst : {
6976
31.3k
    if (parseSILDebugLocation(InstLoc, B))
6977
0
      return true;
6978
6979
31.3k
    unsigned ArgNo = 0;
6980
31.3k
    SmallVector<SILValue, 4> Args;
6981
39.2k
    for (auto &ArgName : ArgNames) {
6982
39.2k
      SILType expectedTy =
6983
39.2k
          substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext());
6984
39.2k
      Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B));
6985
39.2k
    }
6986
6987
31.3k
    ResultVal = B.createApply(InstLoc, FnVal, subs, Args, ApplyOpts);
6988
31.3k
    break;
6989
31.3k
  }
6990
480
  case SILInstructionKind::BeginApplyInst: {
6991
480
    if (parseSILDebugLocation(InstLoc, B))
6992
0
      return true;
6993
    
6994
480
    unsigned ArgNo = 0;
6995
480
    SmallVector<SILValue, 4> Args;
6996
480
    for (auto &ArgName : ArgNames) {
6997
264
      SILType expectedTy =
6998
264
          substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext());
6999
264
      Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B));
7000
264
    }
7001
7002
480
    ResultVal =
7003
480
      B.createBeginApply(InstLoc, FnVal, subs, Args, ApplyOpts);
7004
480
    break;
7005
480
  }
7006
3.02k
  case SILInstructionKind::PartialApplyInst: {
7007
3.02k
    if (parseSILDebugLocation(InstLoc, B))
7008
0
      return true;
7009
7010
    // Compute the result type of the partial_apply, based on which arguments
7011
    // are getting applied.
7012
3.02k
    SmallVector<SILValue, 4> Args;
7013
3.02k
    unsigned ArgNo = substConv.getNumSILArguments() - ArgNames.size();
7014
3.29k
    for (auto &ArgName : ArgNames) {
7015
3.29k
      SILType expectedTy =
7016
3.29k
          substConv.getSILArgumentType(ArgNo++, B.getTypeExpansionContext());
7017
3.29k
      Args.push_back(getLocalValue(ArgName, expectedTy, InstLoc, B));
7018
3.29k
    }
7019
7020
    // FIXME: Why the arbitrary order difference in IRBuilder type argument?
7021
3.02k
    ResultVal = B.createPartialApply(
7022
3.02k
        InstLoc, FnVal, subs, Args, PartialApplyConvention,
7023
3.02k
        IsNoEscape ? PartialApplyInst::OnStackKind::OnStack
7024
3.02k
                   : PartialApplyInst::OnStackKind::NotOnStack);
7025
3.02k
    break;
7026
3.02k
  }
7027
1.06k
  case SILInstructionKind::TryApplyInst: {
7028
1.06k
    Identifier normalBBName, errorBBName;
7029
1.06k
    SourceLoc normalBBLoc, errorBBLoc;
7030
1.06k
    if (P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
7031
1.06k
        parseVerbatim("normal") ||
7032
1.06k
        parseSILIdentifier(normalBBName, normalBBLoc,
7033
1.06k
                           diag::expected_sil_block_name) ||
7034
1.06k
        P.parseToken(tok::comma, diag::expected_tok_in_sil_instr, ",") ||
7035
1.06k
        parseVerbatim("error") ||
7036
1.06k
        parseSILIdentifier(errorBBName, errorBBLoc,
7037
1.06k
                           diag::expected_sil_block_name) ||
7038
1.06k
        parseSILDebugLocation(InstLoc, B))
7039
0
      return true;
7040
7041
1.06k
    unsigned argNo = 0;
7042
1.06k
    SmallVector<SILValue, 4> args;
7043
1.14k
    for (auto &argName : ArgNames) {
7044
1.14k
      SILType expectedTy =
7045
1.14k
          substConv.getSILArgumentType(argNo++, B.getTypeExpansionContext());
7046
1.14k
      args.push_back(getLocalValue(argName, expectedTy, InstLoc, B));
7047
1.14k
    }
7048
7049
1.06k
    SILBasicBlock *normalBB = getBBForReference(normalBBName, normalBBLoc);
7050
1.06k
    SILBasicBlock *errorBB = getBBForReference(errorBBName, errorBBLoc);
7051
1.06k
    ResultVal = B.createTryApply(InstLoc, FnVal, subs, args, normalBB, errorBB,
7052
1.06k
                                 ApplyOpts);
7053
1.06k
    break;
7054
1.06k
  }
7055
35.9k
  }
7056
35.9k
  return false;
7057
35.9k
}
7058
7059
bool SILParser::parseSILFunctionRef(SILLocation InstLoc,
7060
30.1k
                                    SILFunction *&ResultFn) {
7061
30.1k
  Identifier Name;
7062
30.1k
  SILType Ty;
7063
30.1k
  SourceLoc Loc = P.Tok.getLoc();
7064
30.1k
  if (parseGlobalName(Name) ||
7065
30.1k
      P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) ||
7066
30.1k
      parseSILType(Ty))
7067
0
    return true;
7068
7069
30.1k
  auto FnTy = Ty.getAs<SILFunctionType>();
7070
30.1k
  if (!FnTy || !Ty.isObject()) {
7071
0
    P.diagnose(Loc, diag::expected_sil_function_type);
7072
0
    return true;
7073
0
  }
7074
  
7075
30.1k
  ResultFn = getGlobalNameForReference(Name, FnTy, Loc);
7076
30.1k
  return false;
7077
30.1k
}
7078
7079
/// True if the current token sequence looks like the start of a SIL
7080
/// instruction. This can be one of:
7081
///
7082
/// 1. %name
7083
/// 2. ()
7084
/// 3. (%name1
7085
/// 4. identifier | keyword
7086
///   where the identifier is not followed by a ':' or '(', or it is
7087
///   followed by '(' and is an instruction name.  The exceptions here
7088
///   are for recognizing block names.
7089
556k
bool SILParser::isStartOfSILInstruction() {
7090
556k
  if (P.Tok.is(tok::sil_local_name))
7091
175k
    return true;
7092
381k
  if (P.Tok.is(tok::l_paren) &&
7093
381k
      (P.peekToken().is(tok::sil_local_name) || P.peekToken().is(tok::r_paren)))
7094
1.21k
    return true;
7095
380k
  if (P.Tok.is(tok::identifier) || P.Tok.isKeyword()) {
7096
337k
    auto &peek = P.peekToken();
7097
337k
    if (peek.is(tok::l_paren))
7098
10.2k
      return getOpcodeByName(P.Tok.getText()).has_value();
7099
326k
    return !peek.is(tok::colon);
7100
337k
  }
7101
43.0k
  return false;
7102
380k
}
7103
7104
///   sil-basic-block:
7105
///     sil-instruction+
7106
///     identifier sil-bb-argument-list? ':' sil-instruction+
7107
///   sil-bb-argument-list:
7108
///     '(' sil-typed-valueref (',' sil-typed-valueref)+ ')'
7109
237k
bool SILParser::parseSILBasicBlock(SILBuilder &B) {
7110
237k
  SILBasicBlock *BB;
7111
7112
  // The basic block name is optional.
7113
237k
  if (P.Tok.is(tok::sil_local_name)) {
7114
1.62k
    BB = getBBForDefinition(Identifier(), SourceLoc());
7115
236k
  } else {
7116
236k
    Identifier BBName;
7117
236k
    SourceLoc NameLoc;
7118
236k
    if (parseSILIdentifier(BBName, NameLoc, diag::expected_sil_block_name))
7119
0
      return true;
7120
7121
236k
    BB = getBBForDefinition(BBName, NameLoc);
7122
    // For now, since we always assume that PhiArguments have
7123
    // OwnershipKind::None, do not parse or do anything special. Eventually
7124
    // we will parse the convention.
7125
236k
    bool IsEntry = BB->isEntry();
7126
7127
    // If there is a basic block argument list, process it.
7128
236k
    if (P.consumeIf(tok::l_paren)) {
7129
55.9k
      do {
7130
55.9k
        SILType Ty;
7131
55.9k
        ValueOwnershipKind OwnershipKind = OwnershipKind::None;
7132
55.9k
        SourceLoc NameLoc;
7133
55.9k
        StringRef Name = P.Tok.getText();
7134
55.9k
        if (P.parseToken(tok::sil_local_name, NameLoc,
7135
55.9k
                         diag::expected_sil_value_name) ||
7136
55.9k
            P.parseToken(tok::colon, diag::expected_sil_colon_value_ref))
7137
0
          return true;
7138
7139
55.9k
        bool foundNoImplicitCopy = false;
7140
55.9k
        bool foundClosureCapture = false;
7141
55.9k
        bool foundLexical = false;
7142
55.9k
        bool foundEagerMove = false;
7143
55.9k
        bool foundReborrow = false;
7144
55.9k
        bool hasPointerEscape = false;
7145
56.3k
        while (auto attributeName = parseOptionalAttribute(
7146
55.9k
                   {"noImplicitCopy", "_lexical", "_eagerMove",
7147
55.9k
                    "closureCapture", "reborrow", "pointer_escape"})) {
7148
369
          if (*attributeName == "noImplicitCopy")
7149
30
            foundNoImplicitCopy = true;
7150
339
          else if (*attributeName == "_lexical")
7151
21
            foundLexical = true;
7152
318
          else if (*attributeName == "_eagerMove")
7153
45
            foundEagerMove = true;
7154
273
          else if (*attributeName == "closureCapture")
7155
246
            foundClosureCapture = true;
7156
27
          else if (*attributeName == "reborrow")
7157
21
            foundReborrow = true;
7158
6
          else if (*attributeName == "pointer_escape")
7159
6
            hasPointerEscape = true;
7160
0
          else {
7161
0
            llvm_unreachable("Unexpected attribute!");
7162
0
          }
7163
369
        }
7164
7165
55.9k
        LifetimeAnnotation lifetime = LifetimeAnnotation::None;
7166
55.9k
        if (foundEagerMove && foundLexical) {
7167
0
          P.diagnose(NameLoc, diag::sil_arg_both_lexical_and_eagerMove);
7168
0
          return true;
7169
55.9k
        } else if (foundEagerMove) {
7170
45
          lifetime = LifetimeAnnotation::EagerMove;
7171
55.9k
        } else if (foundLexical) {
7172
21
          lifetime = LifetimeAnnotation::Lexical;
7173
21
        }
7174
7175
        // If SILOwnership is enabled and we are not assuming that we are
7176
        // parsing unqualified SIL, look for printed value ownership kinds.
7177
55.9k
        if (F->hasOwnership() &&
7178
55.9k
            parseSILOwnership(OwnershipKind))
7179
0
          return true;
7180
7181
55.9k
        if (parseSILType(Ty))
7182
3
          return true;
7183
7184
55.9k
        SILArgument *Arg;
7185
55.9k
        if (IsEntry) {
7186
44.6k
          auto *fArg = BB->createFunctionArgument(Ty);
7187
44.6k
          fArg->setNoImplicitCopy(foundNoImplicitCopy);
7188
44.6k
          fArg->setClosureCapture(foundClosureCapture);
7189
44.6k
          fArg->setLifetimeAnnotation(lifetime);
7190
44.6k
          fArg->setReborrow(foundReborrow);
7191
44.6k
          fArg->setHasPointerEscape(hasPointerEscape);
7192
44.6k
          Arg = fArg;
7193
7194
          // Today, we construct the ownership kind straight from the function
7195
          // type. Make sure they are in sync, otherwise bail. We want this to
7196
          // be an exact check rather than a compatibility check since we do not
7197
          // want incompatibilities in between @any and other types of ownership
7198
          // to be ignored.
7199
44.6k
          if (F->hasOwnership() && Arg->getOwnershipKind() != OwnershipKind) {
7200
6
            auto diagID =
7201
6
                diag::silfunc_and_silarg_have_incompatible_sil_value_ownership;
7202
6
            P.diagnose(NameLoc, diagID, Arg->getOwnershipKind().asString(),
7203
6
                       OwnershipKind.asString());
7204
6
            return true;
7205
6
          }
7206
44.6k
        } else {
7207
11.3k
          Arg = BB->createPhiArgument(Ty, OwnershipKind, /*decl*/ nullptr,
7208
11.3k
                                      foundReborrow, hasPointerEscape);
7209
11.3k
        }
7210
55.9k
        setLocalValue(Arg, Name, NameLoc);
7211
55.9k
      } while (P.consumeIf(tok::comma));
7212
      
7213
42.1k
      if (P.parseToken(tok::r_paren, diag::sil_basicblock_arg_rparen))
7214
0
        return true;
7215
42.1k
    }
7216
    
7217
236k
    if (P.parseToken(tok::colon, diag::expected_sil_block_colon))
7218
0
      return true;
7219
236k
  }
7220
  
7221
  // Make sure the block is at the end of the function so that forward
7222
  // references don't affect block layout.
7223
237k
  F->moveBlockBefore(BB, F->end());
7224
7225
237k
  B.setInsertionPoint(BB);
7226
556k
  do {
7227
556k
    if (parseSILInstruction(B))
7228
36
      return true;
7229
556k
  } while (isStartOfSILInstruction());
7230
7231
237k
  return false;
7232
237k
}
7233
7234
43.0k
static void populateOwnershipFlags(SILFunction *func) {
7235
237k
  for (auto &bb : *func) {
7236
237k
    for (auto &arg : bb.getArguments()) {
7237
55.9k
      if (computeIsReborrow(arg)) {
7238
816
        arg->setReborrow(true);
7239
816
      }
7240
55.9k
    }
7241
237k
  }
7242
43.0k
}
7243
7244
///   decl-sil:   [[only in SIL mode]]
7245
///     'sil' sil-linkage '@' identifier ':' sil-type decl-sil-body?
7246
///   decl-sil-body:
7247
///     '{' sil-basic-block+ '}'
7248
54.6k
bool SILParserState::parseDeclSIL(Parser &P) {
7249
  // Inform the lexer that we're lexing the body of the SIL declaration.  Do
7250
  // this before we consume the 'sil' token so that all later tokens are
7251
  // properly handled.
7252
54.6k
  Lexer::SILBodyRAII Tmp(*P.L);
7253
7254
54.6k
  P.consumeToken(tok::kw_sil);
7255
7256
54.6k
  SILParser FunctionState(P);
7257
7258
54.6k
  llvm::Optional<SILLinkage> FnLinkage;
7259
54.6k
  Identifier FnName;
7260
54.6k
  SILType FnType;
7261
54.6k
  SourceLoc FnNameLoc;
7262
7263
54.6k
  bool isTransparent = false;
7264
54.6k
  IsSerialized_t isSerialized = IsNotSerialized;
7265
54.6k
  bool isCanonical = false;
7266
54.6k
  IsDynamicallyReplaceable_t isDynamic = IsNotDynamic;
7267
54.6k
  IsDistributed_t isDistributed = IsNotDistributed;
7268
54.6k
  IsRuntimeAccessible_t isRuntimeAccessible = IsNotRuntimeAccessible;
7269
54.6k
  ForceEnableLexicalLifetimes_t forceEnableLexicalLifetimes =
7270
54.6k
      DoNotForceEnableLexicalLifetimes;
7271
54.6k
  UseStackForPackMetadata_t useStackForPackMetadata = DoUseStackForPackMetadata;
7272
54.6k
  bool hasUnsafeNonEscapableResult = false;
7273
54.6k
  IsExactSelfClass_t isExactSelfClass = IsNotExactSelfClass;
7274
54.6k
  bool hasOwnershipSSA = false;
7275
54.6k
  IsThunk_t isThunk = IsNotThunk;
7276
54.6k
  SILFunction::Purpose specialPurpose = SILFunction::Purpose::None;
7277
54.6k
  bool isWeakImported = false;
7278
54.6k
  bool needStackProtection = false;
7279
54.6k
  AvailabilityContext availability = AvailabilityContext::alwaysAvailable();
7280
54.6k
  bool isWithoutActuallyEscapingThunk = false;
7281
54.6k
  Inline_t inlineStrategy = InlineDefault;
7282
54.6k
  OptimizationMode optimizationMode = OptimizationMode::NotSet;
7283
54.6k
  PerformanceConstraints perfConstr = PerformanceConstraints::None;
7284
54.6k
  bool markedAsUsed = false;
7285
54.6k
  StringRef section;
7286
54.6k
  SmallVector<std::string, 1> Semantics;
7287
54.6k
  SmallVector<ParsedSpecAttr, 4> SpecAttrs;
7288
54.6k
  ValueDecl *ClangDecl = nullptr;
7289
54.6k
  EffectsKind MRK = EffectsKind::Unspecified;
7290
54.6k
  SILFunction *DynamicallyReplacedFunction = nullptr;
7291
54.6k
  SILFunction *AdHocWitnessFunction = nullptr;
7292
54.6k
  Identifier objCReplacementFor;
7293
54.6k
  if (parseSILLinkage(FnLinkage, P) ||
7294
54.6k
      parseDeclSILOptional(
7295
54.6k
          &isTransparent, &isSerialized, &isCanonical, &hasOwnershipSSA,
7296
54.6k
          &isThunk, &isDynamic, &isDistributed, &isRuntimeAccessible,
7297
54.6k
          &forceEnableLexicalLifetimes, &useStackForPackMetadata,
7298
54.6k
          &hasUnsafeNonEscapableResult,
7299
54.6k
          &isExactSelfClass, &DynamicallyReplacedFunction,
7300
54.6k
          &AdHocWitnessFunction, &objCReplacementFor, &specialPurpose,
7301
54.6k
          &inlineStrategy, &optimizationMode, &perfConstr, &markedAsUsed,
7302
54.6k
          &section, nullptr, &isWeakImported, &needStackProtection,
7303
54.6k
          &availability, &isWithoutActuallyEscapingThunk, &Semantics,
7304
54.6k
          &SpecAttrs, &ClangDecl, &MRK, FunctionState, M) ||
7305
54.6k
      P.parseToken(tok::at_sign, diag::expected_sil_function_name) ||
7306
54.6k
      P.parseIdentifier(FnName, FnNameLoc, /*diagnoseDollarPrefix=*/false,
7307
54.6k
                        diag::expected_sil_function_name) ||
7308
54.6k
      P.parseToken(tok::colon, diag::expected_sil_type))
7309
0
    return true;
7310
54.6k
  {
7311
    // Construct a Scope for the function body so TypeAliasDecl can be added to
7312
    // the scope.
7313
54.6k
    GenericSignature GenericSig;
7314
54.6k
    GenericParamList *GenericParams = nullptr;
7315
54.6k
    if (FunctionState.parseSILType(FnType, GenericSig, GenericParams,
7316
54.6k
                                   true /*IsFuncDecl*/))
7317
33
      return true;
7318
54.6k
    auto SILFnType = FnType.getAs<SILFunctionType>();
7319
54.6k
    if (!SILFnType || !FnType.isObject()) {
7320
0
      P.diagnose(FnNameLoc, diag::expected_sil_function_type);
7321
0
      return true;
7322
0
    }
7323
  
7324
54.6k
    FunctionState.F =
7325
54.6k
      FunctionState.getGlobalNameForDefinition(FnName, SILFnType, FnNameLoc);
7326
54.6k
    FunctionState.F->setBare(IsBare);
7327
54.6k
    FunctionState.F->setTransparent(IsTransparent_t(isTransparent));
7328
54.6k
    FunctionState.F->setSerialized(IsSerialized_t(isSerialized));
7329
54.6k
    FunctionState.F->setWasDeserializedCanonical(isCanonical);
7330
54.6k
    if (!hasOwnershipSSA)
7331
31.9k
      FunctionState.F->setOwnershipEliminated();
7332
54.6k
    FunctionState.F->setThunk(IsThunk_t(isThunk));
7333
54.6k
    FunctionState.F->setIsDynamic(isDynamic);
7334
54.6k
    FunctionState.F->setIsDistributed(isDistributed);
7335
54.6k
    FunctionState.F->setIsRuntimeAccessible(isRuntimeAccessible);
7336
54.6k
    FunctionState.F->setForceEnableLexicalLifetimes(
7337
54.6k
        forceEnableLexicalLifetimes);
7338
54.6k
    FunctionState.F->setUseStackForPackMetadata(useStackForPackMetadata);
7339
54.6k
    FunctionState.F->setHasUnsafeNonEscapableResult(
7340
54.6k
      hasUnsafeNonEscapableResult);
7341
54.6k
    FunctionState.F->setIsExactSelfClass(isExactSelfClass);
7342
54.6k
    FunctionState.F->setDynamicallyReplacedFunction(
7343
54.6k
        DynamicallyReplacedFunction);
7344
54.6k
    FunctionState.F->setReferencedAdHocRequirementWitnessFunction(
7345
54.6k
        AdHocWitnessFunction);
7346
54.6k
    if (!objCReplacementFor.empty())
7347
0
      FunctionState.F->setObjCReplacement(objCReplacementFor);
7348
54.6k
    FunctionState.F->setSpecialPurpose(specialPurpose);
7349
54.6k
    FunctionState.F->setIsAlwaysWeakImported(isWeakImported);
7350
54.6k
    FunctionState.F->setAvailabilityForLinkage(availability);
7351
54.6k
    FunctionState.F->setWithoutActuallyEscapingThunk(
7352
54.6k
      isWithoutActuallyEscapingThunk);
7353
54.6k
    FunctionState.F->setInlineStrategy(inlineStrategy);
7354
54.6k
    FunctionState.F->setOptimizationMode(optimizationMode);
7355
54.6k
    FunctionState.F->setPerfConstraints(perfConstr);
7356
54.6k
    FunctionState.F->setEffectsKind(MRK);
7357
7358
54.6k
    if (ClangDecl)
7359
30
      FunctionState.F->setClangNodeOwner(ClangDecl);
7360
54.6k
    for (auto &Attr : Semantics) {
7361
2.85k
      FunctionState.F->addSemanticsAttr(Attr);
7362
2.85k
    }
7363
    // Now that we have a SILFunction parse the body, if present.
7364
7365
54.6k
    bool isDefinition = false;
7366
54.6k
    SourceLoc LBraceLoc = P.Tok.getLoc();
7367
7368
54.6k
    if (P.consumeIf(tok::l_brace)) {
7369
43.6k
      while (P.consumeIf(tok::l_square)) {
7370
426
        SourceLoc effectsStart = P.Tok.getLoc();
7371
5.08k
        while (P.Tok.isNot(tok::r_square, tok::eof)) {
7372
4.66k
          P.consumeToken();
7373
4.66k
        }
7374
426
        SourceLoc effectsEnd = P.Tok.getLoc();
7375
426
        P.consumeToken();
7376
426
        StringRef effectsStr = P.SourceMgr.extractText(
7377
426
                      CharSourceRange(P.SourceMgr, effectsStart, effectsEnd));
7378
7379
426
        auto error = FunctionState.F->parseMultipleEffectsFromSIL(effectsStr);
7380
426
        if (error.first) {
7381
0
          SourceLoc loc = effectsStart;
7382
0
          if (loc.isValid())
7383
0
            loc = loc.getAdvancedLoc(error.second);
7384
0
          P.diagnose(loc, diag::error_in_effects_attribute, StringRef(error.first));
7385
0
          return true;
7386
0
        }
7387
426
      }
7388
43.2k
      if (!P.consumeIf(tok::r_brace)) {
7389
43.0k
        isDefinition = true;
7390
7391
43.0k
        FunctionState.ContextGenericSig = GenericSig;
7392
43.0k
        FunctionState.ContextGenericParams = GenericParams;
7393
43.0k
        FunctionState.F->setGenericEnvironment(GenericSig.getGenericEnvironment());
7394
7395
43.0k
        if (GenericSig && !SpecAttrs.empty()) {
7396
456
          for (auto &Attr : SpecAttrs) {
7397
456
            SmallVector<Requirement, 2> requirements;
7398
456
            SmallVector<Type, 2> typeErasedParams;
7399
            // Resolve types and convert requirements.
7400
456
            FunctionState.convertRequirements(Attr.requirements, requirements, typeErasedParams);
7401
456
            auto *fenv = FunctionState.F->getGenericEnvironment();
7402
456
            auto genericSig = buildGenericSignature(P.Context,
7403
456
                                                    fenv->getGenericSignature(),
7404
456
                                                    /*addedGenericParams=*/{ },
7405
456
                                                    std::move(requirements));
7406
456
            FunctionState.F->addSpecializeAttr(SILSpecializeAttr::create(
7407
456
                FunctionState.F->getModule(), genericSig, typeErasedParams, Attr.exported,
7408
456
                Attr.kind, Attr.target, Attr.spiGroupID, Attr.spiModule, Attr.availability));
7409
456
          }
7410
366
        }
7411
7412
        // Parse the basic block list.
7413
43.0k
        SILBuilder B(*FunctionState.F);
7414
7415
237k
        do {
7416
237k
          if (FunctionState.parseSILBasicBlock(B))
7417
45
            return true;
7418
237k
        } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof));
7419
7420
        // OSSA uses flags to represent "reborrow", "escaping" etc.
7421
        // These flags are populated here as a shortcut to rewriting all
7422
        // existing OSSA tests with flags.
7423
43.0k
        if (!DisablePopulateOwnershipFlags) {
7424
43.0k
          populateOwnershipFlags(FunctionState.F);
7425
43.0k
        }
7426
7427
43.0k
        SourceLoc RBraceLoc;
7428
43.0k
        P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
7429
43.0k
                             LBraceLoc);
7430
7431
        // Check that there are no unresolved forward definitions of local
7432
        // archetypes.
7433
43.0k
        if (M.hasUnresolvedLocalArchetypeDefinitions())
7434
0
          llvm_unreachable(
7435
43.0k
              "All forward definitions of local archetypes should be resolved");
7436
43.0k
      }
7437
43.2k
    }
7438
7439
54.5k
    FunctionState.F->setLinkage(resolveSILLinkage(FnLinkage, isDefinition));
7440
54.5k
  }
7441
7442
54.5k
  if (FunctionState.diagnoseProblems())
7443
12
    return true;
7444
7445
54.5k
  return false;
7446
54.5k
}
7447
7448
///   decl-sil-stage:   [[only in SIL mode]]
7449
///     'sil_stage' ('raw' | 'canonical')
7450
2.51k
bool SILParserState::parseDeclSILStage(Parser &P) {
7451
2.51k
  SourceLoc stageLoc = P.consumeToken(tok::kw_sil_stage);
7452
2.51k
  if (!P.Tok.is(tok::identifier)) {
7453
0
    P.diagnose(P.Tok, diag::expected_sil_stage_name);
7454
0
    return true;
7455
0
  }
7456
2.51k
  SILStage stage;
7457
2.51k
  if (P.Tok.isContextualKeyword("raw")) {
7458
723
    stage = SILStage::Raw;
7459
723
    P.consumeToken();
7460
1.79k
  } else if (P.Tok.isContextualKeyword("canonical")) {
7461
1.78k
    stage = SILStage::Canonical;
7462
1.78k
    P.consumeToken();
7463
1.78k
  } else if (P.Tok.isContextualKeyword("lowered")) {
7464
9
    stage = SILStage::Lowered;
7465
9
    P.consumeToken();
7466
9
  } else {
7467
3
    P.diagnose(P.Tok, diag::expected_sil_stage_name);
7468
3
    P.consumeToken();
7469
3
    return true;
7470
3
  }
7471
  
7472
2.51k
  if (DidParseSILStage) {
7473
3
    P.diagnose(stageLoc, diag::multiple_sil_stage_decls);
7474
3
    return false;
7475
3
  }
7476
  
7477
2.51k
  M.setStage(stage);
7478
2.51k
  if (M.getOptions().EnableSILOpaqueValues) {
7479
45
    M.setLoweredAddresses(stage != SILStage::Raw);
7480
45
  }
7481
2.51k
  DidParseSILStage = true;
7482
2.51k
  return false;
7483
2.51k
}
7484
7485
/// Lookup a global variable declaration from its demangled name.
7486
///
7487
/// A variable declaration exists for all sil_global variables defined in
7488
/// Swift. A Swift global defined outside this module will be exposed
7489
/// via an addressor rather than as a sil_global. Globals imported
7490
/// from clang will produce a sil_global but will not have any corresponding
7491
/// VarDecl.
7492
///
7493
/// FIXME: lookupGlobalDecl() can handle collisions between private or
7494
/// fileprivate global variables in the same SIL Module, but the typechecker
7495
/// will still incorrectly diagnose this as an "invalid redeclaration" and give
7496
/// all but the first declaration an error type.
7497
static llvm::Optional<VarDecl *> lookupGlobalDecl(Identifier GlobalName,
7498
                                                  SILLinkage GlobalLinkage,
7499
                                                  SILType GlobalType,
7500
825
                                                  Parser &P) {
7501
  // Create a set of DemangleOptions to produce the global variable's
7502
  // identifier, which is used as a search key in the declaration context.
7503
825
  Demangle::DemangleOptions demangleOpts;
7504
825
  demangleOpts.QualifyEntities = false;
7505
825
  demangleOpts.ShowPrivateDiscriminators = false;
7506
825
  demangleOpts.DisplayEntityTypes = false;
7507
825
  std::string GlobalDeclName = Demangle::demangleSymbolAsString(
7508
825
    GlobalName.str(), demangleOpts);
7509
7510
825
  SmallVector<ValueDecl *, 4> CurModuleResults;
7511
825
  P.SF.getParentModule()->lookupValue(
7512
825
      P.Context.getIdentifier(GlobalDeclName), NLKind::UnqualifiedLookup,
7513
825
      CurModuleResults);
7514
  // Bail-out on clang-imported globals.
7515
825
  if (CurModuleResults.empty())
7516
720
    return nullptr;
7517
7518
  // private and fileprivate globals of the same name may be merged into a
7519
  // single SIL module. Find the declaration with the correct type and
7520
  // linkage. (If multiple globals have the same type and linkage then it
7521
  // doesn't matter which declaration we use).
7522
105
  for (ValueDecl *ValDecl : CurModuleResults) {
7523
105
    auto *VD = cast<VarDecl>(ValDecl);
7524
105
    CanType DeclTy = VD->getTypeInContext()->getCanonicalType();
7525
105
    if (DeclTy == GlobalType.getASTType()
7526
105
        && getDeclSILLinkage(VD) == GlobalLinkage) {
7527
105
      return VD;
7528
105
    }
7529
105
  }
7530
0
  return llvm::None;
7531
105
}
7532
7533
/// decl-sil-global: [[only in SIL mode]]
7534
///   'sil_global' sil-linkage @name : sil-type [external]
7535
825
bool SILParserState::parseSILGlobal(Parser &P) {
7536
  // Inform the lexer that we're lexing the body of the SIL declaration.
7537
825
  Lexer::SILBodyRAII Tmp(*P.L);
7538
7539
825
  P.consumeToken(tok::kw_sil_global);
7540
825
  llvm::Optional<SILLinkage> GlobalLinkage;
7541
825
  Identifier GlobalName;
7542
825
  SILType GlobalType;
7543
825
  SourceLoc NameLoc;
7544
825
  IsSerialized_t isSerialized = IsNotSerialized;
7545
825
  bool isLet = false;
7546
7547
825
  SILParser State(P);
7548
825
  if (parseSILLinkage(GlobalLinkage, P) ||
7549
825
      parseDeclSILOptional(nullptr, &isSerialized, nullptr, nullptr, nullptr,
7550
825
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7551
825
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7552
825
                           nullptr, nullptr, nullptr, nullptr, &isLet, nullptr,
7553
825
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7554
825
                           nullptr, State, M) ||
7555
825
      P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
7556
825
      P.parseIdentifier(GlobalName, NameLoc, /*diagnoseDollarPrefix=*/false,
7557
825
                        diag::expected_sil_value_name) ||
7558
825
      P.parseToken(tok::colon, diag::expected_sil_type))
7559
0
    return true;
7560
7561
825
  if (State.parseSILType(GlobalType))
7562
0
    return true;
7563
7564
  // Non-external global variables are definitions by default.
7565
825
  if (!GlobalLinkage.has_value())
7566
477
    GlobalLinkage = SILLinkage::DefaultForDefinition;
7567
7568
  // Lookup the global variable declaration for this sil_global.
7569
825
  auto VD =
7570
825
      lookupGlobalDecl(GlobalName, GlobalLinkage.value(), GlobalType, P);
7571
825
  if (!VD) {
7572
0
    P.diagnose(NameLoc, diag::sil_global_variable_not_found, GlobalName);
7573
0
    return true;
7574
0
  }
7575
825
  auto *GV = SILGlobalVariable::create(
7576
825
      M, GlobalLinkage.value(), isSerialized, GlobalName.str(), GlobalType,
7577
825
      RegularLocation(NameLoc), VD.value());
7578
7579
825
  GV->setLet(isLet);
7580
  // Parse static initializer if exists.
7581
825
  if (State.P.consumeIf(tok::equal) && State.P.consumeIf(tok::l_brace)) {
7582
171
    SILBuilder B(GV);
7583
543
    do {
7584
543
      State.parseSILInstruction(B);
7585
543
    } while (! State.P.consumeIf(tok::r_brace));
7586
171
  }
7587
825
  return false;
7588
825
}
7589
7590
/// decl-sil-property: [[only in SIL mode]]
7591
///   'sil_property' sil-decl-ref '(' sil-key-path-pattern-component ')'
7592
7593
90
bool SILParserState::parseSILProperty(Parser &P) {
7594
90
  Lexer::SILBodyRAII Tmp(*P.L);
7595
7596
90
  auto loc = P.consumeToken(tok::kw_sil_property);
7597
90
  auto InstLoc = RegularLocation(loc);
7598
90
  SILParser SP(P);
7599
  
7600
90
  IsSerialized_t Serialized = IsNotSerialized;
7601
90
  if (parseDeclSILOptional(nullptr, &Serialized, nullptr, nullptr, nullptr,
7602
90
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7603
90
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7604
90
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7605
90
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7606
90
                           nullptr, SP, M))
7607
0
    return true;
7608
  
7609
90
  ValueDecl *VD;
7610
  
7611
90
  if (SP.parseSILDottedPath(VD))
7612
0
    return true;
7613
  
7614
90
  GenericParamList *patternParams;
7615
90
  patternParams = P.maybeParseGenericParams().getPtrOrNull();
7616
90
  auto patternSig = handleSILGenericParams(patternParams, &P.SF);
7617
7618
90
  if (patternSig) {
7619
48
    if (patternSig.getCanonicalSignature() !=
7620
48
        VD->getInnermostDeclContext()
7621
48
            ->getGenericSignatureOfContext()
7622
48
            .getCanonicalSignature()) {
7623
0
      P.diagnose(loc, diag::sil_property_generic_signature_mismatch);
7624
0
      return true;
7625
0
    }
7626
48
  } else {
7627
42
    if (VD->getInnermostDeclContext()->getGenericSignatureOfContext()) {
7628
0
      P.diagnose(loc, diag::sil_property_generic_signature_mismatch);
7629
0
      return true;
7630
0
    }
7631
42
  }
7632
7633
90
  Identifier ComponentKind;
7634
90
  llvm::Optional<KeyPathPatternComponent> Component;
7635
90
  SourceLoc ComponentLoc;
7636
90
  SmallVector<SILType, 4> OperandTypes;
7637
7638
90
  if (P.parseToken(tok::l_paren, diag::expected_tok_in_sil_instr, "("))
7639
0
    return true;
7640
  
7641
90
  if (!P.consumeIf(tok::r_paren)) {
7642
54
    KeyPathPatternComponent parsedComponent;
7643
54
    if (P.parseIdentifier(ComponentKind, ComponentLoc,
7644
54
                          /*diagnoseDollarPrefix=*/false,
7645
54
                          diag::expected_tok_in_sil_instr, "component kind")
7646
54
        || SP.parseKeyPathPatternComponent(parsedComponent, OperandTypes,
7647
54
                 ComponentLoc, ComponentKind, InstLoc,
7648
54
                 patternSig, patternParams)
7649
54
        || P.parseToken(tok::r_paren, diag::expected_tok_in_sil_instr, ")"))
7650
0
      return true;
7651
    
7652
54
    Component = std::move(parsedComponent);
7653
54
  }
7654
  
7655
90
  SILProperty::create(M, Serialized,
7656
90
                      cast<AbstractStorageDecl>(VD), Component);
7657
90
  return false;
7658
90
}
7659
7660
/// decl-sil-vtable: [[only in SIL mode]]
7661
///   'sil_vtable' ClassName decl-sil-vtable-body
7662
/// decl-sil-vtable-body:
7663
///   '{' sil-vtable-entry* '}'
7664
/// sil-vtable-entry:
7665
///   SILDeclRef ':' SILFunctionName
7666
1.45k
bool SILParserState::parseSILVTable(Parser &P) {
7667
1.45k
  P.consumeToken(tok::kw_sil_vtable);
7668
1.45k
  SILParser VTableState(P);
7669
7670
1.45k
  IsSerialized_t Serialized = IsNotSerialized;
7671
1.45k
  if (parseDeclSILOptional(nullptr, &Serialized, nullptr, nullptr, nullptr,
7672
1.45k
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7673
1.45k
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7674
1.45k
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7675
1.45k
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7676
1.45k
                           nullptr, VTableState, M))
7677
0
    return true;
7678
7679
  // Parse the class name.
7680
1.45k
  Identifier Name;
7681
1.45k
  SourceLoc Loc;
7682
1.45k
  if (VTableState.parseSILIdentifier(Name, Loc,
7683
1.45k
                                     diag::expected_sil_value_name))
7684
0
    return true;
7685
7686
  // Find the class decl.
7687
1.45k
  llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res =
7688
1.45k
    lookupTopDecl(P, Name, /*typeLookup=*/true);
7689
1.45k
  assert(Res.is<ValueDecl*>() && "Class look-up should return a Decl");
7690
0
  ValueDecl *VD = Res.get<ValueDecl*>();
7691
1.45k
  if (!VD) {
7692
0
    P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
7693
0
    return true;
7694
0
  }
7695
7696
1.45k
  auto *theClass = dyn_cast<ClassDecl>(VD);
7697
1.45k
  if (!theClass) {
7698
0
    P.diagnose(Loc, diag::sil_vtable_class_not_found, Name);
7699
0
    return true;
7700
0
  }
7701
7702
1.45k
  SourceLoc LBraceLoc = P.Tok.getLoc();
7703
1.45k
  P.consumeToken(tok::l_brace);
7704
7705
  // We need to turn on InSILBody to parse SILDeclRef.
7706
1.45k
  Lexer::SILBodyRAII Tmp(*P.L);
7707
  // Parse the entry list.
7708
1.45k
  std::vector<SILVTable::Entry> vtableEntries;
7709
1.45k
  if (P.Tok.isNot(tok::r_brace)) {
7710
2.10k
    do {
7711
2.10k
      SILDeclRef Ref;
7712
2.10k
      Identifier FuncName;
7713
2.10k
      SourceLoc FuncLoc;
7714
2.10k
      if (VTableState.parseSILDeclRef(Ref, true))
7715
0
        return true;
7716
2.10k
      SILFunction *Func = nullptr;
7717
2.10k
      if (P.Tok.is(tok::kw_nil)) {
7718
0
        P.consumeToken();
7719
2.10k
      } else {
7720
2.10k
        if (P.parseToken(tok::colon, diag::expected_sil_vtable_colon) ||
7721
2.10k
            P.parseToken(tok::at_sign, diag::expected_sil_function_name) ||
7722
2.10k
            VTableState.parseSILIdentifier(FuncName, FuncLoc,
7723
2.10k
                                           diag::expected_sil_value_name))
7724
0
        return true;
7725
2.10k
        Func = M.lookUpFunction(FuncName.str());
7726
2.10k
        if (!Func) {
7727
0
          P.diagnose(FuncLoc, diag::sil_vtable_func_not_found, FuncName);
7728
0
          return true;
7729
0
        }
7730
2.10k
      }
7731
7732
2.10k
      auto Kind = SILVTable::Entry::Kind::Normal;
7733
2.10k
      bool NonOverridden = false;
7734
2.88k
      while (P.Tok.is(tok::l_square)) {
7735
780
        P.consumeToken(tok::l_square);
7736
780
        if (P.Tok.isNot(tok::identifier)) {
7737
0
          P.diagnose(P.Tok.getLoc(), diag::sil_vtable_bad_entry_kind);
7738
0
          return true;
7739
0
        }
7740
7741
780
        if (P.Tok.getText() == "override") {
7742
495
          P.consumeToken();
7743
495
          Kind = SILVTable::Entry::Kind::Override;
7744
495
        } else if (P.Tok.getText() == "inherited") {
7745
177
          P.consumeToken();
7746
177
          Kind = SILVTable::Entry::Kind::Inherited;
7747
177
        } else if (P.Tok.getText() == "nonoverridden") {
7748
108
          P.consumeToken();
7749
108
          NonOverridden = true;
7750
108
        } else {
7751
0
          P.diagnose(P.Tok.getLoc(), diag::sil_vtable_bad_entry_kind);
7752
0
          return true;
7753
0
        }
7754
7755
780
        if (P.parseToken(tok::r_square, diag::sil_vtable_expect_rsquare))
7756
0
          return true;
7757
780
      }
7758
7759
2.10k
      vtableEntries.emplace_back(Ref, Func, Kind, NonOverridden);
7760
2.10k
    } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof));
7761
876
  }
7762
7763
1.45k
  SourceLoc RBraceLoc;
7764
1.45k
  P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
7765
1.45k
                       LBraceLoc);
7766
7767
1.45k
  SILVTable::create(M, theClass, Serialized, vtableEntries);
7768
1.45k
  return false;
7769
1.45k
}
7770
7771
/// decl-sil-vtable: [[only in SIL mode]]
7772
///   'sil_vtable' ClassName decl-sil-vtable-body
7773
/// decl-sil-vtable-body:
7774
///   '{' sil-vtable-entry* '}'
7775
/// sil-vtable-entry:
7776
///   SILDeclRef ':' SILFunctionName
7777
57
bool SILParserState::parseSILMoveOnlyDeinit(Parser &parser) {
7778
57
  parser.consumeToken(tok::kw_sil_moveonlydeinit);
7779
57
  SILParser moveOnlyDeinitTableState(parser);
7780
7781
57
  IsSerialized_t Serialized = IsNotSerialized;
7782
57
  if (parseDeclSILOptional(nullptr, &Serialized, nullptr, nullptr, nullptr,
7783
57
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7784
57
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7785
57
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7786
57
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
7787
57
                           nullptr, moveOnlyDeinitTableState, M))
7788
0
    return true;
7789
7790
  // Parse the class name.
7791
57
  Identifier name;
7792
57
  SourceLoc loc;
7793
57
  if (moveOnlyDeinitTableState.parseSILIdentifier(
7794
57
          name, loc, diag::expected_sil_value_name))
7795
0
    return true;
7796
7797
  // Find the nominal decl.
7798
57
  llvm::PointerUnion<ValueDecl *, ModuleDecl *> res =
7799
57
      lookupTopDecl(parser, name, /*typeLookup=*/true);
7800
57
  assert(res.is<ValueDecl *>() && "Class Nominal-up should return a Decl");
7801
0
  ValueDecl *varDecl = res.get<ValueDecl *>();
7802
57
  if (!varDecl) {
7803
0
    parser.diagnose(loc, diag::sil_moveonlydeinit_nominal_not_found, name);
7804
0
    return true;
7805
0
  }
7806
7807
57
  auto *theNominalDecl = dyn_cast<NominalTypeDecl>(varDecl);
7808
57
  if (!theNominalDecl) {
7809
0
    parser.diagnose(loc, diag::sil_moveonlydeinit_nominal_not_found, name);
7810
0
    return true;
7811
0
  }
7812
7813
57
  SourceLoc lBraceLoc = parser.Tok.getLoc();
7814
57
  parser.consumeToken(tok::l_brace);
7815
7816
  // We need to turn on InSILBody to parse SILDeclRef.
7817
57
  Lexer::SILBodyRAII tmp(*parser.L);
7818
57
  SILFunction *func = nullptr;
7819
7820
57
  if (parser.Tok.isNot(tok::r_brace)) {
7821
57
    Identifier funcName;
7822
57
    SourceLoc funcLoc;
7823
57
    if (parser.Tok.is(tok::kw_nil)) {
7824
0
      parser.consumeToken();
7825
57
    } else {
7826
57
      if (parser.parseToken(tok::at_sign, diag::expected_sil_function_name) ||
7827
57
          moveOnlyDeinitTableState.parseSILIdentifier(
7828
57
              funcName, funcLoc, diag::expected_sil_value_name))
7829
0
        return true;
7830
57
      func = M.lookUpFunction(funcName.str());
7831
57
      if (!func) {
7832
0
        parser.diagnose(funcLoc, diag::sil_moveonlydeinit_func_not_found,
7833
0
                        funcName);
7834
0
        return true;
7835
0
      }
7836
57
    }
7837
57
  }
7838
7839
57
  SourceLoc RBraceLoc;
7840
57
  parser.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
7841
57
                            lBraceLoc);
7842
7843
57
  SILMoveOnlyDeinit::create(M, theNominalDecl, Serialized, func);
7844
57
  return false;
7845
57
}
7846
7847
1.01k
static ProtocolDecl *parseProtocolDecl(Parser &P, SILParser &SP) {
7848
1.01k
  Identifier DeclName;
7849
1.01k
  SourceLoc DeclLoc;
7850
1.01k
  if (SP.parseSILIdentifier(DeclName, DeclLoc, diag::expected_sil_value_name))
7851
0
    return nullptr;
7852
7853
  // Find the protocol decl. The protocol can be imported.
7854
1.01k
  llvm::PointerUnion<ValueDecl*, ModuleDecl *> Res =
7855
1.01k
    lookupTopDecl(P, DeclName, /*typeLookup=*/true);
7856
1.01k
  assert(Res.is<ValueDecl*>() && "Protocol look-up should return a Decl");
7857
0
  ValueDecl *VD = Res.get<ValueDecl*>();
7858
1.01k
  if (!VD) {
7859
0
    P.diagnose(DeclLoc, diag::sil_witness_protocol_not_found, DeclName);
7860
0
    return nullptr;
7861
0
  }
7862
1.01k
  auto *proto = dyn_cast<ProtocolDecl>(VD);
7863
1.01k
  if (!proto)
7864
0
    P.diagnose(DeclLoc, diag::sil_witness_protocol_not_found, DeclName);
7865
1.01k
  return proto;
7866
1.01k
}
7867
7868
static AssociatedTypeDecl *parseAssociatedTypeDecl(Parser &P, SILParser &SP,
7869
92
                                                   ProtocolDecl *proto) {
7870
92
  Identifier DeclName;
7871
92
  SourceLoc DeclLoc;
7872
92
  if (SP.parseSILIdentifier(DeclName, DeclLoc, diag::expected_sil_value_name))
7873
0
    return nullptr;
7874
  // We can return multiple decls, for now, we use the first lookup result.
7875
  // One example is two decls when searching for Generator of Sequence:
7876
  // one from Sequence, the other from _Sequence_Type.
7877
92
  SmallVector<ValueDecl *, 4> values;
7878
92
  auto VD = lookupMember(P, proto->getInterfaceType(), DeclName, DeclLoc,
7879
92
                         values, true/*ExpectMultipleResults*/);
7880
92
  if (!VD) {
7881
0
    P.diagnose(DeclLoc, diag::sil_witness_assoc_not_found, DeclName);
7882
0
    return nullptr;
7883
0
  }
7884
92
  return dyn_cast<AssociatedTypeDecl>(VD);
7885
92
}
7886
7887
static bool parseAssociatedTypePath(SILParser &SP,
7888
58
                                    SmallVectorImpl<Identifier> &path) {
7889
58
  do {
7890
58
    Identifier name;
7891
58
    SourceLoc loc;
7892
58
    if (SP.parseSILIdentifier(name, loc, diag::expected_sil_value_name))
7893
0
      return false;
7894
58
    path.push_back(name);
7895
58
  } while (SP.P.consumeIf(tok::period));
7896
7897
58
  return true;
7898
58
}
7899
7900
static bool matchesAssociatedTypePath(CanType assocType,
7901
116
                                      ArrayRef<Identifier> path) {
7902
116
  if (auto memberType = dyn_cast<DependentMemberType>(assocType)) {
7903
58
    return (!path.empty() &&
7904
58
            memberType->getName() == path.back() &&
7905
58
            matchesAssociatedTypePath(memberType.getBase(), path.drop_back()));
7906
58
  } else {
7907
58
    assert(isa<GenericTypeParamType>(assocType));
7908
0
    return path.empty();
7909
58
  }
7910
116
}
7911
7912
static CanType parseAssociatedTypePath(Parser &P, SILParser &SP,
7913
58
                                       ProtocolDecl *proto) {
7914
58
  SourceLoc loc = SP.P.Tok.getLoc();
7915
58
  SmallVector<Identifier, 4> path;
7916
58
  if (!parseAssociatedTypePath(SP, path))
7917
0
    return CanType();
7918
7919
  // This is only used for parsing associated conformances, so we can
7920
  // go ahead and just search the requirement signature for something that
7921
  // matches the path.
7922
58
  for (auto &reqt : proto->getRequirementSignature().getRequirements()) {
7923
58
    if (reqt.getKind() != RequirementKind::Conformance)
7924
0
      continue;
7925
58
    CanType assocType = reqt.getFirstType()->getCanonicalType();
7926
58
    if (matchesAssociatedTypePath(assocType, path))
7927
58
      return assocType;
7928
58
  }
7929
7930
0
  SmallString<128> name;
7931
0
  name += path[0].str();
7932
0
  for (auto elt : makeArrayRef(path).slice(1)) {
7933
0
    name += '.';
7934
0
    name += elt.str();
7935
0
  }
7936
0
  P.diagnose(loc, diag::sil_witness_assoc_conf_not_found, name);
7937
0
  return CanType();
7938
58
}
7939
7940
static ProtocolConformanceRef
7941
parseRootProtocolConformance(Parser &P, SILParser &SP, Type ConformingTy,
7942
774
                             ProtocolDecl *&proto) {
7943
774
  const StringRef ModuleKeyword = "module";
7944
774
  Identifier ModuleName;
7945
774
  SourceLoc Loc, KeywordLoc;
7946
774
  proto = parseProtocolDecl(P, SP);
7947
774
  if (!proto)
7948
0
    return ProtocolConformanceRef();
7949
7950
774
  if (P.parseSpecificIdentifier(
7951
774
          ModuleKeyword, KeywordLoc,
7952
774
          Diagnostic(diag::expected_tok_in_sil_instr, ModuleKeyword)) ||
7953
774
      SP.parseSILIdentifier(ModuleName, Loc, diag::expected_sil_value_name))
7954
0
    return ProtocolConformanceRef();
7955
7956
  // Calling lookupConformance on a BoundGenericType will return a specialized
7957
  // conformance. We use UnboundGenericType to find the normal conformance.
7958
774
  Type lookupTy = ConformingTy;
7959
774
  if (auto bound = lookupTy->getAs<BoundGenericType>())
7960
117
    lookupTy = bound->getDecl()->getDeclaredType();
7961
774
  auto lookup = P.SF.getParentModule()->lookupConformance(lookupTy, proto);
7962
774
  if (lookup.isInvalid()) {
7963
0
    P.diagnose(KeywordLoc, diag::sil_witness_protocol_conformance_not_found);
7964
0
    return ProtocolConformanceRef();
7965
0
  }
7966
7967
774
  return lookup;
7968
774
}
7969
7970
///  protocol-conformance ::= normal-protocol-conformance
7971
///  protocol-conformance ::=
7972
///    generic-parameter-list? type: 'inherit' '(' protocol-conformance ')'
7973
///  protocol-conformance ::=
7974
///    generic-parameter-list? type: 'specialize' '<' substitution* '>'
7975
///    '(' protocol-conformance ')'
7976
///  normal-protocol-conformance ::=
7977
///    generic-parameter-list? type: protocolName module ModuleName
7978
/// Note that generic-parameter-list is already parsed before calling this.
7979
ProtocolConformanceRef SILParser::parseProtocolConformance(
7980
    ProtocolDecl *&proto,
7981
    GenericSignature &genericSig,
7982
792
    GenericParamList *&genericParams) {
7983
  // Make sure we don't leave it uninitialized in the caller
7984
792
  genericSig = GenericSignature();
7985
7986
792
  genericParams = P.maybeParseGenericParams().getPtrOrNull();
7987
792
  if (genericParams) {
7988
117
    genericSig = handleSILGenericParams(genericParams, &P.SF);
7989
117
  }
7990
7991
792
  return parseProtocolConformanceHelper(proto, genericSig, genericParams);
7992
792
}
7993
7994
ProtocolConformanceRef SILParser::parseProtocolConformanceHelper(
7995
    ProtocolDecl *&proto,
7996
    GenericSignature witnessSig,
7997
792
    GenericParamList *witnessParams) {
7998
  // Parse AST type.
7999
792
  ParserResult<TypeRepr> TyR = P.parseType();
8000
792
  if (TyR.isNull())
8001
0
    return ProtocolConformanceRef();
8002
8003
792
  if (!witnessSig)
8004
675
    witnessSig = ContextGenericSig;
8005
792
  if (witnessParams == nullptr)
8006
675
    witnessParams = ContextGenericParams;
8007
8008
792
  auto ConformingTy = performTypeResolution(TyR.get(), /*IsSILType=*/false,
8009
792
                                            witnessSig, witnessParams);
8010
792
  if (witnessSig) {
8011
135
    ConformingTy = witnessSig.getGenericEnvironment()
8012
135
        ->mapTypeIntoContext(ConformingTy);
8013
135
  }
8014
8015
792
  if (ConformingTy->hasError())
8016
0
    return ProtocolConformanceRef();
8017
8018
792
  if (P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8019
0
    return ProtocolConformanceRef();
8020
8021
792
  if (P.Tok.is(tok::identifier) && P.Tok.getText() == "specialize") {
8022
18
    P.consumeToken();
8023
8024
    // Parse substitutions for specialized conformance.
8025
18
    SmallVector<ParsedSubstitution, 4> parsedSubs;
8026
18
    if (parseSubstitutions(parsedSubs, witnessSig, witnessParams))
8027
0
      return ProtocolConformanceRef();
8028
8029
18
    if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen))
8030
0
      return ProtocolConformanceRef();
8031
18
    ProtocolDecl *dummy;
8032
18
    GenericSignature specializedSig;
8033
18
    GenericParamList *specializedParams = nullptr;
8034
18
    auto genericConform =
8035
18
        parseProtocolConformance(dummy, specializedSig, specializedParams);
8036
18
    if (genericConform.isInvalid() || !genericConform.isConcrete())
8037
0
      return ProtocolConformanceRef();
8038
18
    if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen))
8039
0
      return ProtocolConformanceRef();
8040
8041
18
    SubstitutionMap subMap =
8042
18
      getApplySubstitutionsFromParsed(*this, specializedSig, parsedSubs);
8043
18
    if (!subMap)
8044
0
      return ProtocolConformanceRef();
8045
8046
18
    auto *rootConform = cast<RootProtocolConformance>(
8047
18
        genericConform.getConcrete());
8048
18
    auto result = P.Context.getSpecializedConformance(
8049
18
        ConformingTy, rootConform, subMap);
8050
18
    return ProtocolConformanceRef(result);
8051
18
  }
8052
8053
774
  if (P.Tok.is(tok::identifier) && P.Tok.getText() == "inherit") {
8054
0
    P.consumeToken();
8055
8056
0
    if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen))
8057
0
      return ProtocolConformanceRef();
8058
0
    auto baseConform = parseProtocolConformance();
8059
0
    if (baseConform.isInvalid() || !baseConform.isConcrete())
8060
0
      return ProtocolConformanceRef();
8061
0
    if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen))
8062
0
      return ProtocolConformanceRef();
8063
8064
0
    auto result = P.Context.getInheritedConformance(ConformingTy,
8065
0
                                                    baseConform.getConcrete());
8066
0
    return ProtocolConformanceRef(result);
8067
0
  }
8068
8069
774
  auto retVal =
8070
774
    parseRootProtocolConformance(P, *this, ConformingTy, proto);
8071
774
  return retVal;
8072
774
}
8073
8074
/// Parser a single SIL vtable entry and add it to either \p witnessEntries
8075
/// or \c conditionalConformances.
8076
static bool parseSILWitnessTableEntry(
8077
         Parser &P,
8078
         SILModule &M,
8079
         ProtocolDecl *proto,
8080
         GenericSignature witnessSig,
8081
         GenericParamList *witnessParams,
8082
         SILParser &witnessState,
8083
         std::vector<SILWitnessTable::Entry> &witnessEntries,
8084
         std::vector<SILWitnessTable::ConditionalConformance>
8085
1.05k
           &conditionalConformances) {
8086
1.05k
  Identifier EntryKeyword;
8087
1.05k
  SourceLoc KeywordLoc;
8088
1.05k
  if (P.parseIdentifier(EntryKeyword, KeywordLoc,
8089
1.05k
                        /*diagnoseDollarPrefix=*/false,
8090
1.05k
                        diag::expected_tok_in_sil_instr,
8091
1.05k
                        "method, associated_type, associated_type_protocol"
8092
1.05k
                        ", base_protocol, no_default"))
8093
0
    return true;
8094
8095
1.05k
  if (EntryKeyword.str() == "no_default") {
8096
111
    witnessEntries.push_back(SILDefaultWitnessTable::Entry());
8097
111
    return false;
8098
111
  }
8099
8100
939
  if (EntryKeyword.str() == "base_protocol") {
8101
46
    ProtocolDecl *proto = parseProtocolDecl(P, witnessState);
8102
46
    if (!proto)
8103
0
      return true;
8104
46
    if (P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8105
0
      return true;
8106
46
    auto conform =
8107
46
      witnessState.parseProtocolConformance();
8108
    // Ignore invalid and abstract witness entries.
8109
46
    if (conform.isInvalid() || !conform.isConcrete())
8110
0
      return false;
8111
8112
46
    witnessEntries.push_back(
8113
46
        SILWitnessTable::BaseProtocolWitness{proto, conform.getConcrete()});
8114
46
    return false;
8115
46
  }
8116
8117
893
  if (EntryKeyword.str() == "associated_type_protocol" ||
8118
893
      EntryKeyword.str() == "conditional_conformance") {
8119
67
    if (P.parseToken(tok::l_paren, diag::expected_sil_witness_lparen))
8120
0
      return true;
8121
67
    CanType assocOrSubject;
8122
67
    if (EntryKeyword.str() == "associated_type_protocol") {
8123
58
      assocOrSubject = parseAssociatedTypePath(P, witnessState, proto);
8124
58
    } else {
8125
      // Parse AST type.
8126
9
      ParserResult<TypeRepr> TyR = P.parseType();
8127
9
      if (TyR.isNull())
8128
0
        return true;
8129
8130
9
      SILTypeResolutionContext silContext(/*isSILType=*/false,
8131
9
                                          witnessParams,
8132
9
                                          /*openedPacks=*/nullptr);
8133
9
      auto Ty =
8134
9
          swift::performTypeResolution(TyR.get(), P.Context,
8135
9
                                       witnessSig, &silContext,
8136
9
                                       &P.SF);
8137
9
      if (witnessSig) {
8138
9
        Ty = witnessSig.getGenericEnvironment()->mapTypeIntoContext(Ty);
8139
9
      }
8140
8141
9
      if (Ty->hasError())
8142
0
        return true;
8143
8144
9
      assocOrSubject = Ty->getCanonicalType();
8145
9
    }
8146
67
    if (!assocOrSubject)
8147
0
      return true;
8148
67
    if (P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8149
0
      return true;
8150
67
    ProtocolDecl *proto = parseProtocolDecl(P, witnessState);
8151
67
    if (!proto)
8152
0
      return true;
8153
67
    if (P.parseToken(tok::r_paren, diag::expected_sil_witness_rparen) ||
8154
67
        P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8155
0
      return true;
8156
8157
67
    ProtocolConformanceRef conformance(proto);
8158
67
    if (P.Tok.getText() != "dependent") {
8159
58
      auto concrete =
8160
58
        witnessState.parseProtocolConformance();
8161
      // Ignore invalid and abstract witness entries.
8162
58
      if (concrete.isInvalid() || !concrete.isConcrete())
8163
0
        return false;
8164
58
      conformance = concrete;
8165
58
    } else {
8166
9
      P.consumeToken();
8167
9
    }
8168
8169
67
    if (EntryKeyword.str() == "associated_type_protocol")
8170
58
      witnessEntries.push_back(
8171
58
          SILWitnessTable::AssociatedTypeProtocolWitness{assocOrSubject,
8172
58
                                                         proto,
8173
58
                                                         conformance});
8174
9
    else
8175
9
      conditionalConformances.push_back(
8176
9
          SILWitnessTable::ConditionalConformance{assocOrSubject,
8177
9
                                                  conformance});
8178
8179
67
    return false;
8180
67
  }
8181
8182
826
  if (EntryKeyword.str() == "associated_type") {
8183
92
    AssociatedTypeDecl *assoc = parseAssociatedTypeDecl(P, witnessState,
8184
92
                                                        proto);
8185
92
    if (!assoc)
8186
0
      return true;
8187
92
    if (P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8188
0
      return true;
8189
8190
    // Parse AST type.
8191
92
    ParserResult<TypeRepr> TyR = P.parseType();
8192
92
    if (TyR.isNull())
8193
0
      return true;
8194
8195
92
    SILTypeResolutionContext silContext(/*isSILType=*/false,
8196
92
                                        witnessParams,
8197
92
                                        /*openedPacks=*/nullptr);
8198
92
    auto Ty =
8199
92
        swift::performTypeResolution(TyR.get(), P.Context,
8200
92
                                     witnessSig, &silContext,
8201
92
                                     &P.SF);
8202
92
    if (witnessSig) {
8203
42
      Ty = witnessSig.getGenericEnvironment()->mapTypeIntoContext(Ty);
8204
42
    }
8205
8206
92
    if (Ty->hasError())
8207
0
      return true;
8208
8209
92
    witnessEntries.push_back(
8210
92
        SILWitnessTable::AssociatedTypeWitness{assoc, Ty->getCanonicalType()});
8211
92
    return false;
8212
92
  }
8213
8214
734
  if (EntryKeyword.str() != "method") {
8215
0
    P.diagnose(KeywordLoc, diag::expected_tok_in_sil_instr, "method");
8216
0
    return true;
8217
0
  }
8218
8219
734
  SILDeclRef Ref;
8220
734
  Identifier FuncName;
8221
734
  SourceLoc FuncLoc;
8222
734
  if (witnessState.parseSILDeclRef(Ref, true) ||
8223
734
      P.parseToken(tok::colon, diag::expected_sil_witness_colon))
8224
0
    return true;
8225
8226
734
  SILFunction *Func = nullptr;
8227
734
  if (P.Tok.is(tok::kw_nil)) {
8228
21
    P.consumeToken();
8229
713
  } else {
8230
713
    if (P.parseToken(tok::at_sign, diag::expected_sil_function_name) ||
8231
713
        witnessState.parseSILIdentifier(FuncName, FuncLoc,
8232
713
                                        diag::expected_sil_value_name))
8233
0
      return true;
8234
8235
713
    Func = M.lookUpFunction(FuncName.str());
8236
713
    if (!Func) {
8237
0
      P.diagnose(FuncLoc, diag::sil_witness_func_not_found, FuncName);
8238
0
      return true;
8239
0
    }
8240
713
  }
8241
734
  witnessEntries.push_back(SILWitnessTable::MethodWitness{
8242
734
    Ref, Func
8243
734
  });
8244
8245
734
  return false;
8246
734
}
8247
8248
/// decl-sil-witness ::= 'sil_witness_table' sil-linkage?
8249
///                      normal-protocol-conformance decl-sil-witness-body
8250
/// normal-protocol-conformance ::=
8251
///   generic-parameter-list? type: protocolName module ModuleName
8252
/// decl-sil-witness-body:
8253
///   '{' sil-witness-entry* '}'
8254
/// sil-witness-entry:
8255
///   method SILDeclRef ':' @SILFunctionName
8256
///   associated_type AssociatedTypeDeclName: Type
8257
///   associated_type_protocol (AssocName: ProtocolName):
8258
///                              protocol-conformance|dependent
8259
///   base_protocol ProtocolName: protocol-conformance
8260
670
bool SILParserState::parseSILWitnessTable(Parser &P) {
8261
670
  P.consumeToken(tok::kw_sil_witness_table);
8262
670
  SILParser WitnessState(P);
8263
  
8264
  // Parse the linkage.
8265
670
  llvm::Optional<SILLinkage> Linkage;
8266
670
  parseSILLinkage(Linkage, P);
8267
  
8268
670
  IsSerialized_t isSerialized = IsNotSerialized;
8269
670
  if (parseDeclSILOptional(nullptr, &isSerialized, nullptr, nullptr, nullptr,
8270
670
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
8271
670
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
8272
670
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
8273
670
                           nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
8274
670
                           nullptr, WitnessState, M))
8275
0
    return true;
8276
8277
  // Parse the protocol conformance.
8278
670
  ProtocolDecl *proto;
8279
670
  GenericSignature witnessSig;
8280
670
  GenericParamList *witnessParams = nullptr;
8281
670
  auto conf = WitnessState.parseProtocolConformance(proto,
8282
670
                                                    witnessSig,
8283
670
                                                    witnessParams);
8284
670
  WitnessState.ContextGenericSig = witnessSig;
8285
670
  WitnessState.ContextGenericParams = witnessParams;
8286
8287
  // FIXME: should we really allow a specialized or inherited conformance here?
8288
670
  RootProtocolConformance *theConformance = nullptr;
8289
670
  if (conf.isConcrete())
8290
670
    theConformance = conf.getConcrete()->getRootConformance();
8291
8292
670
  SILWitnessTable *wt = nullptr;
8293
670
  if (theConformance) {
8294
670
    wt = M.lookUpWitnessTable(theConformance);
8295
670
    assert((!wt || wt->isDeclaration()) &&
8296
670
           "Attempting to create duplicate witness table.");
8297
670
  }
8298
8299
  // If we don't have an lbrace, then this witness table is a declaration.
8300
670
  if (P.Tok.getKind() != tok::l_brace) {
8301
    // Default to public external linkage.
8302
15
    if (!Linkage)
8303
6
      Linkage = SILLinkage::PublicExternal;
8304
    // We ignore empty witness table without normal protocol conformance.
8305
15
    if (!wt && theConformance)
8306
15
      wt = SILWitnessTable::create(M, *Linkage, theConformance);
8307
15
    return false;
8308
15
  }
8309
8310
655
  if (!theConformance) {
8311
0
    P.diagnose(P.Tok, diag::sil_witness_protocol_conformance_not_found);
8312
0
    return true;
8313
0
  }
8314
8315
655
  SourceLoc LBraceLoc = P.Tok.getLoc();
8316
655
  P.consumeToken(tok::l_brace);
8317
8318
  // We need to turn on InSILBody to parse SILDeclRef.
8319
655
  Lexer::SILBodyRAII Tmp(*P.L);
8320
  // Parse the entry list.
8321
655
  std::vector<SILWitnessTable::Entry> witnessEntries;
8322
655
  std::vector<SILWitnessTable::ConditionalConformance> conditionalConformances;
8323
8324
655
  if (P.Tok.isNot(tok::r_brace)) {
8325
846
    do {
8326
846
      if (parseSILWitnessTableEntry(P, M, proto, witnessSig, witnessParams,
8327
846
                                    WitnessState, witnessEntries,
8328
846
                                    conditionalConformances))
8329
0
        return true;
8330
846
    } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof));
8331
577
  }
8332
8333
655
  SourceLoc RBraceLoc;
8334
655
  P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
8335
655
                       LBraceLoc);
8336
  
8337
  // Default to public linkage.
8338
655
  if (!Linkage)
8339
337
    Linkage = SILLinkage::Public;
8340
8341
655
  if (!wt)
8342
652
    wt = SILWitnessTable::create(M, *Linkage, theConformance);
8343
3
  else
8344
3
    wt->setLinkage(*Linkage);
8345
655
  wt->convertToDefinition(witnessEntries, conditionalConformances,
8346
655
                          isSerialized);
8347
655
  return false;
8348
655
}
8349
8350
/// decl-sil-default-witness ::= 'sil_default_witness_table' 
8351
///                              sil-linkage identifier
8352
///                              decl-sil-default-witness-body
8353
/// decl-sil-default-witness-body:
8354
///   '{' sil-default-witness-entry* '}'
8355
/// sil-default-witness-entry:
8356
///   sil-witness-entry
8357
///   'no_default'
8358
126
bool SILParserState::parseSILDefaultWitnessTable(Parser &P) {
8359
126
  P.consumeToken(tok::kw_sil_default_witness_table);
8360
126
  SILParser WitnessState(P);
8361
  
8362
  // Parse the linkage.
8363
126
  llvm::Optional<SILLinkage> Linkage;
8364
126
  parseSILLinkage(Linkage, P);
8365
  
8366
  // Parse the protocol.
8367
126
  ProtocolDecl *protocol = parseProtocolDecl(P, WitnessState);
8368
126
  if (!protocol)
8369
0
    return true;
8370
8371
126
  WitnessState.ContextGenericSig = protocol->getGenericSignature();
8372
126
  WitnessState.ContextGenericParams = protocol->getGenericParams();
8373
8374
  // Parse the body.
8375
126
  SourceLoc LBraceLoc = P.Tok.getLoc();
8376
126
  P.consumeToken(tok::l_brace);
8377
8378
  // We need to turn on InSILBody to parse SILDeclRef.
8379
126
  Lexer::SILBodyRAII Tmp(*P.L);
8380
8381
  // Parse the entry list.
8382
126
  std::vector<SILWitnessTable::Entry> witnessEntries;
8383
126
  std::vector<SILWitnessTable::ConditionalConformance> conditionalConformances;
8384
8385
126
  if (P.Tok.isNot(tok::r_brace)) {
8386
204
    do {
8387
204
      if (parseSILWitnessTableEntry(P, M, protocol,
8388
204
                                    protocol->getGenericSignature(),
8389
204
                                    protocol->getGenericParams(),
8390
204
                                    WitnessState, witnessEntries,
8391
204
                                    conditionalConformances))
8392
0
        return true;
8393
204
    } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof));
8394
99
  }
8395
8396
126
  SourceLoc RBraceLoc;
8397
126
  P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
8398
126
                       LBraceLoc);
8399
  
8400
  // Default to public linkage.
8401
126
  if (!Linkage)
8402
57
    Linkage = SILLinkage::Public;
8403
8404
126
  SILDefaultWitnessTable::create(M, *Linkage, protocol, witnessEntries);
8405
126
  return false;
8406
126
}
8407
8408
/// decl-sil-differentiability-witness ::=
8409
///   'sil_differentiability_witness'
8410
///   ('[' 'serialized' ']')?
8411
///   sil-linkage?
8412
///   sil-differentiability-witness-config-and-function
8413
///   decl-sil-differentiability-witness-body?
8414
///
8415
/// decl-sil-differentiability-witness-body ::=
8416
///   '{'
8417
///   ('jvp' sil-function-name ':' sil-type)?
8418
///   ('vjp' sil-function-name ':' sil-type)?
8419
///   '}'
8420
///
8421
/// index-subset ::=
8422
///   [0-9]+ (' ' [0-9]+)*
8423
419
bool SILParserState::parseSILDifferentiabilityWitness(Parser &P) {
8424
419
  auto loc = P.consumeToken(tok::kw_sil_differentiability_witness);
8425
419
  auto silLoc = RegularLocation(loc);
8426
419
  SILParser State(P);
8427
8428
  // Parse the linkage.
8429
419
  llvm::Optional<SILLinkage> linkage;
8430
419
  if (parseSILLinkage(linkage, P))
8431
0
    return true;
8432
8433
  // Parse '[serialized]' flag (optional).
8434
419
  bool isSerialized = false;
8435
419
  SourceLoc serializedTokLoc;
8436
419
  if (P.Tok.is(tok::l_square) && P.isIdentifier(P.peekToken(), "serialized")) {
8437
52
    isSerialized = true;
8438
52
    serializedTokLoc = P.Tok.getLoc();
8439
52
    P.consumeToken(tok::l_square);
8440
52
    P.consumeToken(tok::identifier);
8441
52
    if (P.parseToken(tok::r_square, diag::sil_diff_witness_expected_token, "]"))
8442
0
      return true;
8443
52
  }
8444
8445
  // We need to turn on InSILBody to parse the function references.
8446
419
  Lexer::SILBodyRAII tmp(*P.L);
8447
8448
419
  DifferentiabilityKind kind;
8449
419
  AutoDiffConfig config;
8450
419
  SILFunction *originalFn;
8451
419
  if (parseSILDifferentiabilityWitnessConfigAndFunction(
8452
419
          P, State, silLoc, kind, config, originalFn))
8453
0
    return true;
8454
8455
  // If this is just a declaration, create the declaration now and return.
8456
419
  if (!P.Tok.is(tok::l_brace)) {
8457
252
    if (isSerialized) {
8458
0
      P.diagnose(serializedTokLoc,
8459
0
                 diag::sil_diff_witness_serialized_declaration);
8460
0
      return true;
8461
0
    }
8462
8463
252
    SILDifferentiabilityWitness::createDeclaration(
8464
252
        M, linkage ? *linkage : SILLinkage::DefaultForDeclaration, originalFn,
8465
252
        kind, config.parameterIndices, config.resultIndices,
8466
252
        config.derivativeGenericSignature);
8467
252
    return false;
8468
252
  }
8469
8470
  // This is a definition, so parse differentiability witness body.
8471
167
  SILFunction *jvp = nullptr;
8472
167
  SILFunction *vjp = nullptr;
8473
167
  if (P.Tok.is(tok::l_brace)) {
8474
    // Parse '{'.
8475
167
    SourceLoc lBraceLoc;
8476
167
    P.consumeIf(tok::l_brace, lBraceLoc);
8477
    // Parse JVP (optional).
8478
167
    if (P.isIdentifier(P.Tok, "jvp")) {
8479
104
      P.consumeToken(tok::identifier);
8480
104
      if (P.parseToken(tok::colon, diag::sil_diff_witness_expected_token, ":"))
8481
0
        return true;
8482
104
      if (State.parseSILFunctionRef(silLoc, jvp))
8483
0
        return true;
8484
104
    }
8485
    // Parse VJP (optional).
8486
167
    if (P.isIdentifier(P.Tok, "vjp")) {
8487
116
      P.consumeToken(tok::identifier);
8488
116
      if (P.parseToken(tok::colon, diag::sil_diff_witness_expected_token, ":"))
8489
0
        return true;
8490
116
      if (State.parseSILFunctionRef(silLoc, vjp))
8491
0
        return true;
8492
116
    }
8493
    // Parse '}'.
8494
167
    SourceLoc rBraceLoc;
8495
167
    if (P.parseMatchingToken(tok::r_brace, rBraceLoc, diag::expected_sil_rbrace,
8496
167
                             lBraceLoc))
8497
0
      return true;
8498
167
  }
8499
8500
167
  SILDifferentiabilityWitness::createDefinition(
8501
167
      M, linkage ? *linkage : SILLinkage::DefaultForDefinition, originalFn,
8502
167
      kind, config.parameterIndices, config.resultIndices,
8503
167
      config.derivativeGenericSignature, jvp, vjp, isSerialized);
8504
167
  return false;
8505
167
}
8506
8507
llvm::Optional<llvm::coverage::Counter> SILParser::parseSILCoverageExpr(
8508
114
    llvm::coverage::CounterExpressionBuilder &Builder) {
8509
114
  if (P.Tok.is(tok::integer_literal)) {
8510
72
    unsigned CounterId;
8511
72
    if (parseInteger(CounterId, diag::sil_coverage_invalid_counter))
8512
0
      return llvm::None;
8513
72
    return llvm::coverage::Counter::getCounter(CounterId);
8514
72
  }
8515
8516
42
  if (P.Tok.is(tok::identifier)) {
8517
9
    Identifier Zero;
8518
9
    SourceLoc Loc;
8519
9
    if (parseSILIdentifier(Zero, Loc, diag::sil_coverage_invalid_counter))
8520
0
      return llvm::None;
8521
9
    if (Zero.str() != "zero") {
8522
0
      P.diagnose(Loc, diag::sil_coverage_invalid_counter);
8523
0
      return llvm::None;
8524
0
    }
8525
9
    return llvm::coverage::Counter::getZero();
8526
9
  }
8527
8528
33
  if (P.Tok.is(tok::l_paren)) {
8529
33
    P.consumeToken(tok::l_paren);
8530
33
    auto LHS = parseSILCoverageExpr(Builder);
8531
33
    if (!LHS)
8532
0
      return llvm::None;
8533
33
    const Identifier Operator = P.Context.getIdentifier(P.Tok.getText());
8534
33
    const SourceLoc Loc = P.consumeToken();
8535
33
    if (Operator.str() != "+" && Operator.str() != "-") {
8536
0
      P.diagnose(Loc, diag::sil_coverage_invalid_operator);
8537
0
      return llvm::None;
8538
0
    }
8539
33
    auto RHS = parseSILCoverageExpr(Builder);
8540
33
    if (!RHS)
8541
0
      return llvm::None;
8542
33
    if (P.parseToken(tok::r_paren, diag::sil_coverage_expected_rparen))
8543
0
      return llvm::None;
8544
8545
33
    if (Operator.str() == "+")
8546
21
      return Builder.add(*LHS, *RHS);
8547
12
    return Builder.subtract(*LHS, *RHS);
8548
33
  }
8549
8550
0
  P.diagnose(P.Tok, diag::sil_coverage_invalid_counter);
8551
0
  return llvm::None;
8552
33
}
8553
8554
/// decl-sil-coverage-map ::= 'sil_coverage_map' CoveredName PGOFuncName CoverageHash
8555
///                           decl-sil-coverage-body
8556
/// decl-sil-coverage-body:
8557
///   '{' sil-coverage-entry* '}'
8558
/// sil-coverage-entry:
8559
///   sil-coverage-loc ':' sil-coverage-expr
8560
/// sil-coverage-loc:
8561
///   StartLine ':' StartCol '->' EndLine ':' EndCol
8562
/// sil-coverage-expr:
8563
///   ...
8564
24
bool SILParserState::parseSILCoverageMap(Parser &P) {
8565
24
  P.consumeToken(tok::kw_sil_coverage_map);
8566
24
  SILParser State(P);
8567
8568
  // Parse the filename.
8569
24
  Identifier Filename;
8570
24
  SourceLoc FileLoc;
8571
24
  if (State.parseSILIdentifier(Filename, FileLoc,
8572
24
                               diag::expected_sil_value_name))
8573
0
    return true;
8574
8575
  // Parse the covered name.
8576
24
  if (!P.Tok.is(tok::string_literal)) {
8577
0
    P.diagnose(P.Tok, diag::sil_coverage_expected_quote);
8578
0
    return true;
8579
0
  }
8580
24
  StringRef FuncName = P.Tok.getText().drop_front().drop_back();
8581
24
  P.consumeToken();
8582
8583
  // Parse the PGO func name.
8584
24
  if (!P.Tok.is(tok::string_literal)) {
8585
0
    P.diagnose(P.Tok, diag::sil_coverage_expected_quote);
8586
0
    return true;
8587
0
  }
8588
24
  StringRef PGOFuncName = P.Tok.getText().drop_front().drop_back();
8589
24
  P.consumeToken();
8590
8591
24
  uint64_t Hash;
8592
24
  if (State.parseInteger(Hash, diag::sil_coverage_invalid_hash))
8593
0
    return true;
8594
8595
24
  if (!P.Tok.is(tok::l_brace)) {
8596
0
    P.diagnose(P.Tok, diag::sil_coverage_expected_lbrace);
8597
0
    return true;
8598
0
  }
8599
24
  SourceLoc LBraceLoc = P.Tok.getLoc();
8600
24
  P.consumeToken(tok::l_brace);
8601
8602
24
  llvm::coverage::CounterExpressionBuilder Builder;
8603
24
  std::vector<SILCoverageMap::MappedRegion> Regions;
8604
24
  bool BodyHasError = false;
8605
24
  if (P.Tok.isNot(tok::r_brace)) {
8606
54
    do {
8607
54
      unsigned StartLine, StartCol, EndLine, EndCol;
8608
54
      if (State.parseInteger(StartLine, diag::sil_coverage_expected_loc) ||
8609
54
          P.parseToken(tok::colon, diag::sil_coverage_expected_loc) ||
8610
54
          State.parseInteger(StartCol, diag::sil_coverage_expected_loc) ||
8611
54
          P.parseToken(tok::arrow, diag::sil_coverage_expected_arrow) ||
8612
54
          State.parseInteger(EndLine, diag::sil_coverage_expected_loc) ||
8613
54
          P.parseToken(tok::colon, diag::sil_coverage_expected_loc) ||
8614
54
          State.parseInteger(EndCol, diag::sil_coverage_expected_loc)) {
8615
0
        BodyHasError = true;
8616
0
        break;
8617
0
      }
8618
8619
54
      if (P.parseToken(tok::colon, diag::sil_coverage_expected_colon)) {
8620
0
        BodyHasError = true;
8621
0
        break;
8622
0
      }
8623
8624
54
      using MappedRegion = SILCoverageMap::MappedRegion;
8625
8626
54
      if (P.Tok.isContextualKeyword("skipped")) {
8627
6
        P.consumeToken();
8628
6
        Regions.push_back(
8629
6
            MappedRegion::skipped(StartLine, StartCol, EndLine, EndCol));
8630
48
      } else {
8631
48
        auto Counter = State.parseSILCoverageExpr(Builder);
8632
48
        if (!Counter) {
8633
0
          BodyHasError = true;
8634
0
          break;
8635
0
        }
8636
48
        Regions.push_back(
8637
48
            MappedRegion::code(StartLine, StartCol, EndLine, EndCol, *Counter));
8638
48
      }
8639
8640
54
    } while (P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::eof));
8641
18
  }
8642
24
  if (BodyHasError)
8643
0
    P.skipUntilDeclRBrace();
8644
8645
24
  SourceLoc RBraceLoc;
8646
24
  P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
8647
24
                       LBraceLoc);
8648
8649
24
  if (!BodyHasError)
8650
24
    SILCoverageMap::create(M, &P.SF, Filename.str(), FuncName.str(),
8651
24
                           PGOFuncName.str(), Hash, Regions,
8652
24
                           Builder.getExpressions());
8653
24
  return false;
8654
24
}
8655
8656
/// sil-scope-ref ::= 'scope' [0-9]+
8657
/// sil-scope ::= 'sil_scope' [0-9]+ '{'
8658
///                 debug-loc
8659
///                 'parent' scope-parent
8660
///                 ('inlined_at' sil-scope-ref)?
8661
///               '}'
8662
/// scope-parent ::= sil-function-name ':' sil-type
8663
/// scope-parent ::= sil-scope-ref
8664
/// debug-loc ::= 'loc' string-literal ':' [0-9]+ ':' [0-9]+
8665
228
bool SILParserState::parseSILScope(Parser &P) {
8666
228
  P.consumeToken(tok::kw_sil_scope);
8667
228
  SILParser ScopeState(P);
8668
8669
228
  SourceLoc SlotLoc = P.Tok.getLoc();
8670
228
  unsigned Slot;
8671
228
  if (ScopeState.parseInteger(Slot, diag::sil_invalid_scope_slot))
8672
0
    return true;
8673
8674
228
  SourceLoc LBraceLoc = P.Tok.getLoc();
8675
228
  P.consumeToken(tok::l_brace);
8676
8677
228
  StringRef Key = P.Tok.getText();
8678
228
  SILLocation Loc = SILLocation::invalid();
8679
228
  if (Key == "loc")
8680
186
    if (ScopeState.parseSILLocation(Loc))
8681
0
      return true;
8682
228
  ScopeState.parseVerbatim("parent");
8683
228
  Identifier FnName;
8684
228
  SILDebugScope *Parent = nullptr;
8685
228
  SILFunction *ParentFn = nullptr;
8686
228
  if (P.Tok.is(tok::integer_literal)) {
8687
    /// scope-parent ::= sil-scope-ref
8688
66
    if (ScopeState.parseScopeRef(Parent))
8689
0
      return true;
8690
162
  } else {
8691
    /// scope-parent ::= sil-function-name
8692
162
    SILType Ty;
8693
162
    SourceLoc FnLoc = P.Tok.getLoc();
8694
    // We need to turn on InSILBody to parse the function reference.
8695
162
    Lexer::SILBodyRAII Tmp(*P.L);
8696
162
    GenericSignature IgnoredSig;
8697
162
    GenericParamList *IgnoredParams = nullptr;
8698
162
    if ((ScopeState.parseGlobalName(FnName)) ||
8699
162
        P.parseToken(tok::colon, diag::expected_sil_colon_value_ref) ||
8700
162
        ScopeState.parseSILType(Ty, IgnoredSig, IgnoredParams, true))
8701
0
      return true;
8702
8703
    // The function doesn't exist yet. Create a zombie forward declaration.
8704
162
    auto FnTy = Ty.getAs<SILFunctionType>();
8705
162
    if (!FnTy || !Ty.isObject()) {
8706
0
      P.diagnose(FnLoc, diag::expected_sil_function_type);
8707
0
      return true;
8708
0
    }
8709
162
    ParentFn = ScopeState.getGlobalNameForReference(FnName, FnTy, FnLoc, true);
8710
162
    ScopeState.TUState.PotentialZombieFns.insert(ParentFn);
8711
162
  }
8712
8713
228
  SILDebugScope *InlinedAt = nullptr;
8714
228
  if (P.Tok.getText() == "inlined_at") {
8715
3
    P.consumeToken();
8716
3
    if (ScopeState.parseScopeRef(InlinedAt))
8717
0
      return true;
8718
3
  }
8719
8720
228
  SourceLoc RBraceLoc;
8721
228
  P.parseMatchingToken(tok::r_brace, RBraceLoc, diag::expected_sil_rbrace,
8722
228
                       LBraceLoc);
8723
8724
228
  auto &Scope = ScopeSlots[Slot];
8725
228
  if (Scope) {
8726
0
    P.diagnose(SlotLoc, diag::sil_scope_redefined, Slot);
8727
0
    return true;
8728
0
  }
8729
8730
228
  Scope = new (M) SILDebugScope(Loc, ParentFn, Parent, InlinedAt);
8731
228
  return false;
8732
228
}