-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaDeclAttr.cpp
7233 lines (6361 loc) · 257 KB
/
SemaDeclAttr.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
//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements decl-related attribute processing.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/MathExtras.h"
using namespace clang;
using namespace sema;
namespace AttributeLangSupport {
enum LANG {
C,
Cpp,
ObjC
};
} // end namespace AttributeLangSupport
//===----------------------------------------------------------------------===//
// Helper functions
//===----------------------------------------------------------------------===//
/// isFunctionOrMethod - Return true if the given decl has function
/// type (function or function-typed variable) or an Objective-C
/// method.
static bool isFunctionOrMethod(const Decl *D) {
return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
}
/// \brief Return true if the given decl has function type (function or
/// function-typed variable) or an Objective-C method or a block.
static bool isFunctionOrMethodOrBlock(const Decl *D) {
return isFunctionOrMethod(D) || isa<BlockDecl>(D);
}
/// Return true if the given decl has a declarator that should have
/// been processed by Sema::GetTypeForDeclarator.
static bool hasDeclarator(const Decl *D) {
// In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
isa<ObjCPropertyDecl>(D);
}
/// hasFunctionProto - Return true if the given decl has a argument
/// information. This decl should have already passed
/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
static bool hasFunctionProto(const Decl *D) {
if (const FunctionType *FnTy = D->getFunctionType())
return isa<FunctionProtoType>(FnTy);
return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
}
/// getFunctionOrMethodNumParams - Return number of function or method
/// parameters. It is an error to call this on a K&R function (use
/// hasFunctionProto first).
static unsigned getFunctionOrMethodNumParams(const Decl *D) {
if (const FunctionType *FnTy = D->getFunctionType())
return cast<FunctionProtoType>(FnTy)->getNumParams();
if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
return BD->getNumParams();
return cast<ObjCMethodDecl>(D)->param_size();
}
static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
if (const FunctionType *FnTy = D->getFunctionType())
return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
return BD->getParamDecl(Idx)->getType();
return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
}
static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
if (const auto *FD = dyn_cast<FunctionDecl>(D))
return FD->getParamDecl(Idx)->getSourceRange();
if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
return MD->parameters()[Idx]->getSourceRange();
if (const auto *BD = dyn_cast<BlockDecl>(D))
return BD->getParamDecl(Idx)->getSourceRange();
return SourceRange();
}
static QualType getFunctionOrMethodResultType(const Decl *D) {
if (const FunctionType *FnTy = D->getFunctionType())
return cast<FunctionType>(FnTy)->getReturnType();
return cast<ObjCMethodDecl>(D)->getReturnType();
}
static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
if (const auto *FD = dyn_cast<FunctionDecl>(D))
return FD->getReturnTypeSourceRange();
if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
return MD->getReturnTypeSourceRange();
return SourceRange();
}
static bool isFunctionOrMethodVariadic(const Decl *D) {
if (const FunctionType *FnTy = D->getFunctionType()) {
const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
return proto->isVariadic();
}
if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
return BD->isVariadic();
return cast<ObjCMethodDecl>(D)->isVariadic();
}
static bool isInstanceMethod(const Decl *D) {
if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
return MethodDecl->isInstance();
return false;
}
static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
if (!PT)
return false;
ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
if (!Cls)
return false;
IdentifierInfo* ClsName = Cls->getIdentifier();
// FIXME: Should we walk the chain of classes?
return ClsName == &Ctx.Idents.get("NSString") ||
ClsName == &Ctx.Idents.get("NSMutableString");
}
static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
const PointerType *PT = T->getAs<PointerType>();
if (!PT)
return false;
const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
if (RD->getTagKind() != TTK_Struct)
return false;
return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
}
static unsigned getNumAttributeArgs(const AttributeList &Attr) {
// FIXME: Include the type in the argument list.
return Attr.getNumArgs() + Attr.hasParsedType();
}
template <typename Compare>
static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
unsigned Num, unsigned Diag,
Compare Comp) {
if (Comp(getNumAttributeArgs(Attr), Num)) {
S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
return false;
}
return true;
}
/// \brief Check if the attribute has exactly as many args as Num. May
/// output an error.
static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
unsigned Num) {
return checkAttributeNumArgsImpl(S, Attr, Num,
diag::err_attribute_wrong_number_arguments,
std::not_equal_to<unsigned>());
}
/// \brief Check if the attribute has at least as many args as Num. May
/// output an error.
static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
unsigned Num) {
return checkAttributeNumArgsImpl(S, Attr, Num,
diag::err_attribute_too_few_arguments,
std::less<unsigned>());
}
/// \brief Check if the attribute has at most as many args as Num. May
/// output an error.
static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
unsigned Num) {
return checkAttributeNumArgsImpl(S, Attr, Num,
diag::err_attribute_too_many_arguments,
std::greater<unsigned>());
}
/// \brief A helper function to provide Attribute Location for the Attr types
/// AND the AttributeList.
template <typename AttrInfo>
static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
SourceLocation>::type
getAttrLoc(const AttrInfo &Attr) {
return Attr.getLocation();
}
static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
return Attr.getLoc();
}
/// \brief A helper function to provide Attribute Name for the Attr types
/// AND the AttributeList.
template <typename AttrInfo>
static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
const AttrInfo *>::type
getAttrName(const AttrInfo &Attr) {
return &Attr;
}
const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
return Attr.getName();
}
/// \brief If Expr is a valid integer constant, get the value of the integer
/// expression and return success or failure. May output an error.
template<typename AttrInfo>
static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
uint32_t &Val, unsigned Idx = UINT_MAX) {
llvm::APSInt I(32);
if (Expr->isTypeDependent() || Expr->isValueDependent() ||
!Expr->isIntegerConstantExpr(I, S.Context)) {
if (Idx != UINT_MAX)
S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
<< getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
<< Expr->getSourceRange();
else
S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
<< getAttrName(Attr) << AANT_ArgumentIntegerConstant
<< Expr->getSourceRange();
return false;
}
if (!I.isIntN(32)) {
S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
<< I.toString(10, false) << 32 << /* Unsigned */ 1;
return false;
}
Val = (uint32_t)I.getZExtValue();
return true;
}
/// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
/// that the result will fit into a regular (signed) int. All args have the same
/// purpose as they do in checkUInt32Argument.
template<typename AttrInfo>
static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
int &Val, unsigned Idx = UINT_MAX) {
uint32_t UVal;
if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
return false;
if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
llvm::APSInt I(32); // for toString
I = UVal;
S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
<< I.toString(10, false) << 32 << /* Unsigned */ 0;
return false;
}
Val = UVal;
return true;
}
/// \brief Diagnose mutually exclusive attributes when present on a given
/// declaration. Returns true if diagnosed.
template <typename AttrTy>
static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
IdentifierInfo *Ident) {
if (AttrTy *A = D->getAttr<AttrTy>()) {
S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
<< A;
S.Diag(A->getLocation(), diag::note_conflicting_attribute);
return true;
}
return false;
}
/// \brief Check if IdxExpr is a valid parameter index for a function or
/// instance method D. May output an error.
///
/// \returns true if IdxExpr is a valid index.
template <typename AttrInfo>
static bool checkFunctionOrMethodParameterIndex(
Sema &S, const Decl *D, const AttrInfo& Attr,
unsigned AttrArgNum, const Expr *IdxExpr, uint64_t &Idx) {
assert(isFunctionOrMethodOrBlock(D));
// In C++ the implicit 'this' function parameter also counts.
// Parameters are counted from one.
bool HP = hasFunctionProto(D);
bool HasImplicitThisParam = isInstanceMethod(D);
bool IV = HP && isFunctionOrMethodVariadic(D);
unsigned NumParams =
(HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
llvm::APSInt IdxInt;
if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
!IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
<< getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
<< IdxExpr->getSourceRange();
return false;
}
Idx = IdxInt.getLimitedValue();
if (Idx < 1 || (!IV && Idx > NumParams)) {
S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
<< getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
return false;
}
Idx--; // Convert to zero-based.
if (HasImplicitThisParam) {
if (Idx == 0) {
S.Diag(getAttrLoc(Attr),
diag::err_attribute_invalid_implicit_this_argument)
<< getAttrName(Attr) << IdxExpr->getSourceRange();
return false;
}
--Idx;
}
return true;
}
/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
/// If not emit an error and return false. If the argument is an identifier it
/// will emit an error with a fixit hint and treat it as if it was a string
/// literal.
bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation) {
// Look for identifiers. If we have one emit a hint to fix it to a literal.
if (Attr.isArgIdent(ArgNum)) {
IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Diag(Loc->Loc, diag::err_attribute_argument_type)
<< Attr.getName() << AANT_ArgumentString
<< FixItHint::CreateInsertion(Loc->Loc, "\"")
<< FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Str = Loc->Ident->getName();
if (ArgLocation)
*ArgLocation = Loc->Loc;
return true;
}
// Now check for an actual string literal.
Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
if (ArgLocation)
*ArgLocation = ArgExpr->getLocStart();
if (!Literal || !Literal->isAscii()) {
Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
<< Attr.getName() << AANT_ArgumentString;
return false;
}
Str = Literal->getString();
return true;
}
/// \brief Applies the given attribute to the Decl without performing any
/// additional semantic checking.
template <typename AttrType>
static void handleSimpleAttribute(Sema &S, Decl *D,
const AttributeList &Attr) {
D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
Attr.getAttributeSpellingListIndex()));
}
template <typename AttrType>
static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
const AttributeList &Attr) {
handleSimpleAttribute<AttrType>(S, D, Attr);
}
/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
/// already have one of the given incompatible attributes.
template <typename AttrType, typename IncompatibleAttrType,
typename... IncompatibleAttrTypes>
static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
const AttributeList &Attr) {
if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
Attr.getName()))
return;
handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
Attr);
}
/// \brief Check if the passed-in expression is of type int or bool.
static bool isIntOrBool(Expr *Exp) {
QualType QT = Exp->getType();
return QT->isBooleanType() || QT->isIntegerType();
}
// Check to see if the type is a smart pointer of some kind. We assume
// it's a smart pointer if it defines both operator-> and operator*.
static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
DeclContextLookupResult Res1 = RT->getDecl()->lookup(
S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
if (Res1.empty())
return false;
DeclContextLookupResult Res2 = RT->getDecl()->lookup(
S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
if (Res2.empty())
return false;
return true;
}
/// \brief Check if passed in Decl is a pointer type.
/// Note that this function may produce an error message.
/// \return true if the Decl is a pointer type; false otherwise
static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
const AttributeList &Attr) {
const ValueDecl *vd = cast<ValueDecl>(D);
QualType QT = vd->getType();
if (QT->isAnyPointerType())
return true;
if (const RecordType *RT = QT->getAs<RecordType>()) {
// If it's an incomplete type, it could be a smart pointer; skip it.
// (We don't want to force template instantiation if we can avoid it,
// since that would alter the order in which templates are instantiated.)
if (RT->isIncompleteType())
return true;
if (threadSafetyCheckIsSmartPointer(S, RT))
return true;
}
S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
<< Attr.getName() << QT;
return false;
}
/// \brief Checks that the passed in QualType either is of RecordType or points
/// to RecordType. Returns the relevant RecordType, null if it does not exit.
static const RecordType *getRecordType(QualType QT) {
if (const RecordType *RT = QT->getAs<RecordType>())
return RT;
// Now check if we point to record type.
if (const PointerType *PT = QT->getAs<PointerType>())
return PT->getPointeeType()->getAs<RecordType>();
return nullptr;
}
static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
const RecordType *RT = getRecordType(Ty);
if (!RT)
return false;
// Don't check for the capability if the class hasn't been defined yet.
if (RT->isIncompleteType())
return true;
// Allow smart pointers to be used as capability objects.
// FIXME -- Check the type that the smart pointer points to.
if (threadSafetyCheckIsSmartPointer(S, RT))
return true;
// Check if the record itself has a capability.
RecordDecl *RD = RT->getDecl();
if (RD->hasAttr<CapabilityAttr>())
return true;
// Else check if any base classes have a capability.
if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
CXXBasePaths BPaths(false, false);
if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
const auto *Type = BS->getType()->getAs<RecordType>();
return Type->getDecl()->hasAttr<CapabilityAttr>();
}, BPaths))
return true;
}
return false;
}
static bool checkTypedefTypeForCapability(QualType Ty) {
const auto *TD = Ty->getAs<TypedefType>();
if (!TD)
return false;
TypedefNameDecl *TN = TD->getDecl();
if (!TN)
return false;
return TN->hasAttr<CapabilityAttr>();
}
static bool typeHasCapability(Sema &S, QualType Ty) {
if (checkTypedefTypeForCapability(Ty))
return true;
if (checkRecordTypeForCapability(S, Ty))
return true;
return false;
}
static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
// Capability expressions are simple expressions involving the boolean logic
// operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
// a DeclRefExpr is found, its type should be checked to determine whether it
// is a capability or not.
if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
return typeHasCapability(S, E->getType());
else if (const auto *E = dyn_cast<CastExpr>(Ex))
return isCapabilityExpr(S, E->getSubExpr());
else if (const auto *E = dyn_cast<ParenExpr>(Ex))
return isCapabilityExpr(S, E->getSubExpr());
else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
if (E->getOpcode() == UO_LNot)
return isCapabilityExpr(S, E->getSubExpr());
return false;
} else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
return isCapabilityExpr(S, E->getLHS()) &&
isCapabilityExpr(S, E->getRHS());
return false;
}
return false;
}
/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
/// a capability object.
/// \param Sidx The attribute argument index to start checking with.
/// \param ParamIdxOk Whether an argument can be indexing into a function
/// parameter list.
static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
const AttributeList &Attr,
SmallVectorImpl<Expr *> &Args,
int Sidx = 0,
bool ParamIdxOk = false) {
for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Expr *ArgExp = Attr.getArgAsExpr(Idx);
if (ArgExp->isTypeDependent()) {
// FIXME -- need to check this again on template instantiation
Args.push_back(ArgExp);
continue;
}
if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
if (StrLit->getLength() == 0 ||
(StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
// Pass empty strings to the analyzer without warnings.
// Treat "*" as the universal lock.
Args.push_back(ArgExp);
continue;
}
// We allow constant strings to be used as a placeholder for expressions
// that are not valid C++ syntax, but warn that they are ignored.
S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
Attr.getName();
Args.push_back(ArgExp);
continue;
}
QualType ArgTy = ArgExp->getType();
// A pointer to member expression of the form &MyClass::mu is treated
// specially -- we need to look at the type of the member.
if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
if (UOp->getOpcode() == UO_AddrOf)
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
if (DRE->getDecl()->isCXXInstanceMember())
ArgTy = DRE->getDecl()->getType();
// First see if we can just cast to record type, or pointer to record type.
const RecordType *RT = getRecordType(ArgTy);
// Now check if we index into a record type function param.
if(!RT && ParamIdxOk) {
FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
if(FD && IL) {
unsigned int NumParams = FD->getNumParams();
llvm::APInt ArgValue = IL->getValue();
uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
<< Attr.getName() << Idx + 1 << NumParams;
continue;
}
ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
}
}
// If the type does not have a capability, see if the components of the
// expression have capabilities. This allows for writing C code where the
// capability may be on the type, and the expression is a capability
// boolean logic expression. Eg) requires_capability(A || B && !C)
if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
<< Attr.getName() << ArgTy;
Args.push_back(ArgExp);
}
}
//===----------------------------------------------------------------------===//
// Attribute Implementations
//===----------------------------------------------------------------------===//
static void handlePtGuardedVarAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
if (!threadSafetyCheckIsPointer(S, D, Attr))
return;
D->addAttr(::new (S.Context)
PtGuardedVarAttr(Attr.getRange(), S.Context,
Attr.getAttributeSpellingListIndex()));
}
static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
const AttributeList &Attr,
Expr* &Arg) {
SmallVector<Expr*, 1> Args;
// check that all arguments are lockable objects
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
unsigned Size = Args.size();
if (Size != 1)
return false;
Arg = Args[0];
return true;
}
static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Expr *Arg = nullptr;
if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
return;
D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
Attr.getAttributeSpellingListIndex()));
}
static void handlePtGuardedByAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
Expr *Arg = nullptr;
if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
return;
if (!threadSafetyCheckIsPointer(S, D, Attr))
return;
D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
S.Context, Arg,
Attr.getAttributeSpellingListIndex()));
}
static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
const AttributeList &Attr,
SmallVectorImpl<Expr *> &Args) {
if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
return false;
// Check that this attribute only applies to lockable types.
QualType QT = cast<ValueDecl>(D)->getType();
if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
<< Attr.getName();
return false;
}
// Check that all arguments are lockable objects.
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
if (Args.empty())
return false;
return true;
}
static void handleAcquiredAfterAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 1> Args;
if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
return;
Expr **StartArg = &Args[0];
D->addAttr(::new (S.Context)
AcquiredAfterAttr(Attr.getRange(), S.Context,
StartArg, Args.size(),
Attr.getAttributeSpellingListIndex()));
}
static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 1> Args;
if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
return;
Expr **StartArg = &Args[0];
D->addAttr(::new (S.Context)
AcquiredBeforeAttr(Attr.getRange(), S.Context,
StartArg, Args.size(),
Attr.getAttributeSpellingListIndex()));
}
static bool checkLockFunAttrCommon(Sema &S, Decl *D,
const AttributeList &Attr,
SmallVectorImpl<Expr *> &Args) {
// zero or more arguments ok
// check that all arguments are lockable objects
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
return true;
}
static void handleAssertSharedLockAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 1> Args;
if (!checkLockFunAttrCommon(S, D, Attr, Args))
return;
unsigned Size = Args.size();
Expr **StartArg = Size == 0 ? nullptr : &Args[0];
D->addAttr(::new (S.Context)
AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
Attr.getAttributeSpellingListIndex()));
}
static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 1> Args;
if (!checkLockFunAttrCommon(S, D, Attr, Args))
return;
unsigned Size = Args.size();
Expr **StartArg = Size == 0 ? nullptr : &Args[0];
D->addAttr(::new (S.Context)
AssertExclusiveLockAttr(Attr.getRange(), S.Context,
StartArg, Size,
Attr.getAttributeSpellingListIndex()));
}
/// \brief Checks to be sure that the given parameter number is in bounds, and is
/// an integral type. Will emit appropriate diagnostics if this returns
/// false.
///
/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
/// to actually retrieve the argument, so it's base-0.
template <typename AttrInfo>
static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
const AttrInfo &Attr, Expr *AttrArg,
unsigned FuncParamNo, unsigned AttrArgNo,
bool AllowDependentType = false) {
uint64_t Idx;
if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
Idx))
return false;
const ParmVarDecl *Param = FD->getParamDecl(Idx);
if (AllowDependentType && Param->getType()->isDependentType())
return true;
if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
SourceLocation SrcLoc = AttrArg->getLocStart();
S.Diag(SrcLoc, diag::err_attribute_integers_only)
<< getAttrName(Attr) << Param->getSourceRange();
return false;
}
return true;
}
/// \brief Checks to be sure that the given parameter number is in bounds, and is
/// an integral type. Will emit appropriate diagnostics if this returns false.
///
/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
/// to actually retrieve the argument, so it's base-0.
static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
const AttributeList &Attr,
unsigned FuncParamNo, unsigned AttrArgNo,
bool AllowDependentType = false) {
assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
FuncParamNo, AttrArgNo, AllowDependentType);
}
static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
!checkAttributeAtMostNumArgs(S, Attr, 2))
return;
const auto *FD = cast<FunctionDecl>(D);
if (!FD->getReturnType()->isPointerType()) {
S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
<< Attr.getName();
return;
}
const Expr *SizeExpr = Attr.getArgAsExpr(0);
int SizeArgNo;
// Parameter indices are 1-indexed, hence Index=1
if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
return;
if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
return;
// Args are 1-indexed, so 0 implies that the arg was not present
int NumberArgNo = 0;
if (Attr.getNumArgs() == 2) {
const Expr *NumberExpr = Attr.getArgAsExpr(1);
// Parameter indices are 1-based, hence Index=2
if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
/*Index=*/2))
return;
if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
return;
}
D->addAttr(::new (S.Context) AllocSizeAttr(
Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
Attr.getAttributeSpellingListIndex()));
}
static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
const AttributeList &Attr,
SmallVectorImpl<Expr *> &Args) {
if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
return false;
if (!isIntOrBool(Attr.getArgAsExpr(0))) {
S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
<< Attr.getName() << 1 << AANT_ArgumentIntOrBool;
return false;
}
// check that all arguments are lockable objects
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
return true;
}
static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 2> Args;
if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
return;
D->addAttr(::new (S.Context)
SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Attr.getArgAsExpr(0),
Args.data(), Args.size(),
Attr.getAttributeSpellingListIndex()));
}
static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
SmallVector<Expr*, 2> Args;
if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
return;
D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
Args.size(), Attr.getAttributeSpellingListIndex()));
}
static void handleLockReturnedAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
// check that the argument is lockable object
SmallVector<Expr*, 1> Args;
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
unsigned Size = Args.size();
if (Size == 0)
return;
D->addAttr(::new (S.Context)
LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
Attr.getAttributeSpellingListIndex()));
}
static void handleLocksExcludedAttr(Sema &S, Decl *D,
const AttributeList &Attr) {
if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
return;
// check that all arguments are lockable objects
SmallVector<Expr*, 1> Args;
checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
unsigned Size = Args.size();
if (Size == 0)
return;
Expr **StartArg = &Args[0];
D->addAttr(::new (S.Context)
LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
Attr.getAttributeSpellingListIndex()));
}
static bool checkFunctionConditionAttr(Sema &S, Decl *D,
const AttributeList &Attr,
Expr *&Cond, StringRef &Msg) {
Cond = Attr.getArgAsExpr(0);
if (!Cond->isTypeDependent()) {
ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
if (Converted.isInvalid())
return false;
Cond = Converted.get();
}
if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
return false;
if (Msg.empty())
Msg = "<no message provided>";
SmallVector<PartialDiagnosticAt, 8> Diags;
if (!Cond->isValueDependent() &&
!Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
Diags)) {
S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
<< Attr.getName();
for (const PartialDiagnosticAt &PDiag : Diags)
S.Diag(PDiag.first, PDiag.second);
return false;
}
return true;
}
static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
Expr *Cond;
StringRef Msg;
if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
D->addAttr(::new (S.Context)
EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
Attr.getAttributeSpellingListIndex()));
}
namespace {
/// Determines if a given Expr references any of the given function's
/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
class ArgumentDependenceChecker
: public RecursiveASTVisitor<ArgumentDependenceChecker> {
#ifndef NDEBUG
const CXXRecordDecl *ClassType;
#endif
llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
bool Result;
public:
ArgumentDependenceChecker(const FunctionDecl *FD) {
#ifndef NDEBUG
if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
ClassType = MD->getParent();
else
ClassType = nullptr;
#endif
Parms.insert(FD->param_begin(), FD->param_end());
}
bool referencesArgs(Expr *E) {
Result = false;
TraverseStmt(E);
return Result;