SemaExprMember.cpp 73 KB

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