SemaExprMember.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  1. //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis member access expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/Overload.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Sema/Lookup.h"
  22. #include "clang/Sema/Scope.h"
  23. #include "clang/Sema/ScopeInfo.h"
  24. #include "clang/Sema/SemaInternal.h"
  25. using namespace clang;
  26. using namespace sema;
  27. typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
  28. /// Determines if the given class is provably not derived from all of
  29. /// the prospective base classes.
  30. static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
  31. const BaseSet &Bases) {
  32. auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
  33. return !Bases.count(Base->getCanonicalDecl());
  34. };
  35. return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
  36. }
  37. enum IMAKind {
  38. /// The reference is definitely not an instance member access.
  39. IMA_Static,
  40. /// The reference may be an implicit instance member access.
  41. IMA_Mixed,
  42. /// The reference may be to an instance member, but it might be invalid if
  43. /// so, because the context is not an instance method.
  44. IMA_Mixed_StaticContext,
  45. /// The reference may be to an instance member, but it is invalid if
  46. /// so, because the context is from an unrelated class.
  47. IMA_Mixed_Unrelated,
  48. /// The reference is definitely an implicit instance member access.
  49. IMA_Instance,
  50. /// The reference may be to an unresolved using declaration.
  51. IMA_Unresolved,
  52. /// The reference is a contextually-permitted abstract member reference.
  53. IMA_Abstract,
  54. /// The reference may be to an unresolved using declaration and the
  55. /// context is not an instance method.
  56. IMA_Unresolved_StaticContext,
  57. // The reference refers to a field which is not a member of the containing
  58. // class, which is allowed because we're in C++11 mode and the context is
  59. // unevaluated.
  60. IMA_Field_Uneval_Context,
  61. /// All possible referrents are instance members and the current
  62. /// context is not an instance method.
  63. IMA_Error_StaticContext,
  64. /// All possible referrents are instance members of an unrelated
  65. /// class.
  66. IMA_Error_Unrelated
  67. };
  68. /// The given lookup names class member(s) and is not being used for
  69. /// an address-of-member expression. Classify the type of access
  70. /// according to whether it's possible that this reference names an
  71. /// instance member. This is best-effort in dependent contexts; it is okay to
  72. /// conservatively answer "yes", in which case some errors will simply
  73. /// not be caught until template-instantiation.
  74. static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
  75. const LookupResult &R) {
  76. assert(!R.empty() && (*R.begin())->isCXXClassMember());
  77. DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
  78. bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
  79. (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
  80. if (R.isUnresolvableResult())
  81. return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
  82. // Collect all the declaring classes of instance members we find.
  83. bool hasNonInstance = false;
  84. bool isField = false;
  85. BaseSet Classes;
  86. for (NamedDecl *D : R) {
  87. // Look through any using decls.
  88. D = D->getUnderlyingDecl();
  89. if (D->isCXXInstanceMember()) {
  90. isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
  91. isa<IndirectFieldDecl>(D);
  92. CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
  93. Classes.insert(R->getCanonicalDecl());
  94. } else
  95. hasNonInstance = true;
  96. }
  97. // If we didn't find any instance members, it can't be an implicit
  98. // member reference.
  99. if (Classes.empty())
  100. return IMA_Static;
  101. // C++11 [expr.prim.general]p12:
  102. // An id-expression that denotes a non-static data member or non-static
  103. // member function of a class can only be used:
  104. // (...)
  105. // - if that id-expression denotes a non-static data member and it
  106. // appears in an unevaluated operand.
  107. //
  108. // This rule is specific to C++11. However, we also permit this form
  109. // in unevaluated inline assembly operands, like the operand to a SIZE.
  110. IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
  111. assert(!AbstractInstanceResult);
  112. switch (SemaRef.ExprEvalContexts.back().Context) {
  113. case Sema::ExpressionEvaluationContext::Unevaluated:
  114. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  115. if (isField && SemaRef.getLangOpts().CPlusPlus11)
  116. AbstractInstanceResult = IMA_Field_Uneval_Context;
  117. break;
  118. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  119. AbstractInstanceResult = IMA_Abstract;
  120. break;
  121. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  122. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  123. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  124. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  125. break;
  126. }
  127. // If the current context is not an instance method, it can't be
  128. // an implicit member reference.
  129. if (isStaticContext) {
  130. if (hasNonInstance)
  131. return IMA_Mixed_StaticContext;
  132. return AbstractInstanceResult ? AbstractInstanceResult
  133. : IMA_Error_StaticContext;
  134. }
  135. CXXRecordDecl *contextClass;
  136. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
  137. contextClass = MD->getParent()->getCanonicalDecl();
  138. else
  139. contextClass = cast<CXXRecordDecl>(DC);
  140. // [class.mfct.non-static]p3:
  141. // ...is used in the body of a non-static member function of class X,
  142. // if name lookup (3.4.1) resolves the name in the id-expression to a
  143. // non-static non-type member of some class C [...]
  144. // ...if C is not X or a base class of X, the class member access expression
  145. // is ill-formed.
  146. if (R.getNamingClass() &&
  147. contextClass->getCanonicalDecl() !=
  148. R.getNamingClass()->getCanonicalDecl()) {
  149. // If the naming class is not the current context, this was a qualified
  150. // member name lookup, and it's sufficient to check that we have the naming
  151. // class as a base class.
  152. Classes.clear();
  153. Classes.insert(R.getNamingClass()->getCanonicalDecl());
  154. }
  155. // If we can prove that the current context is unrelated to all the
  156. // declaring classes, it can't be an implicit member reference (in
  157. // which case it's an error if any of those members are selected).
  158. if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
  159. return hasNonInstance ? IMA_Mixed_Unrelated :
  160. AbstractInstanceResult ? AbstractInstanceResult :
  161. IMA_Error_Unrelated;
  162. return (hasNonInstance ? IMA_Mixed : IMA_Instance);
  163. }
  164. /// Diagnose a reference to a field with no object available.
  165. static void diagnoseInstanceReference(Sema &SemaRef,
  166. const CXXScopeSpec &SS,
  167. NamedDecl *Rep,
  168. const DeclarationNameInfo &nameInfo) {
  169. SourceLocation Loc = nameInfo.getLoc();
  170. SourceRange Range(Loc);
  171. if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
  172. // Look through using shadow decls and aliases.
  173. Rep = Rep->getUnderlyingDecl();
  174. DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
  175. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
  176. CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
  177. CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
  178. bool InStaticMethod = Method && Method->isStatic();
  179. bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
  180. if (IsField && InStaticMethod)
  181. // "invalid use of member 'x' in static member function"
  182. SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
  183. << Range << nameInfo.getName();
  184. else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
  185. !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
  186. // Unqualified lookup in a non-static member function found a member of an
  187. // enclosing class.
  188. SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
  189. << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
  190. else if (IsField)
  191. SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
  192. << nameInfo.getName() << Range;
  193. else
  194. SemaRef.Diag(Loc, diag::err_member_call_without_object)
  195. << Range;
  196. }
  197. /// Builds an expression which might be an implicit member expression.
  198. ExprResult
  199. Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
  200. SourceLocation TemplateKWLoc,
  201. LookupResult &R,
  202. const TemplateArgumentListInfo *TemplateArgs,
  203. const Scope *S) {
  204. switch (ClassifyImplicitMemberAccess(*this, R)) {
  205. case IMA_Instance:
  206. return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
  207. case IMA_Mixed:
  208. case IMA_Mixed_Unrelated:
  209. case IMA_Unresolved:
  210. return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
  211. S);
  212. case IMA_Field_Uneval_Context:
  213. Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
  214. << R.getLookupNameInfo().getName();
  215. LLVM_FALLTHROUGH;
  216. case IMA_Static:
  217. case IMA_Abstract:
  218. case IMA_Mixed_StaticContext:
  219. case IMA_Unresolved_StaticContext:
  220. if (TemplateArgs || TemplateKWLoc.isValid())
  221. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
  222. return BuildDeclarationNameExpr(SS, R, false);
  223. case IMA_Error_StaticContext:
  224. case IMA_Error_Unrelated:
  225. diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
  226. R.getLookupNameInfo());
  227. return ExprError();
  228. }
  229. llvm_unreachable("unexpected instance member access kind");
  230. }
  231. /// Determine whether input char is from rgba component set.
  232. static bool
  233. IsRGBA(char c) {
  234. switch (c) {
  235. case 'r':
  236. case 'g':
  237. case 'b':
  238. case 'a':
  239. return true;
  240. default:
  241. return false;
  242. }
  243. }
  244. // OpenCL v1.1, s6.1.7
  245. // The component swizzle length must be in accordance with the acceptable
  246. // vector sizes.
  247. static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
  248. {
  249. return (len >= 1 && len <= 4) || len == 8 || len == 16;
  250. }
  251. /// Check an ext-vector component access expression.
  252. ///
  253. /// VK should be set in advance to the value kind of the base
  254. /// expression.
  255. static QualType
  256. CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
  257. SourceLocation OpLoc, const IdentifierInfo *CompName,
  258. SourceLocation CompLoc) {
  259. // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
  260. // see FIXME there.
  261. //
  262. // FIXME: This logic can be greatly simplified by splitting it along
  263. // halving/not halving and reworking the component checking.
  264. const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
  265. // The vector accessor can't exceed the number of elements.
  266. const char *compStr = CompName->getNameStart();
  267. // This flag determines whether or not the component is one of the four
  268. // special names that indicate a subset of exactly half the elements are
  269. // to be selected.
  270. bool HalvingSwizzle = false;
  271. // This flag determines whether or not CompName has an 's' char prefix,
  272. // indicating that it is a string of hex values to be used as vector indices.
  273. bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
  274. bool HasRepeated = false;
  275. bool HasIndex[16] = {};
  276. int Idx;
  277. // Check that we've found one of the special components, or that the component
  278. // names must come from the same set.
  279. if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
  280. !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
  281. HalvingSwizzle = true;
  282. } else if (!HexSwizzle &&
  283. (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
  284. bool HasRGBA = IsRGBA(*compStr);
  285. do {
  286. // Ensure that xyzw and rgba components don't intermingle.
  287. if (HasRGBA != IsRGBA(*compStr))
  288. break;
  289. if (HasIndex[Idx]) HasRepeated = true;
  290. HasIndex[Idx] = true;
  291. compStr++;
  292. } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
  293. // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
  294. if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
  295. if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
  296. const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
  297. S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
  298. << StringRef(DiagBegin, 1)
  299. << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
  300. }
  301. }
  302. } else {
  303. if (HexSwizzle) compStr++;
  304. while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
  305. if (HasIndex[Idx]) HasRepeated = true;
  306. HasIndex[Idx] = true;
  307. compStr++;
  308. }
  309. }
  310. if (!HalvingSwizzle && *compStr) {
  311. // We didn't get to the end of the string. This means the component names
  312. // didn't come from the same set *or* we encountered an illegal name.
  313. S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
  314. << StringRef(compStr, 1) << SourceRange(CompLoc);
  315. return QualType();
  316. }
  317. // Ensure no component accessor exceeds the width of the vector type it
  318. // operates on.
  319. if (!HalvingSwizzle) {
  320. compStr = CompName->getNameStart();
  321. if (HexSwizzle)
  322. compStr++;
  323. while (*compStr) {
  324. if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
  325. S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
  326. << baseType << SourceRange(CompLoc);
  327. return QualType();
  328. }
  329. }
  330. }
  331. // OpenCL mode requires swizzle length to be in accordance with accepted
  332. // sizes. Clang however supports arbitrary lengths for other languages.
  333. if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
  334. unsigned SwizzleLength = CompName->getLength();
  335. if (HexSwizzle)
  336. SwizzleLength--;
  337. if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
  338. S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
  339. << SwizzleLength << SourceRange(CompLoc);
  340. return QualType();
  341. }
  342. }
  343. // The component accessor looks fine - now we need to compute the actual type.
  344. // The vector type is implied by the component accessor. For example,
  345. // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
  346. // vec4.s0 is a float, vec4.s23 is a vec3, etc.
  347. // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
  348. unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
  349. : CompName->getLength();
  350. if (HexSwizzle)
  351. CompSize--;
  352. if (CompSize == 1)
  353. return vecType->getElementType();
  354. if (HasRepeated) VK = VK_RValue;
  355. QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
  356. // Now look up the TypeDefDecl from the vector type. Without this,
  357. // diagostics look bad. We want extended vector types to appear built-in.
  358. for (Sema::ExtVectorDeclsType::iterator
  359. I = S.ExtVectorDecls.begin(S.getExternalSource()),
  360. E = S.ExtVectorDecls.end();
  361. I != E; ++I) {
  362. if ((*I)->getUnderlyingType() == VT)
  363. return S.Context.getTypedefType(*I);
  364. }
  365. return VT; // should never get here (a typedef type should always be found).
  366. }
  367. static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
  368. IdentifierInfo *Member,
  369. const Selector &Sel,
  370. ASTContext &Context) {
  371. if (Member)
  372. if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
  373. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
  374. return PD;
  375. if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
  376. return OMD;
  377. for (const auto *I : PDecl->protocols()) {
  378. if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
  379. Context))
  380. return D;
  381. }
  382. return nullptr;
  383. }
  384. static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
  385. IdentifierInfo *Member,
  386. const Selector &Sel,
  387. ASTContext &Context) {
  388. // Check protocols on qualified interfaces.
  389. Decl *GDecl = nullptr;
  390. for (const auto *I : QIdTy->quals()) {
  391. if (Member)
  392. if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
  393. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  394. GDecl = PD;
  395. break;
  396. }
  397. // Also must look for a getter or setter name which uses property syntax.
  398. if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
  399. GDecl = OMD;
  400. break;
  401. }
  402. }
  403. if (!GDecl) {
  404. for (const auto *I : QIdTy->quals()) {
  405. // Search in the protocol-qualifier list of current protocol.
  406. GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
  407. if (GDecl)
  408. return GDecl;
  409. }
  410. }
  411. return GDecl;
  412. }
  413. ExprResult
  414. Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
  415. bool IsArrow, SourceLocation OpLoc,
  416. const CXXScopeSpec &SS,
  417. SourceLocation TemplateKWLoc,
  418. NamedDecl *FirstQualifierInScope,
  419. const DeclarationNameInfo &NameInfo,
  420. const TemplateArgumentListInfo *TemplateArgs) {
  421. // Even in dependent contexts, try to diagnose base expressions with
  422. // obviously wrong types, e.g.:
  423. //
  424. // T* t;
  425. // t.f;
  426. //
  427. // In Obj-C++, however, the above expression is valid, since it could be
  428. // accessing the 'f' property if T is an Obj-C interface. The extra check
  429. // allows this, while still reporting an error if T is a struct pointer.
  430. if (!IsArrow) {
  431. const PointerType *PT = BaseType->getAs<PointerType>();
  432. if (PT && (!getLangOpts().ObjC1 ||
  433. PT->getPointeeType()->isRecordType())) {
  434. assert(BaseExpr && "cannot happen with implicit member accesses");
  435. Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
  436. << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
  437. return ExprError();
  438. }
  439. }
  440. assert(BaseType->isDependentType() ||
  441. NameInfo.getName().isDependentName() ||
  442. isDependentScopeSpecifier(SS));
  443. // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
  444. // must have pointer type, and the accessed type is the pointee.
  445. return CXXDependentScopeMemberExpr::Create(
  446. Context, BaseExpr, BaseType, IsArrow, OpLoc,
  447. SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
  448. NameInfo, TemplateArgs);
  449. }
  450. /// We know that the given qualified member reference points only to
  451. /// declarations which do not belong to the static type of the base
  452. /// expression. Diagnose the problem.
  453. static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
  454. Expr *BaseExpr,
  455. QualType BaseType,
  456. const CXXScopeSpec &SS,
  457. NamedDecl *rep,
  458. const DeclarationNameInfo &nameInfo) {
  459. // If this is an implicit member access, use a different set of
  460. // diagnostics.
  461. if (!BaseExpr)
  462. return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
  463. SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
  464. << SS.getRange() << rep << BaseType;
  465. }
  466. // Check whether the declarations we found through a nested-name
  467. // specifier in a member expression are actually members of the base
  468. // type. The restriction here is:
  469. //
  470. // C++ [expr.ref]p2:
  471. // ... In these cases, the id-expression shall name a
  472. // member of the class or of one of its base classes.
  473. //
  474. // So it's perfectly legitimate for the nested-name specifier to name
  475. // an unrelated class, and for us to find an overload set including
  476. // decls from classes which are not superclasses, as long as the decl
  477. // we actually pick through overload resolution is from a superclass.
  478. bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
  479. QualType BaseType,
  480. const CXXScopeSpec &SS,
  481. const LookupResult &R) {
  482. CXXRecordDecl *BaseRecord =
  483. cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
  484. if (!BaseRecord) {
  485. // We can't check this yet because the base type is still
  486. // dependent.
  487. assert(BaseType->isDependentType());
  488. return false;
  489. }
  490. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  491. // If this is an implicit member reference and we find a
  492. // non-instance member, it's not an error.
  493. if (!BaseExpr && !(*I)->isCXXInstanceMember())
  494. return false;
  495. // Note that we use the DC of the decl, not the underlying decl.
  496. DeclContext *DC = (*I)->getDeclContext();
  497. while (DC->isTransparentContext())
  498. DC = DC->getParent();
  499. if (!DC->isRecord())
  500. continue;
  501. CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
  502. if (BaseRecord->getCanonicalDecl() == MemberRecord ||
  503. !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
  504. return false;
  505. }
  506. DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
  507. R.getRepresentativeDecl(),
  508. R.getLookupNameInfo());
  509. return true;
  510. }
  511. namespace {
  512. // Callback to only accept typo corrections that are either a ValueDecl or a
  513. // FunctionTemplateDecl and are declared in the current record or, for a C++
  514. // classes, one of its base classes.
  515. class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
  516. public:
  517. explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
  518. : Record(RTy->getDecl()) {
  519. // Don't add bare keywords to the consumer since they will always fail
  520. // validation by virtue of not being associated with any decls.
  521. WantTypeSpecifiers = false;
  522. WantExpressionKeywords = false;
  523. WantCXXNamedCasts = false;
  524. WantFunctionLikeCasts = false;
  525. WantRemainingKeywords = false;
  526. }
  527. bool ValidateCandidate(const TypoCorrection &candidate) override {
  528. NamedDecl *ND = candidate.getCorrectionDecl();
  529. // Don't accept candidates that cannot be member functions, constants,
  530. // variables, or templates.
  531. if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
  532. return false;
  533. // Accept candidates that occur in the current record.
  534. if (Record->containsDecl(ND))
  535. return true;
  536. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
  537. // Accept candidates that occur in any of the current class' base classes.
  538. for (const auto &BS : RD->bases()) {
  539. if (const RecordType *BSTy =
  540. dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
  541. if (BSTy->getDecl()->containsDecl(ND))
  542. return true;
  543. }
  544. }
  545. }
  546. return false;
  547. }
  548. private:
  549. const RecordDecl *const Record;
  550. };
  551. }
  552. static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
  553. Expr *BaseExpr,
  554. const RecordType *RTy,
  555. SourceLocation OpLoc, bool IsArrow,
  556. CXXScopeSpec &SS, bool HasTemplateArgs,
  557. TypoExpr *&TE) {
  558. SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
  559. RecordDecl *RDecl = RTy->getDecl();
  560. if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
  561. SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
  562. diag::err_typecheck_incomplete_tag,
  563. BaseRange))
  564. return true;
  565. if (HasTemplateArgs) {
  566. // LookupTemplateName doesn't expect these both to exist simultaneously.
  567. QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
  568. bool MOUS;
  569. SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
  570. return false;
  571. }
  572. DeclContext *DC = RDecl;
  573. if (SS.isSet()) {
  574. // If the member name was a qualified-id, look into the
  575. // nested-name-specifier.
  576. DC = SemaRef.computeDeclContext(SS, false);
  577. if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
  578. SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
  579. << SS.getRange() << DC;
  580. return true;
  581. }
  582. assert(DC && "Cannot handle non-computable dependent contexts in lookup");
  583. if (!isa<TypeDecl>(DC)) {
  584. SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
  585. << DC << SS.getRange();
  586. return true;
  587. }
  588. }
  589. // The record definition is complete, now look up the member.
  590. SemaRef.LookupQualifiedName(R, DC, SS);
  591. if (!R.empty())
  592. return false;
  593. DeclarationName Typo = R.getLookupName();
  594. SourceLocation TypoLoc = R.getNameLoc();
  595. struct QueryState {
  596. Sema &SemaRef;
  597. DeclarationNameInfo NameInfo;
  598. Sema::LookupNameKind LookupKind;
  599. Sema::RedeclarationKind Redecl;
  600. };
  601. QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
  602. R.redeclarationKind()};
  603. TE = SemaRef.CorrectTypoDelayed(
  604. R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
  605. llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
  606. [=, &SemaRef](const TypoCorrection &TC) {
  607. if (TC) {
  608. assert(!TC.isKeyword() &&
  609. "Got a keyword as a correction for a member!");
  610. bool DroppedSpecifier =
  611. TC.WillReplaceSpecifier() &&
  612. Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
  613. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  614. << Typo << DC << DroppedSpecifier
  615. << SS.getRange());
  616. } else {
  617. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
  618. }
  619. },
  620. [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
  621. LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
  622. R.clear(); // Ensure there's no decls lingering in the shared state.
  623. R.suppressDiagnostics();
  624. R.setLookupName(TC.getCorrection());
  625. for (NamedDecl *ND : TC)
  626. R.addDecl(ND);
  627. R.resolveKind();
  628. return SemaRef.BuildMemberReferenceExpr(
  629. BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
  630. nullptr, R, nullptr, nullptr);
  631. },
  632. Sema::CTK_ErrorRecovery, DC);
  633. return false;
  634. }
  635. static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
  636. ExprResult &BaseExpr, bool &IsArrow,
  637. SourceLocation OpLoc, CXXScopeSpec &SS,
  638. Decl *ObjCImpDecl, bool HasTemplateArgs);
  639. ExprResult
  640. Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
  641. SourceLocation OpLoc, bool IsArrow,
  642. CXXScopeSpec &SS,
  643. SourceLocation TemplateKWLoc,
  644. NamedDecl *FirstQualifierInScope,
  645. const DeclarationNameInfo &NameInfo,
  646. const TemplateArgumentListInfo *TemplateArgs,
  647. const Scope *S,
  648. ActOnMemberAccessExtraArgs *ExtraArgs) {
  649. if (BaseType->isDependentType() ||
  650. (SS.isSet() && isDependentScopeSpecifier(SS)))
  651. return ActOnDependentMemberExpr(Base, BaseType,
  652. IsArrow, OpLoc,
  653. SS, TemplateKWLoc, FirstQualifierInScope,
  654. NameInfo, TemplateArgs);
  655. LookupResult R(*this, NameInfo, LookupMemberName);
  656. // Implicit member accesses.
  657. if (!Base) {
  658. TypoExpr *TE = nullptr;
  659. QualType RecordTy = BaseType;
  660. if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
  661. if (LookupMemberExprInRecord(
  662. *this, R, nullptr, RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
  663. SS, TemplateKWLoc.isValid() || TemplateArgs != nullptr, TE))
  664. return ExprError();
  665. if (TE)
  666. return TE;
  667. // Explicit member accesses.
  668. } else {
  669. ExprResult BaseResult = Base;
  670. ExprResult Result =
  671. LookupMemberExpr(*this, R, BaseResult, IsArrow, OpLoc, SS,
  672. ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
  673. TemplateKWLoc.isValid() || TemplateArgs != nullptr);
  674. if (BaseResult.isInvalid())
  675. return ExprError();
  676. Base = BaseResult.get();
  677. if (Result.isInvalid())
  678. return ExprError();
  679. if (Result.get())
  680. return Result;
  681. // LookupMemberExpr can modify Base, and thus change BaseType
  682. BaseType = Base->getType();
  683. }
  684. return BuildMemberReferenceExpr(Base, BaseType,
  685. OpLoc, IsArrow, SS, TemplateKWLoc,
  686. FirstQualifierInScope, R, TemplateArgs, S,
  687. false, ExtraArgs);
  688. }
  689. ExprResult
  690. Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
  691. SourceLocation loc,
  692. IndirectFieldDecl *indirectField,
  693. DeclAccessPair foundDecl,
  694. Expr *baseObjectExpr,
  695. SourceLocation opLoc) {
  696. // First, build the expression that refers to the base object.
  697. // Case 1: the base of the indirect field is not a field.
  698. VarDecl *baseVariable = indirectField->getVarDecl();
  699. CXXScopeSpec EmptySS;
  700. if (baseVariable) {
  701. assert(baseVariable->getType()->isRecordType());
  702. // In principle we could have a member access expression that
  703. // accesses an anonymous struct/union that's a static member of
  704. // the base object's class. However, under the current standard,
  705. // static data members cannot be anonymous structs or unions.
  706. // Supporting this is as easy as building a MemberExpr here.
  707. assert(!baseObjectExpr && "anonymous struct/union is static data member?");
  708. DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
  709. ExprResult result
  710. = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
  711. if (result.isInvalid()) return ExprError();
  712. baseObjectExpr = result.get();
  713. }
  714. assert((baseVariable || baseObjectExpr) &&
  715. "referencing anonymous struct/union without a base variable or "
  716. "expression");
  717. // Build the implicit member references to the field of the
  718. // anonymous struct/union.
  719. Expr *result = baseObjectExpr;
  720. IndirectFieldDecl::chain_iterator
  721. FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
  722. // Case 2: the base of the indirect field is a field and the user
  723. // wrote a member expression.
  724. if (!baseVariable) {
  725. FieldDecl *field = cast<FieldDecl>(*FI);
  726. bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
  727. // Make a nameInfo that properly uses the anonymous name.
  728. DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
  729. // Build the first member access in the chain with full information.
  730. result =
  731. BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(),
  732. SS, field, foundDecl, memberNameInfo)
  733. .get();
  734. if (!result)
  735. return ExprError();
  736. }
  737. // In all cases, we should now skip the first declaration in the chain.
  738. ++FI;
  739. while (FI != FEnd) {
  740. FieldDecl *field = cast<FieldDecl>(*FI++);
  741. // FIXME: these are somewhat meaningless
  742. DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
  743. DeclAccessPair fakeFoundDecl =
  744. DeclAccessPair::make(field, field->getAccess());
  745. result =
  746. BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
  747. (FI == FEnd ? SS : EmptySS), field,
  748. fakeFoundDecl, memberNameInfo)
  749. .get();
  750. }
  751. return result;
  752. }
  753. static ExprResult
  754. BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
  755. const CXXScopeSpec &SS,
  756. MSPropertyDecl *PD,
  757. const DeclarationNameInfo &NameInfo) {
  758. // Property names are always simple identifiers and therefore never
  759. // require any interesting additional storage.
  760. return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
  761. S.Context.PseudoObjectTy, VK_LValue,
  762. SS.getWithLocInContext(S.Context),
  763. NameInfo.getLoc());
  764. }
  765. /// \brief Build a MemberExpr AST node.
  766. static MemberExpr *BuildMemberExpr(
  767. Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
  768. SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
  769. ValueDecl *Member, DeclAccessPair FoundDecl,
  770. const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
  771. ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
  772. assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
  773. MemberExpr *E = MemberExpr::Create(
  774. C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
  775. FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
  776. SemaRef.MarkMemberReferenced(E);
  777. return E;
  778. }
  779. /// \brief Determine if the given scope is within a function-try-block handler.
  780. static bool IsInFnTryBlockHandler(const Scope *S) {
  781. // Walk the scope stack until finding a FnTryCatchScope, or leave the
  782. // function scope. If a FnTryCatchScope is found, check whether the TryScope
  783. // flag is set. If it is not, it's a function-try-block handler.
  784. for (; S != S->getFnParent(); S = S->getParent()) {
  785. if (S->getFlags() & Scope::FnTryCatchScope)
  786. return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
  787. }
  788. return false;
  789. }
  790. static VarDecl *
  791. getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
  792. const TemplateArgumentListInfo *TemplateArgs,
  793. const DeclarationNameInfo &MemberNameInfo,
  794. SourceLocation TemplateKWLoc) {
  795. if (!TemplateArgs) {
  796. S.diagnoseMissingTemplateArguments(TemplateName(VarTempl),
  797. MemberNameInfo.getBeginLoc());
  798. return nullptr;
  799. }
  800. DeclResult VDecl = S.CheckVarTemplateId(
  801. VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
  802. if (VDecl.isInvalid())
  803. return nullptr;
  804. VarDecl *Var = cast<VarDecl>(VDecl.get());
  805. if (!Var->getTemplateSpecializationKind())
  806. Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
  807. MemberNameInfo.getLoc());
  808. return Var;
  809. }
  810. ExprResult
  811. Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
  812. SourceLocation OpLoc, bool IsArrow,
  813. const CXXScopeSpec &SS,
  814. SourceLocation TemplateKWLoc,
  815. NamedDecl *FirstQualifierInScope,
  816. LookupResult &R,
  817. const TemplateArgumentListInfo *TemplateArgs,
  818. const Scope *S,
  819. bool SuppressQualifierCheck,
  820. ActOnMemberAccessExtraArgs *ExtraArgs) {
  821. QualType BaseType = BaseExprType;
  822. if (IsArrow) {
  823. assert(BaseType->isPointerType());
  824. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  825. }
  826. R.setBaseObjectType(BaseType);
  827. // C++1z [expr.ref]p2:
  828. // For the first option (dot) the first expression shall be a glvalue [...]
  829. if (!IsArrow && BaseExpr && BaseExpr->isRValue()) {
  830. ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
  831. if (Converted.isInvalid())
  832. return ExprError();
  833. BaseExpr = Converted.get();
  834. }
  835. const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
  836. DeclarationName MemberName = MemberNameInfo.getName();
  837. SourceLocation MemberLoc = MemberNameInfo.getLoc();
  838. if (R.isAmbiguous())
  839. return ExprError();
  840. // [except.handle]p10: Referring to any non-static member or base class of an
  841. // object in the handler for a function-try-block of a constructor or
  842. // destructor for that object results in undefined behavior.
  843. const auto *FD = getCurFunctionDecl();
  844. if (S && BaseExpr && FD &&
  845. (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
  846. isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
  847. IsInFnTryBlockHandler(S))
  848. Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
  849. << isa<CXXDestructorDecl>(FD);
  850. if (R.empty()) {
  851. // Rederive where we looked up.
  852. DeclContext *DC = (SS.isSet()
  853. ? computeDeclContext(SS, false)
  854. : BaseType->getAs<RecordType>()->getDecl());
  855. if (ExtraArgs) {
  856. ExprResult RetryExpr;
  857. if (!IsArrow && BaseExpr) {
  858. SFINAETrap Trap(*this, true);
  859. ParsedType ObjectType;
  860. bool MayBePseudoDestructor = false;
  861. RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
  862. OpLoc, tok::arrow, ObjectType,
  863. MayBePseudoDestructor);
  864. if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
  865. CXXScopeSpec TempSS(SS);
  866. RetryExpr = ActOnMemberAccessExpr(
  867. ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
  868. TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
  869. }
  870. if (Trap.hasErrorOccurred())
  871. RetryExpr = ExprError();
  872. }
  873. if (RetryExpr.isUsable()) {
  874. Diag(OpLoc, diag::err_no_member_overloaded_arrow)
  875. << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
  876. return RetryExpr;
  877. }
  878. }
  879. Diag(R.getNameLoc(), diag::err_no_member)
  880. << MemberName << DC
  881. << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
  882. return ExprError();
  883. }
  884. // Diagnose lookups that find only declarations from a non-base
  885. // type. This is possible for either qualified lookups (which may
  886. // have been qualified with an unrelated type) or implicit member
  887. // expressions (which were found with unqualified lookup and thus
  888. // may have come from an enclosing scope). Note that it's okay for
  889. // lookup to find declarations from a non-base type as long as those
  890. // aren't the ones picked by overload resolution.
  891. if ((SS.isSet() || !BaseExpr ||
  892. (isa<CXXThisExpr>(BaseExpr) &&
  893. cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
  894. !SuppressQualifierCheck &&
  895. CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
  896. return ExprError();
  897. // Construct an unresolved result if we in fact got an unresolved
  898. // result.
  899. if (R.isOverloadedResult() || R.isUnresolvableResult()) {
  900. // Suppress any lookup-related diagnostics; we'll do these when we
  901. // pick a member.
  902. R.suppressDiagnostics();
  903. UnresolvedMemberExpr *MemExpr
  904. = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
  905. BaseExpr, BaseExprType,
  906. IsArrow, OpLoc,
  907. SS.getWithLocInContext(Context),
  908. TemplateKWLoc, MemberNameInfo,
  909. TemplateArgs, R.begin(), R.end());
  910. return MemExpr;
  911. }
  912. assert(R.isSingleResult());
  913. DeclAccessPair FoundDecl = R.begin().getPair();
  914. NamedDecl *MemberDecl = R.getFoundDecl();
  915. // FIXME: diagnose the presence of template arguments now.
  916. // If the decl being referenced had an error, return an error for this
  917. // sub-expr without emitting another error, in order to avoid cascading
  918. // error cases.
  919. if (MemberDecl->isInvalidDecl())
  920. return ExprError();
  921. // Handle the implicit-member-access case.
  922. if (!BaseExpr) {
  923. // If this is not an instance member, convert to a non-member access.
  924. if (!MemberDecl->isCXXInstanceMember()) {
  925. // If this is a variable template, get the instantiated variable
  926. // declaration corresponding to the supplied template arguments
  927. // (while emitting diagnostics as necessary) that will be referenced
  928. // by this expression.
  929. assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
  930. "How did we get template arguments here sans a variable template");
  931. if (isa<VarTemplateDecl>(MemberDecl)) {
  932. MemberDecl = getVarTemplateSpecialization(
  933. *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
  934. R.getLookupNameInfo(), TemplateKWLoc);
  935. if (!MemberDecl)
  936. return ExprError();
  937. }
  938. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
  939. FoundDecl, TemplateArgs);
  940. }
  941. SourceLocation Loc = R.getNameLoc();
  942. if (SS.getRange().isValid())
  943. Loc = SS.getRange().getBegin();
  944. CheckCXXThisCapture(Loc);
  945. BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
  946. }
  947. // Check the use of this member.
  948. if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
  949. return ExprError();
  950. if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
  951. return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
  952. MemberNameInfo);
  953. if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
  954. return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
  955. MemberNameInfo);
  956. if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
  957. // We may have found a field within an anonymous union or struct
  958. // (C++ [class.union]).
  959. return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
  960. FoundDecl, BaseExpr,
  961. OpLoc);
  962. if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
  963. return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
  964. TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
  965. Var->getType().getNonReferenceType(), VK_LValue,
  966. OK_Ordinary);
  967. }
  968. if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
  969. ExprValueKind valueKind;
  970. QualType type;
  971. if (MemberFn->isInstance()) {
  972. valueKind = VK_RValue;
  973. type = Context.BoundMemberTy;
  974. } else {
  975. valueKind = VK_LValue;
  976. type = MemberFn->getType();
  977. }
  978. return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
  979. TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
  980. type, valueKind, OK_Ordinary);
  981. }
  982. assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
  983. if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
  984. return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
  985. TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
  986. Enum->getType(), VK_RValue, OK_Ordinary);
  987. }
  988. if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
  989. if (VarDecl *Var = getVarTemplateSpecialization(
  990. *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
  991. return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
  992. TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
  993. Var->getType().getNonReferenceType(), VK_LValue,
  994. OK_Ordinary);
  995. return ExprError();
  996. }
  997. // We found something that we didn't expect. Complain.
  998. if (isa<TypeDecl>(MemberDecl))
  999. Diag(MemberLoc, diag::err_typecheck_member_reference_type)
  1000. << MemberName << BaseType << int(IsArrow);
  1001. else
  1002. Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
  1003. << MemberName << BaseType << int(IsArrow);
  1004. Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
  1005. << MemberName;
  1006. R.suppressDiagnostics();
  1007. return ExprError();
  1008. }
  1009. /// Given that normal member access failed on the given expression,
  1010. /// and given that the expression's type involves builtin-id or
  1011. /// builtin-Class, decide whether substituting in the redefinition
  1012. /// types would be profitable. The redefinition type is whatever
  1013. /// this translation unit tried to typedef to id/Class; we store
  1014. /// it to the side and then re-use it in places like this.
  1015. static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
  1016. const ObjCObjectPointerType *opty
  1017. = base.get()->getType()->getAs<ObjCObjectPointerType>();
  1018. if (!opty) return false;
  1019. const ObjCObjectType *ty = opty->getObjectType();
  1020. QualType redef;
  1021. if (ty->isObjCId()) {
  1022. redef = S.Context.getObjCIdRedefinitionType();
  1023. } else if (ty->isObjCClass()) {
  1024. redef = S.Context.getObjCClassRedefinitionType();
  1025. } else {
  1026. return false;
  1027. }
  1028. // Do the substitution as long as the redefinition type isn't just a
  1029. // possibly-qualified pointer to builtin-id or builtin-Class again.
  1030. opty = redef->getAs<ObjCObjectPointerType>();
  1031. if (opty && !opty->getObjectType()->getInterface())
  1032. return false;
  1033. base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
  1034. return true;
  1035. }
  1036. static bool isRecordType(QualType T) {
  1037. return T->isRecordType();
  1038. }
  1039. static bool isPointerToRecordType(QualType T) {
  1040. if (const PointerType *PT = T->getAs<PointerType>())
  1041. return PT->getPointeeType()->isRecordType();
  1042. return false;
  1043. }
  1044. /// Perform conversions on the LHS of a member access expression.
  1045. ExprResult
  1046. Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
  1047. if (IsArrow && !Base->getType()->isFunctionType())
  1048. return DefaultFunctionArrayLvalueConversion(Base);
  1049. return CheckPlaceholderExpr(Base);
  1050. }
  1051. /// Look up the given member of the given non-type-dependent
  1052. /// expression. This can return in one of two ways:
  1053. /// * If it returns a sentinel null-but-valid result, the caller will
  1054. /// assume that lookup was performed and the results written into
  1055. /// the provided structure. It will take over from there.
  1056. /// * Otherwise, the returned expression will be produced in place of
  1057. /// an ordinary member expression.
  1058. ///
  1059. /// The ObjCImpDecl bit is a gross hack that will need to be properly
  1060. /// fixed for ObjC++.
  1061. static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
  1062. ExprResult &BaseExpr, bool &IsArrow,
  1063. SourceLocation OpLoc, CXXScopeSpec &SS,
  1064. Decl *ObjCImpDecl, bool HasTemplateArgs) {
  1065. assert(BaseExpr.get() && "no base expression");
  1066. // Perform default conversions.
  1067. BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
  1068. if (BaseExpr.isInvalid())
  1069. return ExprError();
  1070. QualType BaseType = BaseExpr.get()->getType();
  1071. assert(!BaseType->isDependentType());
  1072. DeclarationName MemberName = R.getLookupName();
  1073. SourceLocation MemberLoc = R.getNameLoc();
  1074. // For later type-checking purposes, turn arrow accesses into dot
  1075. // accesses. The only access type we support that doesn't follow
  1076. // the C equivalence "a->b === (*a).b" is ObjC property accesses,
  1077. // and those never use arrows, so this is unaffected.
  1078. if (IsArrow) {
  1079. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  1080. BaseType = Ptr->getPointeeType();
  1081. else if (const ObjCObjectPointerType *Ptr
  1082. = BaseType->getAs<ObjCObjectPointerType>())
  1083. BaseType = Ptr->getPointeeType();
  1084. else if (BaseType->isRecordType()) {
  1085. // Recover from arrow accesses to records, e.g.:
  1086. // struct MyRecord foo;
  1087. // foo->bar
  1088. // This is actually well-formed in C++ if MyRecord has an
  1089. // overloaded operator->, but that should have been dealt with
  1090. // by now--or a diagnostic message already issued if a problem
  1091. // was encountered while looking for the overloaded operator->.
  1092. if (!S.getLangOpts().CPlusPlus) {
  1093. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  1094. << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
  1095. << FixItHint::CreateReplacement(OpLoc, ".");
  1096. }
  1097. IsArrow = false;
  1098. } else if (BaseType->isFunctionType()) {
  1099. goto fail;
  1100. } else {
  1101. S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
  1102. << BaseType << BaseExpr.get()->getSourceRange();
  1103. return ExprError();
  1104. }
  1105. }
  1106. // Handle field access to simple records.
  1107. if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
  1108. TypoExpr *TE = nullptr;
  1109. if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
  1110. OpLoc, IsArrow, SS, HasTemplateArgs, TE))
  1111. return ExprError();
  1112. // Returning valid-but-null is how we indicate to the caller that
  1113. // the lookup result was filled in. If typo correction was attempted and
  1114. // failed, the lookup result will have been cleared--that combined with the
  1115. // valid-but-null ExprResult will trigger the appropriate diagnostics.
  1116. return ExprResult(TE);
  1117. }
  1118. // Handle ivar access to Objective-C objects.
  1119. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
  1120. if (!SS.isEmpty() && !SS.isInvalid()) {
  1121. S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
  1122. << 1 << SS.getScopeRep()
  1123. << FixItHint::CreateRemoval(SS.getRange());
  1124. SS.clear();
  1125. }
  1126. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1127. // There are three cases for the base type:
  1128. // - builtin id (qualified or unqualified)
  1129. // - builtin Class (qualified or unqualified)
  1130. // - an interface
  1131. ObjCInterfaceDecl *IDecl = OTy->getInterface();
  1132. if (!IDecl) {
  1133. if (S.getLangOpts().ObjCAutoRefCount &&
  1134. (OTy->isObjCId() || OTy->isObjCClass()))
  1135. goto fail;
  1136. // There's an implicit 'isa' ivar on all objects.
  1137. // But we only actually find it this way on objects of type 'id',
  1138. // apparently.
  1139. if (OTy->isObjCId() && Member->isStr("isa"))
  1140. return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
  1141. OpLoc, S.Context.getObjCClassType());
  1142. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1143. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1144. ObjCImpDecl, HasTemplateArgs);
  1145. goto fail;
  1146. }
  1147. if (S.RequireCompleteType(OpLoc, BaseType,
  1148. diag::err_typecheck_incomplete_tag,
  1149. BaseExpr.get()))
  1150. return ExprError();
  1151. ObjCInterfaceDecl *ClassDeclared = nullptr;
  1152. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  1153. if (!IV) {
  1154. // Attempt to correct for typos in ivar names.
  1155. auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
  1156. Validator->IsObjCIvarLookup = IsArrow;
  1157. if (TypoCorrection Corrected = S.CorrectTypo(
  1158. R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
  1159. std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
  1160. IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
  1161. S.diagnoseTypo(
  1162. Corrected,
  1163. S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
  1164. << IDecl->getDeclName() << MemberName);
  1165. // Figure out the class that declares the ivar.
  1166. assert(!ClassDeclared);
  1167. Decl *D = cast<Decl>(IV->getDeclContext());
  1168. if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
  1169. D = Category->getClassInterface();
  1170. if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
  1171. ClassDeclared = Implementation->getClassInterface();
  1172. else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
  1173. ClassDeclared = Interface;
  1174. assert(ClassDeclared && "cannot query interface");
  1175. } else {
  1176. if (IsArrow &&
  1177. IDecl->FindPropertyDeclaration(
  1178. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  1179. S.Diag(MemberLoc, diag::err_property_found_suggest)
  1180. << Member << BaseExpr.get()->getType()
  1181. << FixItHint::CreateReplacement(OpLoc, ".");
  1182. return ExprError();
  1183. }
  1184. S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
  1185. << IDecl->getDeclName() << MemberName
  1186. << BaseExpr.get()->getSourceRange();
  1187. return ExprError();
  1188. }
  1189. }
  1190. assert(ClassDeclared);
  1191. // If the decl being referenced had an error, return an error for this
  1192. // sub-expr without emitting another error, in order to avoid cascading
  1193. // error cases.
  1194. if (IV->isInvalidDecl())
  1195. return ExprError();
  1196. // Check whether we can reference this field.
  1197. if (S.DiagnoseUseOfDecl(IV, MemberLoc))
  1198. return ExprError();
  1199. if (IV->getAccessControl() != ObjCIvarDecl::Public &&
  1200. IV->getAccessControl() != ObjCIvarDecl::Package) {
  1201. ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
  1202. if (ObjCMethodDecl *MD = S.getCurMethodDecl())
  1203. ClassOfMethodDecl = MD->getClassInterface();
  1204. else if (ObjCImpDecl && S.getCurFunctionDecl()) {
  1205. // Case of a c-function declared inside an objc implementation.
  1206. // FIXME: For a c-style function nested inside an objc implementation
  1207. // class, there is no implementation context available, so we pass
  1208. // down the context as argument to this routine. Ideally, this context
  1209. // need be passed down in the AST node and somehow calculated from the
  1210. // AST for a function decl.
  1211. if (ObjCImplementationDecl *IMPD =
  1212. dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
  1213. ClassOfMethodDecl = IMPD->getClassInterface();
  1214. else if (ObjCCategoryImplDecl* CatImplClass =
  1215. dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
  1216. ClassOfMethodDecl = CatImplClass->getClassInterface();
  1217. }
  1218. if (!S.getLangOpts().DebuggerSupport) {
  1219. if (IV->getAccessControl() == ObjCIvarDecl::Private) {
  1220. if (!declaresSameEntity(ClassDeclared, IDecl) ||
  1221. !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
  1222. S.Diag(MemberLoc, diag::err_private_ivar_access)
  1223. << IV->getDeclName();
  1224. } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
  1225. // @protected
  1226. S.Diag(MemberLoc, diag::err_protected_ivar_access)
  1227. << IV->getDeclName();
  1228. }
  1229. }
  1230. bool warn = true;
  1231. if (S.getLangOpts().ObjCWeak) {
  1232. Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
  1233. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
  1234. if (UO->getOpcode() == UO_Deref)
  1235. BaseExp = UO->getSubExpr()->IgnoreParenCasts();
  1236. if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
  1237. if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1238. S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
  1239. warn = false;
  1240. }
  1241. }
  1242. if (warn) {
  1243. if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
  1244. ObjCMethodFamily MF = MD->getMethodFamily();
  1245. warn = (MF != OMF_init && MF != OMF_dealloc &&
  1246. MF != OMF_finalize &&
  1247. !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
  1248. }
  1249. if (warn)
  1250. S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
  1251. }
  1252. ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
  1253. IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
  1254. IsArrow);
  1255. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1256. if (!S.isUnevaluatedContext() &&
  1257. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
  1258. S.getCurFunction()->recordUseOfWeak(Result);
  1259. }
  1260. return Result;
  1261. }
  1262. // Objective-C property access.
  1263. const ObjCObjectPointerType *OPT;
  1264. if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
  1265. if (!SS.isEmpty() && !SS.isInvalid()) {
  1266. S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
  1267. << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
  1268. SS.clear();
  1269. }
  1270. // This actually uses the base as an r-value.
  1271. BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
  1272. if (BaseExpr.isInvalid())
  1273. return ExprError();
  1274. assert(S.Context.hasSameUnqualifiedType(BaseType,
  1275. BaseExpr.get()->getType()));
  1276. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1277. const ObjCObjectType *OT = OPT->getObjectType();
  1278. // id, with and without qualifiers.
  1279. if (OT->isObjCId()) {
  1280. // Check protocols on qualified interfaces.
  1281. Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
  1282. if (Decl *PMDecl =
  1283. FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
  1284. if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
  1285. // Check the use of this declaration
  1286. if (S.DiagnoseUseOfDecl(PD, MemberLoc))
  1287. return ExprError();
  1288. return new (S.Context)
  1289. ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
  1290. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1291. }
  1292. if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
  1293. // Check the use of this method.
  1294. if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
  1295. return ExprError();
  1296. Selector SetterSel =
  1297. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  1298. S.PP.getSelectorTable(),
  1299. Member);
  1300. ObjCMethodDecl *SMD = nullptr;
  1301. if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
  1302. /*Property id*/ nullptr,
  1303. SetterSel, S.Context))
  1304. SMD = dyn_cast<ObjCMethodDecl>(SDecl);
  1305. return new (S.Context)
  1306. ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
  1307. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1308. }
  1309. }
  1310. // Use of id.member can only be for a property reference. Do not
  1311. // use the 'id' redefinition in this case.
  1312. if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1313. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1314. ObjCImpDecl, HasTemplateArgs);
  1315. return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
  1316. << MemberName << BaseType);
  1317. }
  1318. // 'Class', unqualified only.
  1319. if (OT->isObjCClass()) {
  1320. // Only works in a method declaration (??!).
  1321. ObjCMethodDecl *MD = S.getCurMethodDecl();
  1322. if (!MD) {
  1323. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1324. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1325. ObjCImpDecl, HasTemplateArgs);
  1326. goto fail;
  1327. }
  1328. // Also must look for a getter name which uses property syntax.
  1329. Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
  1330. ObjCInterfaceDecl *IFace = MD->getClassInterface();
  1331. if (!IFace)
  1332. goto fail;
  1333. ObjCMethodDecl *Getter;
  1334. if ((Getter = IFace->lookupClassMethod(Sel))) {
  1335. // Check the use of this method.
  1336. if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
  1337. return ExprError();
  1338. } else
  1339. Getter = IFace->lookupPrivateMethod(Sel, false);
  1340. // If we found a getter then this may be a valid dot-reference, we
  1341. // will look for the matching setter, in case it is needed.
  1342. Selector SetterSel =
  1343. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  1344. S.PP.getSelectorTable(),
  1345. Member);
  1346. ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
  1347. if (!Setter) {
  1348. // If this reference is in an @implementation, also check for 'private'
  1349. // methods.
  1350. Setter = IFace->lookupPrivateMethod(SetterSel, false);
  1351. }
  1352. if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
  1353. return ExprError();
  1354. if (Getter || Setter) {
  1355. return new (S.Context) ObjCPropertyRefExpr(
  1356. Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
  1357. OK_ObjCProperty, MemberLoc, BaseExpr.get());
  1358. }
  1359. if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
  1360. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1361. ObjCImpDecl, HasTemplateArgs);
  1362. return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
  1363. << MemberName << BaseType);
  1364. }
  1365. // Normal property access.
  1366. return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
  1367. MemberLoc, SourceLocation(), QualType(),
  1368. false);
  1369. }
  1370. // Handle 'field access' to vectors, such as 'V.xx'.
  1371. if (BaseType->isExtVectorType()) {
  1372. // FIXME: this expr should store IsArrow.
  1373. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1374. ExprValueKind VK;
  1375. if (IsArrow)
  1376. VK = VK_LValue;
  1377. else {
  1378. if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
  1379. VK = POE->getSyntacticForm()->getValueKind();
  1380. else
  1381. VK = BaseExpr.get()->getValueKind();
  1382. }
  1383. QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
  1384. Member, MemberLoc);
  1385. if (ret.isNull())
  1386. return ExprError();
  1387. Qualifiers BaseQ =
  1388. S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
  1389. ret = S.Context.getQualifiedType(ret, BaseQ);
  1390. return new (S.Context)
  1391. ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
  1392. }
  1393. // Adjust builtin-sel to the appropriate redefinition type if that's
  1394. // not just a pointer to builtin-sel again.
  1395. if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
  1396. !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
  1397. BaseExpr = S.ImpCastExprToType(
  1398. BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
  1399. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1400. ObjCImpDecl, HasTemplateArgs);
  1401. }
  1402. // Failure cases.
  1403. fail:
  1404. // Recover from dot accesses to pointers, e.g.:
  1405. // type *foo;
  1406. // foo.bar
  1407. // This is actually well-formed in two cases:
  1408. // - 'type' is an Objective C type
  1409. // - 'bar' is a pseudo-destructor name which happens to refer to
  1410. // the appropriate pointer type
  1411. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  1412. if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
  1413. MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
  1414. S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
  1415. << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
  1416. << FixItHint::CreateReplacement(OpLoc, "->");
  1417. // Recurse as an -> access.
  1418. IsArrow = true;
  1419. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1420. ObjCImpDecl, HasTemplateArgs);
  1421. }
  1422. }
  1423. // If the user is trying to apply -> or . to a function name, it's probably
  1424. // because they forgot parentheses to call that function.
  1425. if (S.tryToRecoverWithCall(
  1426. BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
  1427. /*complain*/ false,
  1428. IsArrow ? &isPointerToRecordType : &isRecordType)) {
  1429. if (BaseExpr.isInvalid())
  1430. return ExprError();
  1431. BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
  1432. return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
  1433. ObjCImpDecl, HasTemplateArgs);
  1434. }
  1435. S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
  1436. << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
  1437. return ExprError();
  1438. }
  1439. /// The main callback when the parser finds something like
  1440. /// expression . [nested-name-specifier] identifier
  1441. /// expression -> [nested-name-specifier] identifier
  1442. /// where 'identifier' encompasses a fairly broad spectrum of
  1443. /// possibilities, including destructor and operator references.
  1444. ///
  1445. /// \param OpKind either tok::arrow or tok::period
  1446. /// \param ObjCImpDecl the current Objective-C \@implementation
  1447. /// decl; this is an ugly hack around the fact that Objective-C
  1448. /// \@implementations aren't properly put in the context chain
  1449. ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
  1450. SourceLocation OpLoc,
  1451. tok::TokenKind OpKind,
  1452. CXXScopeSpec &SS,
  1453. SourceLocation TemplateKWLoc,
  1454. UnqualifiedId &Id,
  1455. Decl *ObjCImpDecl) {
  1456. if (SS.isSet() && SS.isInvalid())
  1457. return ExprError();
  1458. // Warn about the explicit constructor calls Microsoft extension.
  1459. if (getLangOpts().MicrosoftExt &&
  1460. Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
  1461. Diag(Id.getSourceRange().getBegin(),
  1462. diag::ext_ms_explicit_constructor_call);
  1463. TemplateArgumentListInfo TemplateArgsBuffer;
  1464. // Decompose the name into its component parts.
  1465. DeclarationNameInfo NameInfo;
  1466. const TemplateArgumentListInfo *TemplateArgs;
  1467. DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
  1468. NameInfo, TemplateArgs);
  1469. DeclarationName Name = NameInfo.getName();
  1470. bool IsArrow = (OpKind == tok::arrow);
  1471. NamedDecl *FirstQualifierInScope
  1472. = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
  1473. // This is a postfix expression, so get rid of ParenListExprs.
  1474. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
  1475. if (Result.isInvalid()) return ExprError();
  1476. Base = Result.get();
  1477. if (Base->getType()->isDependentType() || Name.isDependentName() ||
  1478. isDependentScopeSpecifier(SS)) {
  1479. return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
  1480. TemplateKWLoc, FirstQualifierInScope,
  1481. NameInfo, TemplateArgs);
  1482. }
  1483. ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
  1484. return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
  1485. TemplateKWLoc, FirstQualifierInScope,
  1486. NameInfo, TemplateArgs, S, &ExtraArgs);
  1487. }
  1488. ExprResult
  1489. Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
  1490. SourceLocation OpLoc, const CXXScopeSpec &SS,
  1491. FieldDecl *Field, DeclAccessPair FoundDecl,
  1492. const DeclarationNameInfo &MemberNameInfo) {
  1493. // x.a is an l-value if 'a' has a reference type. Otherwise:
  1494. // x.a is an l-value/x-value/pr-value if the base is (and note
  1495. // that *x is always an l-value), except that if the base isn't
  1496. // an ordinary object then we must have an rvalue.
  1497. ExprValueKind VK = VK_LValue;
  1498. ExprObjectKind OK = OK_Ordinary;
  1499. if (!IsArrow) {
  1500. if (BaseExpr->getObjectKind() == OK_Ordinary)
  1501. VK = BaseExpr->getValueKind();
  1502. else
  1503. VK = VK_RValue;
  1504. }
  1505. if (VK != VK_RValue && Field->isBitField())
  1506. OK = OK_BitField;
  1507. // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
  1508. QualType MemberType = Field->getType();
  1509. if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
  1510. MemberType = Ref->getPointeeType();
  1511. VK = VK_LValue;
  1512. } else {
  1513. QualType BaseType = BaseExpr->getType();
  1514. if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
  1515. Qualifiers BaseQuals = BaseType.getQualifiers();
  1516. // GC attributes are never picked up by members.
  1517. BaseQuals.removeObjCGCAttr();
  1518. // CVR attributes from the base are picked up by members,
  1519. // except that 'mutable' members don't pick up 'const'.
  1520. if (Field->isMutable()) BaseQuals.removeConst();
  1521. Qualifiers MemberQuals =
  1522. Context.getCanonicalType(MemberType).getQualifiers();
  1523. assert(!MemberQuals.hasAddressSpace());
  1524. Qualifiers Combined = BaseQuals + MemberQuals;
  1525. if (Combined != MemberQuals)
  1526. MemberType = Context.getQualifiedType(MemberType, Combined);
  1527. }
  1528. auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1529. if (!(CurMethod && CurMethod->isDefaulted()))
  1530. UnusedPrivateFields.remove(Field);
  1531. ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
  1532. FoundDecl, Field);
  1533. if (Base.isInvalid())
  1534. return ExprError();
  1535. // Build a reference to a private copy for non-static data members in
  1536. // non-static member functions, privatized by OpenMP constructs.
  1537. if (getLangOpts().OpenMP && IsArrow &&
  1538. !CurContext->isDependentContext() &&
  1539. isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
  1540. if (auto *PrivateCopy = isOpenMPCapturedDecl(Field)) {
  1541. return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
  1542. MemberNameInfo.getLoc());
  1543. }
  1544. }
  1545. return BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
  1546. /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
  1547. MemberNameInfo, MemberType, VK, OK);
  1548. }
  1549. /// Builds an implicit member access expression. The current context
  1550. /// is known to be an instance method, and the given unqualified lookup
  1551. /// set is known to contain only instance members, at least one of which
  1552. /// is from an appropriate type.
  1553. ExprResult
  1554. Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
  1555. SourceLocation TemplateKWLoc,
  1556. LookupResult &R,
  1557. const TemplateArgumentListInfo *TemplateArgs,
  1558. bool IsKnownInstance, const Scope *S) {
  1559. assert(!R.empty() && !R.isAmbiguous());
  1560. SourceLocation loc = R.getNameLoc();
  1561. // If this is known to be an instance access, go ahead and build an
  1562. // implicit 'this' expression now.
  1563. // 'this' expression now.
  1564. QualType ThisTy = getCurrentThisType();
  1565. assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
  1566. Expr *baseExpr = nullptr; // null signifies implicit access
  1567. if (IsKnownInstance) {
  1568. SourceLocation Loc = R.getNameLoc();
  1569. if (SS.getRange().isValid())
  1570. Loc = SS.getRange().getBegin();
  1571. CheckCXXThisCapture(Loc);
  1572. baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
  1573. }
  1574. return BuildMemberReferenceExpr(baseExpr, ThisTy,
  1575. /*OpLoc*/ SourceLocation(),
  1576. /*IsArrow*/ true,
  1577. SS, TemplateKWLoc,
  1578. /*FirstQualifierInScope*/ nullptr,
  1579. R, TemplateArgs, S);
  1580. }