forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseSIL.cpp
5351 lines (4726 loc) · 183 KB
/
ParseSIL.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ParseSIL.cpp - SIL File Parsing logic ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTWalker.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/Defer.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/SIL/AbstractionPattern.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// SILParserState implementation
//===----------------------------------------------------------------------===//
namespace swift {
class SILParserTUState {
public:
SILParserTUState(SILModule &M) : M(M) {}
~SILParserTUState();
SILModule &M;
/// This is all of the forward referenced functions with
/// the location for where the reference is.
llvm::DenseMap<Identifier,
std::pair<SILFunction*, SourceLoc>> ForwardRefFns;
/// A list of all functions forward-declared by a sil_scope.
llvm::DenseSet<SILFunction *> PotentialZombieFns;
/// A map from textual .sil scope number to SILDebugScopes.
llvm::DenseMap<unsigned, SILDebugScope *> ScopeSlots;
/// Did we parse a sil_stage for this module?
bool DidParseSILStage = false;
DiagnosticEngine *Diags = nullptr;
};
} // namespace swift
SILParserState::SILParserState(SILModule *M) : M(M) {
S = M ? new SILParserTUState(*M) : nullptr;
}
SILParserState::~SILParserState() {
delete S;
}
SILParserTUState::~SILParserTUState() {
if (!ForwardRefFns.empty())
for (auto Entry : ForwardRefFns)
if (Entry.second.second.isValid())
Diags->diagnose(Entry.second.second, diag::sil_use_of_undefined_value,
Entry.first.str());
// Turn any debug-info-only function declarations into zombies.
for (auto *Fn : PotentialZombieFns)
if (Fn->isExternalDeclaration()) {
Fn->setInlined();
M.eraseFunction(Fn);
}
}
//===----------------------------------------------------------------------===//
// SILParser
//===----------------------------------------------------------------------===//
namespace {
struct ParsedSubstitution {
SourceLoc loc;
Type replacement;
};
struct ParsedSpecAttr {
ArrayRef<RequirementRepr> requirements;
bool exported;
SILSpecializeAttr::SpecializationKind kind;
};
class SILParser {
friend Parser;
public:
Parser &P;
SILModule &SILMod;
SILParserTUState &TUState;
SILFunction *F = nullptr;
GenericEnvironment *GenericEnv = nullptr;
FunctionOwnershipEvaluator OwnershipEvaluator;
private:
/// HadError - Have we seen an error parsing this function?
bool HadError = false;
/// Data structures used to perform name lookup of basic blocks.
llvm::DenseMap<Identifier, SILBasicBlock*> BlocksByName;
llvm::DenseMap<SILBasicBlock*,
std::pair<SourceLoc, Identifier>> UndefinedBlocks;
/// Data structures used to perform name lookup for local values.
llvm::StringMap<ValueBase*> LocalValues;
llvm::StringMap<SourceLoc> ForwardRefLocalValues;
/// A callback to be invoked every time a type was deserialized.
std::function<void(Type)> ParsedTypeCallback;
bool performTypeLocChecking(TypeLoc &T, bool IsSILType,
GenericEnvironment *GenericEnv = nullptr,
DeclContext *DC = nullptr);
void convertRequirements(SILFunction *F, ArrayRef<RequirementRepr> From,
SmallVectorImpl<Requirement> &To);
ProtocolConformance *
parseProtocolConformanceHelper(ProtocolDecl *&proto,
GenericEnvironment *GenericEnv,
bool localScope);
public:
SILParser(Parser &P)
: P(P), SILMod(*P.SIL->M), TUState(*P.SIL->S),
ParsedTypeCallback([](Type ty) {}) {}
/// diagnoseProblems - After a function is fully parse, emit any diagnostics
/// for errors and return true if there were any.
bool diagnoseProblems();
/// getGlobalNameForReference - Given a reference to a global name, look it
/// up and return an appropriate SIL function.
SILFunction *getGlobalNameForReference(Identifier Name,
CanSILFunctionType Ty,
SourceLoc Loc,
bool IgnoreFwdRef = false);
/// getGlobalNameForDefinition - Given a definition of a global name, look
/// it up and return an appropriate SIL function.
SILFunction *getGlobalNameForDefinition(Identifier Name,
CanSILFunctionType Ty,
SourceLoc Loc);
/// getBBForDefinition - Return the SILBasicBlock for a definition of the
/// specified block.
SILBasicBlock *getBBForDefinition(Identifier Name, SourceLoc Loc);
/// getBBForReference - return the SILBasicBlock of the specified name. The
/// source location is used to diagnose a failure if the block ends up never
/// being defined.
SILBasicBlock *getBBForReference(Identifier Name, SourceLoc Loc);
struct UnresolvedValueName {
StringRef Name;
SourceLoc NameLoc;
bool isUndef() const { return Name == "undef"; }
};
/// getLocalValue - Get a reference to a local value with the specified name
/// and type.
SILValue getLocalValue(UnresolvedValueName Name, SILType Type,
SILLocation L, SILBuilder &B);
/// setLocalValue - When an instruction or block argument is defined, this
/// method is used to register it and update our symbol table.
void setLocalValue(ValueBase *Value, StringRef Name, SourceLoc NameLoc);
SILDebugLocation getDebugLoc(SILBuilder & B, SILLocation Loc) {
return SILDebugLocation(Loc, F->getDebugScope());
}
/// @{ Primitive parsing.
/// \verbatim
/// sil-identifier ::= [A-Za-z_0-9]+
/// \endverbatim
bool parseSILIdentifier(Identifier &Result, SourceLoc &Loc,
const Diagnostic &D);
template<typename ...DiagArgTypes, typename ...ArgTypes>
bool parseSILIdentifier(Identifier &Result, Diag<DiagArgTypes...> ID,
ArgTypes... Args) {
SourceLoc L;
return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
}
template <typename T, typename... DiagArgTypes, typename... ArgTypes>
bool parseSILIdentifierSwitch(T &Result, ArrayRef<StringRef> Strings,
Diag<DiagArgTypes...> ID, ArgTypes... Args) {
Identifier TmpResult;
SourceLoc L;
if (parseSILIdentifier(TmpResult, L, Diagnostic(ID, Args...))) {
return true;
}
auto Iter = std::find(Strings.begin(), Strings.end(), TmpResult.str());
if (Iter == Strings.end()) {
P.diagnose(P.Tok, Diagnostic(ID, Args...));
return true;
}
Result = ValueOwnershipKind(*Iter);
return false;
}
template<typename ...DiagArgTypes, typename ...ArgTypes>
bool parseSILIdentifier(Identifier &Result, SourceLoc &L,
Diag<DiagArgTypes...> ID, ArgTypes... Args) {
return parseSILIdentifier(Result, L, Diagnostic(ID, Args...));
}
bool parseVerbatim(StringRef identifier);
template <typename T> bool parseInteger(T &Result, const Diagnostic &D) {
if (!P.Tok.is(tok::integer_literal)) {
P.diagnose(P.Tok, D);
return true;
}
P.Tok.getText().getAsInteger(0, Result);
P.consumeToken(tok::integer_literal);
return false;
}
/// @}
/// @{ Type parsing.
bool parseASTType(CanType &result);
bool parseASTType(CanType &result, SourceLoc &TypeLoc) {
TypeLoc = P.Tok.getLoc();
return parseASTType(result);
}
bool parseSILOwnership(ValueOwnershipKind &OwnershipKind) {
// We parse here @ <identifier>.
if (!P.consumeIf(tok::at_sign)) {
// Add error here.
return true;
}
StringRef AllOwnershipKinds[4] = {"trivial", "unowned", "owned",
"guaranteed"};
return parseSILIdentifierSwitch(OwnershipKind, AllOwnershipKinds,
diag::expected_sil_value_ownership_kind);
}
bool parseSILType(SILType &Result,
GenericEnvironment *&genericEnv,
bool IsFuncDecl = false);
bool parseSILType(SILType &Result) {
GenericEnvironment *IgnoredEnv;
return parseSILType(Result, IgnoredEnv);
}
bool parseSILType(SILType &Result, SourceLoc &TypeLoc) {
TypeLoc = P.Tok.getLoc();
return parseSILType(Result);
}
bool parseSILType(SILType &Result, SourceLoc &TypeLoc,
GenericEnvironment *&GenericEnv) {
TypeLoc = P.Tok.getLoc();
return parseSILType(Result, GenericEnv);
}
/// @}
bool parseSILDottedPath(ValueDecl *&Decl,
SmallVectorImpl<ValueDecl *> &values);
bool parseSILDottedPath(ValueDecl *&Decl) {
SmallVector<ValueDecl *, 4> values;
return parseSILDottedPath(Decl, values);
}
bool parseSILDottedPathWithoutPound(ValueDecl *&Decl,
SmallVectorImpl<ValueDecl *> &values);
bool parseSILDottedPathWithoutPound(ValueDecl *&Decl) {
SmallVector<ValueDecl *, 4> values;
return parseSILDottedPathWithoutPound(Decl, values);
}
/// At the time of calling this function, we may not have the type of the
/// Decl yet. So we return a SILDeclRef on the first lookup result and also
/// return all the lookup results. After parsing the expected type, the
/// caller of this function can choose the one that has the expected type.
bool parseSILDeclRef(SILDeclRef &Result,
SmallVectorImpl<ValueDecl *> &values);
bool parseSILDeclRef(SILDeclRef &Result) {
SmallVector<ValueDecl *, 4> values;
return parseSILDeclRef(Result, values);
}
bool parseSILDeclRef(SILDeclRef &Member, bool FnTypeRequired);
bool parseGlobalName(Identifier &Name);
bool parseValueName(UnresolvedValueName &Name);
bool parseValueRef(SILValue &Result, SILType Ty, SILLocation Loc,
SILBuilder &B);
bool parseTypedValueRef(SILValue &Result, SourceLoc &Loc, SILBuilder &B);
bool parseTypedValueRef(SILValue &Result, SILBuilder &B) {
SourceLoc Tmp;
return parseTypedValueRef(Result, Tmp, B);
}
bool parseSILOpcode(ValueKind &Opcode, SourceLoc &OpcodeLoc,
StringRef &OpcodeName);
bool parseSILDebugVar(SILDebugVariable &Var);
/// \brief Parses the basic block arguments as part of branch instruction.
bool parseSILBBArgsAtBranch(SmallVector<SILValue, 6> &Args, SILBuilder &B);
bool parseSILLocation(SILLocation &L);
bool parseScopeRef(SILDebugScope *&DS);
bool parseSILDebugLocation(SILLocation &L, SILBuilder &B,
bool parsedComma = false);
bool parseSILInstruction(SILBasicBlock *BB, SILBuilder &B);
bool parseCallInstruction(SILLocation InstLoc,
ValueKind Opcode, SILBuilder &B,
SILInstruction *&ResultVal);
bool parseSILFunctionRef(SILLocation InstLoc,
SILBuilder &B, SILInstruction *&ResultVal);
bool parseSILBasicBlock(SILBuilder &B);
bool isStartOfSILInstruction();
bool parseSubstitutions(SmallVectorImpl<ParsedSubstitution> &parsed,
GenericEnvironment *GenericEnv=nullptr);
ProtocolConformance *parseProtocolConformance(ProtocolDecl *&proto,
GenericEnvironment *&genericEnv,
bool localScope);
ProtocolConformance *parseProtocolConformance() {
ProtocolDecl *dummy;
GenericEnvironment *env;
return parseProtocolConformance(dummy, env, true);
}
Optional<llvm::coverage::Counter>
parseSILCoverageExpr(llvm::coverage::CounterExpressionBuilder &Builder);
};
} // end anonymous namespace
bool SILParser::parseSILIdentifier(Identifier &Result, SourceLoc &Loc,
const Diagnostic &D) {
switch (P.Tok.getKind()) {
case tok::identifier:
Result = P.Context.getIdentifier(P.Tok.getText());
break;
case tok::string_literal: {
// Drop the double quotes.
StringRef rawString = P.Tok.getText().drop_front().drop_back();
Result = P.Context.getIdentifier(rawString);
break;
}
case tok::oper_binary_unspaced: // fixme?
case tok::oper_binary_spaced:
// A binary operator can be part of a SILDeclRef.
Result = P.Context.getIdentifier(P.Tok.getText());
break;
case tok::kw_deinit:
Result = P.Context.Id_deinit;
break;
case tok::kw_init:
Result = P.Context.Id_init;
break;
case tok::kw_subscript:
Result = P.Context.Id_subscript;
break;
default:
// If it's some other keyword, grab an identifier for it.
if (P.Tok.isKeyword()) {
Result = P.Context.getIdentifier(P.Tok.getText());
break;
}
P.diagnose(P.Tok, D);
return true;
}
Loc = P.Tok.getLoc();
P.consumeToken();
return false;
}
bool SILParser::parseVerbatim(StringRef name) {
Identifier tok;
SourceLoc loc;
if (parseSILIdentifier(tok, loc, diag::expected_tok_in_sil_instr, name)) {
return true;
}
if (tok.str() != name) {
P.diagnose(loc, diag::expected_tok_in_sil_instr, name);
return true;
}
return false;
}
/// diagnoseProblems - After a function is fully parse, emit any diagnostics
/// for errors and return true if there were any.
bool SILParser::diagnoseProblems() {
// Check for any uses of basic blocks that were not defined.
if (!UndefinedBlocks.empty()) {
// FIXME: These are going to come out in nondeterministic order.
for (auto Entry : UndefinedBlocks)
P.diagnose(Entry.second.first, diag::sil_undefined_basicblock_use,
Entry.second.second);
HadError = true;
}
if (!ForwardRefLocalValues.empty()) {
// FIXME: These are going to come out in nondeterministic order.
for (auto &Entry : ForwardRefLocalValues)
P.diagnose(Entry.second, diag::sil_use_of_undefined_value,
Entry.first());
HadError = true;
}
return HadError;
}
/// getGlobalNameForDefinition - Given a definition of a global name, look
/// it up and return an appropriate SIL function.
SILFunction *SILParser::getGlobalNameForDefinition(Identifier Name,
CanSILFunctionType Ty,
SourceLoc Loc) {
// Check to see if a function of this name has been forward referenced. If so
// complete the forward reference.
auto It = TUState.ForwardRefFns.find(Name);
if (It != TUState.ForwardRefFns.end()) {
SILFunction *Fn = It->second.first;
// Verify that the types match up.
if (Fn->getLoweredFunctionType() != Ty) {
P.diagnose(Loc, diag::sil_value_use_type_mismatch, Name.str(),
Fn->getLoweredFunctionType(), Ty);
P.diagnose(It->second.second, diag::sil_prior_reference);
auto loc = RegularLocation(Loc);
Fn =
SILMod.createFunction(SILLinkage::Private, "", Ty, nullptr, loc,
IsNotBare, IsNotTransparent, IsNotFragile);
Fn->setDebugScope(new (SILMod) SILDebugScope(loc, Fn));
}
assert(Fn->isExternalDeclaration() && "Forward defns cannot have bodies!");
TUState.ForwardRefFns.erase(It);
// Move the function to this position in the module.
SILMod.getFunctionList().remove(Fn);
SILMod.getFunctionList().push_back(Fn);
return Fn;
}
auto loc = RegularLocation(Loc);
// If we don't have a forward reference, make sure the function hasn't been
// defined already.
if (SILMod.lookUpFunction(Name.str()) != nullptr) {
P.diagnose(Loc, diag::sil_value_redefinition, Name.str());
auto *fn =
SILMod.createFunction(SILLinkage::Private, "", Ty, nullptr, loc,
IsNotBare, IsNotTransparent, IsNotFragile);
fn->setDebugScope(new (SILMod) SILDebugScope(loc, fn));
return fn;
}
// Otherwise, this definition is the first use of this name.
auto *fn = SILMod.createFunction(SILLinkage::Private, Name.str(), Ty,
nullptr, loc, IsNotBare,
IsNotTransparent, IsNotFragile);
fn->setDebugScope(new (SILMod) SILDebugScope(loc, fn));
return fn;
}
/// getGlobalNameForReference - Given a reference to a global name, look it
/// up and return an appropriate SIL function.
SILFunction *SILParser::getGlobalNameForReference(Identifier Name,
CanSILFunctionType Ty,
SourceLoc Loc,
bool IgnoreFwdRef) {
auto loc = RegularLocation(Loc);
// Check to see if we have a function by this name already.
if (SILFunction *FnRef = SILMod.lookUpFunction(Name.str())) {
// If so, check for matching types.
if (FnRef->getLoweredFunctionType() != Ty) {
P.diagnose(Loc, diag::sil_value_use_type_mismatch,
Name.str(), FnRef->getLoweredFunctionType(), Ty);
FnRef =
SILMod.createFunction(SILLinkage::Private, "", Ty, nullptr, loc,
IsNotBare, IsNotTransparent, IsNotFragile);
FnRef->setDebugScope(new (SILMod) SILDebugScope(loc, FnRef));
}
return FnRef;
}
// If we didn't find a function, create a new one - it must be a forward
// reference.
auto *Fn = SILMod.createFunction(SILLinkage::Private, Name.str(), Ty,
nullptr, loc, IsNotBare,
IsNotTransparent, IsNotFragile);
Fn->setDebugScope(new (SILMod) SILDebugScope(loc, Fn));
TUState.ForwardRefFns[Name] = { Fn, IgnoreFwdRef ? SourceLoc() : Loc };
TUState.Diags = &P.Diags;
return Fn;
}
/// getBBForDefinition - Return the SILBasicBlock for a definition of the
/// specified block.
SILBasicBlock *SILParser::getBBForDefinition(Identifier Name, SourceLoc Loc) {
// If there was no name specified for this block, just create a new one.
if (Name.empty())
return F->createBasicBlock();
SILBasicBlock *&BB = BlocksByName[Name];
// If the block has never been named yet, just create it.
if (BB == nullptr)
return BB = F->createBasicBlock();
// If it already exists, it was either a forward reference or a redefinition.
// If it is a forward reference, it should be in our undefined set.
if (!UndefinedBlocks.erase(BB)) {
// If we have a redefinition, return a new BB to avoid inserting
// instructions after the terminator.
P.diagnose(Loc, diag::sil_basicblock_redefinition, Name);
HadError = true;
return F->createBasicBlock();
}
// FIXME: Splice the block to the end of the function so they come out in the
// right order.
return BB;
}
/// getBBForReference - return the SILBasicBlock of the specified name. The
/// source location is used to diagnose a failure if the block ends up never
/// being defined.
SILBasicBlock *SILParser::getBBForReference(Identifier Name, SourceLoc Loc) {
// If the block has already been created, use it.
SILBasicBlock *&BB = BlocksByName[Name];
if (BB != nullptr)
return BB;
// Otherwise, create it and remember that this is a forward reference so
// that we can diagnose use without definition problems.
BB = F->createBasicBlock();
UndefinedBlocks[BB] = {Loc, Name};
return BB;
}
/// sil-global-name:
/// '@' identifier
bool SILParser::parseGlobalName(Identifier &Name) {
return P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
parseSILIdentifier(Name, diag::expected_sil_value_name);
}
/// getLocalValue - Get a reference to a local value with the specified name
/// and type.
SILValue SILParser::getLocalValue(UnresolvedValueName Name, SILType Type,
SILLocation Loc, SILBuilder &B) {
if (Name.isUndef())
return SILUndef::get(Type, &SILMod);
// Check to see if this is already defined.
ValueBase *&Entry = LocalValues[Name.Name];
if (Entry) {
// If this value is already defined, check it to make sure types match.
SILType EntryTy = Entry->getType();
if (EntryTy != Type) {
HadError = true;
P.diagnose(Name.NameLoc, diag::sil_value_use_type_mismatch, Name.Name,
EntryTy.getSwiftRValueType(), Type.getSwiftRValueType());
// Make sure to return something of the requested type.
return new (SILMod) GlobalAddrInst(getDebugLoc(B, Loc), Type);
}
return SILValue(Entry);
}
// Otherwise, this is a forward reference. Create a dummy node to represent
// it until we see a real definition.
ForwardRefLocalValues[Name.Name] = Name.NameLoc;
Entry = new (SILMod) GlobalAddrInst(getDebugLoc(B, Loc), Type);
return Entry;
}
/// setLocalValue - When an instruction or block argument is defined, this
/// method is used to register it and update our symbol table.
void SILParser::setLocalValue(ValueBase *Value, StringRef Name,
SourceLoc NameLoc) {
ValueBase *&Entry = LocalValues[Name];
// If this value was already defined, it is either a redefinition, or a
// specification for a forward referenced value.
if (Entry) {
if (!ForwardRefLocalValues.erase(Name)) {
P.diagnose(NameLoc, diag::sil_value_redefinition, Name);
HadError = true;
return;
}
// If the forward reference was of the wrong type, diagnose this now.
if (Entry->getType() != Value->getType()) {
P.diagnose(NameLoc, diag::sil_value_def_type_mismatch, Name,
Entry->getType().getSwiftRValueType(),
Value->getType().getSwiftRValueType());
HadError = true;
} else {
// Forward references only live here if they have a single result.
Entry->replaceAllUsesWith(Value);
}
Entry = Value;
return;
}
// Otherwise, just store it in our map.
Entry = Value;
}
//===----------------------------------------------------------------------===//
// SIL Parsing Logic
//===----------------------------------------------------------------------===//
/// parseSILLinkage - Parse a linkage specifier if present.
/// sil-linkage:
/// /*empty*/ // default depends on whether this is a definition
/// 'public'
/// 'hidden'
/// 'shared'
/// 'private'
/// 'public_external'
/// 'hidden_external'
/// 'private_external'
static bool parseSILLinkage(Optional<SILLinkage> &Result, Parser &P) {
// Begin by initializing result to our base value of None.
Result = None;
// Unfortunate collision with access control keywords.
if (P.Tok.is(tok::kw_public)) {
Result = SILLinkage::Public;
P.consumeToken();
return false;
}
// Unfortunate collision with access control keywords.
if (P.Tok.is(tok::kw_private)) {
Result = SILLinkage::Private;
P.consumeToken();
return false;
}
// If we do not have an identifier, bail. All SILLinkages that we are parsing
// are identifiers.
if (P.Tok.isNot(tok::identifier))
return false;
// Then use a string switch to try and parse the identifier.
Result = llvm::StringSwitch<Optional<SILLinkage>>(P.Tok.getText())
.Case("hidden", SILLinkage::Hidden)
.Case("shared", SILLinkage::Shared)
.Case("public_external", SILLinkage::PublicExternal)
.Case("hidden_external", SILLinkage::HiddenExternal)
.Case("shared_external", SILLinkage::SharedExternal)
.Case("private_external", SILLinkage::PrivateExternal)
.Default(None);
// If we succeed, consume the token.
if (Result) {
P.consumeToken(tok::identifier);
}
return false;
}
/// Given whether it's known to be a definition, resolve an optional
/// SIL linkage to a real one.
static SILLinkage resolveSILLinkage(Optional<SILLinkage> linkage,
bool isDefinition) {
if (linkage.hasValue()) {
return linkage.getValue();
} else if (isDefinition) {
return SILLinkage::DefaultForDefinition;
} else {
return SILLinkage::DefaultForDeclaration;
}
}
static bool parseSILOptional(StringRef &Result, SILParser &SP) {
if (SP.P.consumeIf(tok::l_square)) {
Identifier Id;
SP.parseSILIdentifier(Id, diag::expected_in_attribute_list);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
Result = Id.str();
return true;
}
return false;
}
/// Parse an option attribute ('[' Expected ']')?
static bool parseSILOptional(bool &Result, SILParser &SP, StringRef Expected) {
StringRef Optional;
if (parseSILOptional(Optional, SP)) {
if (Optional != Expected)
return true;
Result = true;
}
return false;
}
namespace {
/// A helper class to perform lookup of IdentTypes in the
/// current parser scope.
class IdentTypeReprLookup : public ASTWalker {
Parser &P;
public:
IdentTypeReprLookup(Parser &P) : P(P) {}
bool walkToTypeReprPre(TypeRepr *Ty) {
auto *T = dyn_cast_or_null<IdentTypeRepr>(Ty);
auto Comp = T->getComponentRange().front();
if (auto Entry = P.lookupInScope(Comp->getIdentifier()))
if (isa<TypeDecl>(Entry)) {
Comp->setValue(Entry);
return false;
}
return true;
}
};
} // end anonymous namespace
/// Remap RequirementReps to Requirements.
void SILParser::convertRequirements(SILFunction *F,
ArrayRef<RequirementRepr> From,
SmallVectorImpl<Requirement> &To) {
if (From.empty()) {
To.clear();
return;
}
auto *GenericEnv = F->getGenericEnvironment();
assert(GenericEnv);
IdentTypeReprLookup PerformLookup(P);
// Use parser lexical scopes to resolve references
// to the generic parameters.
auto ResolveToInterfaceType = [&](TypeLoc Ty) -> Type {
Ty.getTypeRepr()->walk(PerformLookup);
performTypeLocChecking(Ty, /* IsSIL */ false);
assert(Ty.getType());
return GenericEnv->mapTypeOutOfContext(Ty.getType()->getCanonicalType());
};
for (auto &Req : From) {
if (Req.getKind() == RequirementReprKind::SameType) {
auto FirstType = ResolveToInterfaceType(Req.getFirstTypeLoc());
auto SecondType = ResolveToInterfaceType(Req.getSecondTypeLoc());
Requirement ConvertedRequirement(RequirementKind::SameType, FirstType,
SecondType);
To.push_back(ConvertedRequirement);
continue;
}
if (Req.getKind() == RequirementReprKind::TypeConstraint) {
auto FirstType = ResolveToInterfaceType(Req.getFirstTypeLoc());
auto SecondType = ResolveToInterfaceType(Req.getSecondTypeLoc());
Requirement ConvertedRequirement(RequirementKind::Conformance, FirstType,
SecondType);
To.push_back(ConvertedRequirement);
continue;
}
if (Req.getKind() == RequirementReprKind::LayoutConstraint) {
auto Subject = ResolveToInterfaceType(Req.getSubjectLoc());
Requirement ConvertedRequirement(RequirementKind::Layout, Subject,
Req.getLayoutConstraint());
To.push_back(ConvertedRequirement);
continue;
}
llvm_unreachable("Unsupported requirement kind");
}
}
static bool parseDeclSILOptional(bool *isTransparent, bool *isFragile,
IsThunk_t *isThunk, bool *isGlobalInit,
Inline_t *inlineStrategy, bool *isLet,
SmallVectorImpl<std::string> *Semantics,
SmallVectorImpl<ParsedSpecAttr> *SpecAttrs,
ValueDecl **ClangDecl,
EffectsKind *MRK, SILParser &SP) {
while (SP.P.consumeIf(tok::l_square)) {
if (isLet && SP.P.Tok.is(tok::kw_let)) {
*isLet = true;
SP.P.consumeToken(tok::kw_let);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
}
else if (SP.P.Tok.isNot(tok::identifier)) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
} else if (isTransparent && SP.P.Tok.getText() == "transparent")
*isTransparent = true;
else if (isFragile && SP.P.Tok.getText() == "fragile")
*isFragile = true;
else if (isThunk && SP.P.Tok.getText() == "thunk")
*isThunk = IsThunk;
else if (isThunk && SP.P.Tok.getText() == "reabstraction_thunk")
*isThunk = IsReabstractionThunk;
else if (isGlobalInit && SP.P.Tok.getText() == "global_init")
*isGlobalInit = true;
else if (inlineStrategy && SP.P.Tok.getText() == "noinline")
*inlineStrategy = NoInline;
else if (inlineStrategy && SP.P.Tok.getText() == "always_inline")
*inlineStrategy = AlwaysInline;
else if (MRK && SP.P.Tok.getText() == "readnone")
*MRK = EffectsKind::ReadNone;
else if (MRK && SP.P.Tok.getText() == "readonly")
*MRK = EffectsKind::ReadOnly;
else if (MRK && SP.P.Tok.getText() == "readwrite")
*MRK = EffectsKind::ReadWrite;
else if (Semantics && SP.P.Tok.getText() == "_semantics") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef rawString = SP.P.Tok.getText().drop_front().drop_back();
Semantics->push_back(rawString);
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
}
else if (SpecAttrs && SP.P.Tok.getText() == "_specialize") {
SourceLoc AtLoc = SP.P.Tok.getLoc();
SourceLoc Loc(AtLoc);
// Parse a _specialized attribute, building a parsed substitution list
// and pushing a new ParsedSpecAttr on the SpecAttrs list. Conformances
// cannot be generated until the function declaration is fully parsed so
// that the function's generic signature can be consulted.
ParsedSpecAttr SpecAttr;
SpecAttr.requirements = {};
SpecAttr.exported = false;
SpecAttr.kind = SILSpecializeAttr::SpecializationKind::Full;
SpecializeAttr *Attr;
if (!SP.P.parseSpecializeAttribute(tok::r_square, AtLoc, Loc, Attr))
return true;
// Convert SpecializeAttr into ParsedSpecAttr.
SpecAttr.requirements = Attr->getTrailingWhereClause()->getRequirements();
SpecAttr.kind = Attr->getSpecializationKind() ==
swift::SpecializeAttr::SpecializationKind::Full
? SILSpecializeAttr::SpecializationKind::Full
: SILSpecializeAttr::SpecializationKind::Partial;
SpecAttr.exported = Attr->isExported();
SpecAttrs->emplace_back(SpecAttr);
continue;
}
else if (ClangDecl && SP.P.Tok.getText() == "clang") {
SP.P.consumeToken(tok::identifier);
if (SP.parseSILDottedPathWithoutPound(*ClangDecl))
return true;
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
}
else {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
SP.P.consumeToken(tok::identifier);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
}
return false;
}
bool SILParser::performTypeLocChecking(TypeLoc &T, bool IsSILType,
GenericEnvironment *GenericEnv,
DeclContext *DC) {
// Do some type checking / name binding for the parsed type.
assert(P.SF.ASTStage == SourceFile::Parsing &&
"Unexpected stage during parsing!");
if (GenericEnv == nullptr)
GenericEnv = this->GenericEnv;
if (!DC)
DC = &P.SF;
return swift::performTypeLocChecking(P.Context, T,
/*isSILMode=*/true, IsSILType,
GenericEnv, DC);
}
/// Find the top-level ValueDecl or Module given a name.
static llvm::PointerUnion<ValueDecl*, ModuleDecl*> lookupTopDecl(Parser &P,
Identifier Name) {
// Use UnqualifiedLookup to look through all of the imports.
// We have to lie and say we're done with parsing to make this happen.
assert(P.SF.ASTStage == SourceFile::Parsing &&
"Unexpected stage during parsing!");
llvm::SaveAndRestore<SourceFile::ASTStage_t> ASTStage(P.SF.ASTStage,
SourceFile::Parsed);
UnqualifiedLookup DeclLookup(Name, &P.SF, nullptr);
assert(DeclLookup.isSuccess() && DeclLookup.Results.size() == 1);
ValueDecl *VD = DeclLookup.Results.back().getValueDecl();
return VD;
}
/// Find the ValueDecl given an interface type and a member name.
static ValueDecl *lookupMember(Parser &P, Type Ty, Identifier Name,
SourceLoc Loc,
SmallVectorImpl<ValueDecl *> &Lookup,
bool ExpectMultipleResults) {
Type CheckTy = Ty;
if (auto MetaTy = CheckTy->getAs<AnyMetatypeType>())
CheckTy = MetaTy->getInstanceType();
if (auto nominal = CheckTy->getAnyNominal()) {
auto found = nominal->lookupDirect(Name);
Lookup.append(found.begin(), found.end());
} else if (auto moduleTy = CheckTy->getAs<ModuleType>()) {
moduleTy->getModule()->lookupValue({ }, Name, NLKind::QualifiedLookup,
Lookup);
} else {
P.diagnose(Loc, diag::sil_member_lookup_bad_type, Name, Ty);
return nullptr;
}
if (Lookup.empty() || (!ExpectMultipleResults && Lookup.size() != 1)) {
P.diagnose(Loc, diag::sil_named_member_decl_not_found, Name, Ty);
return nullptr;
}
return Lookup[0];
}
bool SILParser::parseASTType(CanType &result) {
ParserResult<TypeRepr> parsedType = P.parseType();
if (parsedType.isNull()) return true;
TypeLoc loc = parsedType.get();
if (performTypeLocChecking(loc, /*IsSILType=*/ false))
return true;
result = loc.getType()->getCanonicalType();
// Invoke the callback on the parsed type.
ParsedTypeCallback(loc.getType());
return false;
}
/// sil-type:
/// '$' '*'? attribute-list (generic-params)? type
///
bool SILParser::parseSILType(SILType &Result,
GenericEnvironment *&GenericEnv,
bool IsFuncDecl){
GenericEnv = nullptr;
if (P.parseToken(tok::sil_dollar, diag::expected_sil_type))
return true;
// If we have a '*', then this is an address type.
SILValueCategory category = SILValueCategory::Object;
if (P.Tok.isAnyOperator() && P.Tok.getText().startswith("*")) {
category = SILValueCategory::Address;
P.consumeStartingCharacterOfCurrentToken();
}
// Parse attributes.
SourceLoc inoutLoc;
TypeAttributes attrs;
P.parseTypeAttributeList(inoutLoc, attrs);
// Global functions are implicitly @convention(thin) if not specified otherwise.
if (IsFuncDecl && !attrs.has(TAK_convention)) {
// Use a random location.
attrs.setAttr(TAK_convention, P.PreviousLoc);
attrs.convention = "thin";
}
ParserResult<TypeRepr> TyR = P.parseType(diag::expected_sil_type,
/*handleCodeCompletion*/ true,
/*isSILFuncDecl*/ IsFuncDecl);
if (TyR.isNull())