SemaPseudoObject.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670
  1. //===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for expressions involving
  10. // pseudo-object references. Pseudo-objects are conceptual objects
  11. // whose storage is entirely abstract and all accesses to which are
  12. // translated through some sort of abstraction barrier.
  13. //
  14. // For example, Objective-C objects can have "properties", either
  15. // declared or undeclared. A property may be accessed by writing
  16. // expr.prop
  17. // where 'expr' is an r-value of Objective-C pointer type and 'prop'
  18. // is the name of the property. If this expression is used in a context
  19. // needing an r-value, it is treated as if it were a message-send
  20. // of the associated 'getter' selector, typically:
  21. // [expr prop]
  22. // If it is used as the LHS of a simple assignment, it is treated
  23. // as a message-send of the associated 'setter' selector, typically:
  24. // [expr setProp: RHS]
  25. // If it is used as the LHS of a compound assignment, or the operand
  26. // of a unary increment or decrement, both are required; for example,
  27. // 'expr.prop *= 100' would be translated to:
  28. // [expr setProp: [expr prop] * 100]
  29. //
  30. //===----------------------------------------------------------------------===//
  31. #include "clang/Sema/SemaInternal.h"
  32. #include "clang/AST/ExprCXX.h"
  33. #include "clang/AST/ExprObjC.h"
  34. #include "clang/Basic/CharInfo.h"
  35. #include "clang/Lex/Preprocessor.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "llvm/ADT/SmallString.h"
  39. using namespace clang;
  40. using namespace sema;
  41. namespace {
  42. // Basically just a very focused copy of TreeTransform.
  43. struct Rebuilder {
  44. Sema &S;
  45. unsigned MSPropertySubscriptCount;
  46. typedef llvm::function_ref<Expr *(Expr *, unsigned)> SpecificRebuilderRefTy;
  47. const SpecificRebuilderRefTy &SpecificCallback;
  48. Rebuilder(Sema &S, const SpecificRebuilderRefTy &SpecificCallback)
  49. : S(S), MSPropertySubscriptCount(0),
  50. SpecificCallback(SpecificCallback) {}
  51. Expr *rebuildObjCPropertyRefExpr(ObjCPropertyRefExpr *refExpr) {
  52. // Fortunately, the constraint that we're rebuilding something
  53. // with a base limits the number of cases here.
  54. if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
  55. return refExpr;
  56. if (refExpr->isExplicitProperty()) {
  57. return new (S.Context) ObjCPropertyRefExpr(
  58. refExpr->getExplicitProperty(), refExpr->getType(),
  59. refExpr->getValueKind(), refExpr->getObjectKind(),
  60. refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
  61. }
  62. return new (S.Context) ObjCPropertyRefExpr(
  63. refExpr->getImplicitPropertyGetter(),
  64. refExpr->getImplicitPropertySetter(), refExpr->getType(),
  65. refExpr->getValueKind(), refExpr->getObjectKind(),
  66. refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
  67. }
  68. Expr *rebuildObjCSubscriptRefExpr(ObjCSubscriptRefExpr *refExpr) {
  69. assert(refExpr->getBaseExpr());
  70. assert(refExpr->getKeyExpr());
  71. return new (S.Context) ObjCSubscriptRefExpr(
  72. SpecificCallback(refExpr->getBaseExpr(), 0),
  73. SpecificCallback(refExpr->getKeyExpr(), 1), refExpr->getType(),
  74. refExpr->getValueKind(), refExpr->getObjectKind(),
  75. refExpr->getAtIndexMethodDecl(), refExpr->setAtIndexMethodDecl(),
  76. refExpr->getRBracket());
  77. }
  78. Expr *rebuildMSPropertyRefExpr(MSPropertyRefExpr *refExpr) {
  79. assert(refExpr->getBaseExpr());
  80. return new (S.Context) MSPropertyRefExpr(
  81. SpecificCallback(refExpr->getBaseExpr(), 0),
  82. refExpr->getPropertyDecl(), refExpr->isArrow(), refExpr->getType(),
  83. refExpr->getValueKind(), refExpr->getQualifierLoc(),
  84. refExpr->getMemberLoc());
  85. }
  86. Expr *rebuildMSPropertySubscriptExpr(MSPropertySubscriptExpr *refExpr) {
  87. assert(refExpr->getBase());
  88. assert(refExpr->getIdx());
  89. auto *NewBase = rebuild(refExpr->getBase());
  90. ++MSPropertySubscriptCount;
  91. return new (S.Context) MSPropertySubscriptExpr(
  92. NewBase,
  93. SpecificCallback(refExpr->getIdx(), MSPropertySubscriptCount),
  94. refExpr->getType(), refExpr->getValueKind(), refExpr->getObjectKind(),
  95. refExpr->getRBracketLoc());
  96. }
  97. Expr *rebuild(Expr *e) {
  98. // Fast path: nothing to look through.
  99. if (auto *PRE = dyn_cast<ObjCPropertyRefExpr>(e))
  100. return rebuildObjCPropertyRefExpr(PRE);
  101. if (auto *SRE = dyn_cast<ObjCSubscriptRefExpr>(e))
  102. return rebuildObjCSubscriptRefExpr(SRE);
  103. if (auto *MSPRE = dyn_cast<MSPropertyRefExpr>(e))
  104. return rebuildMSPropertyRefExpr(MSPRE);
  105. if (auto *MSPSE = dyn_cast<MSPropertySubscriptExpr>(e))
  106. return rebuildMSPropertySubscriptExpr(MSPSE);
  107. // Otherwise, we should look through and rebuild anything that
  108. // IgnoreParens would.
  109. if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
  110. e = rebuild(parens->getSubExpr());
  111. return new (S.Context) ParenExpr(parens->getLParen(),
  112. parens->getRParen(),
  113. e);
  114. }
  115. if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
  116. assert(uop->getOpcode() == UO_Extension);
  117. e = rebuild(uop->getSubExpr());
  118. return UnaryOperator::Create(
  119. S.Context, e, uop->getOpcode(), uop->getType(), uop->getValueKind(),
  120. uop->getObjectKind(), uop->getOperatorLoc(), uop->canOverflow(),
  121. S.CurFPFeatureOverrides());
  122. }
  123. if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
  124. assert(!gse->isResultDependent());
  125. unsigned resultIndex = gse->getResultIndex();
  126. unsigned numAssocs = gse->getNumAssocs();
  127. SmallVector<Expr *, 8> assocExprs;
  128. SmallVector<TypeSourceInfo *, 8> assocTypes;
  129. assocExprs.reserve(numAssocs);
  130. assocTypes.reserve(numAssocs);
  131. for (const GenericSelectionExpr::Association assoc :
  132. gse->associations()) {
  133. Expr *assocExpr = assoc.getAssociationExpr();
  134. if (assoc.isSelected())
  135. assocExpr = rebuild(assocExpr);
  136. assocExprs.push_back(assocExpr);
  137. assocTypes.push_back(assoc.getTypeSourceInfo());
  138. }
  139. return GenericSelectionExpr::Create(
  140. S.Context, gse->getGenericLoc(), gse->getControllingExpr(),
  141. assocTypes, assocExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
  142. gse->containsUnexpandedParameterPack(), resultIndex);
  143. }
  144. if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
  145. assert(!ce->isConditionDependent());
  146. Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
  147. Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
  148. rebuiltExpr = rebuild(rebuiltExpr);
  149. return new (S.Context)
  150. ChooseExpr(ce->getBuiltinLoc(), ce->getCond(), LHS, RHS,
  151. rebuiltExpr->getType(), rebuiltExpr->getValueKind(),
  152. rebuiltExpr->getObjectKind(), ce->getRParenLoc(),
  153. ce->isConditionTrue());
  154. }
  155. llvm_unreachable("bad expression to rebuild!");
  156. }
  157. };
  158. class PseudoOpBuilder {
  159. public:
  160. Sema &S;
  161. unsigned ResultIndex;
  162. SourceLocation GenericLoc;
  163. bool IsUnique;
  164. SmallVector<Expr *, 4> Semantics;
  165. PseudoOpBuilder(Sema &S, SourceLocation genericLoc, bool IsUnique)
  166. : S(S), ResultIndex(PseudoObjectExpr::NoResult),
  167. GenericLoc(genericLoc), IsUnique(IsUnique) {}
  168. virtual ~PseudoOpBuilder() {}
  169. /// Add a normal semantic expression.
  170. void addSemanticExpr(Expr *semantic) {
  171. Semantics.push_back(semantic);
  172. }
  173. /// Add the 'result' semantic expression.
  174. void addResultSemanticExpr(Expr *resultExpr) {
  175. assert(ResultIndex == PseudoObjectExpr::NoResult);
  176. ResultIndex = Semantics.size();
  177. Semantics.push_back(resultExpr);
  178. // An OVE is not unique if it is used as the result expression.
  179. if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantics.back()))
  180. OVE->setIsUnique(false);
  181. }
  182. ExprResult buildRValueOperation(Expr *op);
  183. ExprResult buildAssignmentOperation(Scope *Sc,
  184. SourceLocation opLoc,
  185. BinaryOperatorKind opcode,
  186. Expr *LHS, Expr *RHS);
  187. ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
  188. UnaryOperatorKind opcode,
  189. Expr *op);
  190. virtual ExprResult complete(Expr *syntacticForm);
  191. OpaqueValueExpr *capture(Expr *op);
  192. OpaqueValueExpr *captureValueAsResult(Expr *op);
  193. void setResultToLastSemantic() {
  194. assert(ResultIndex == PseudoObjectExpr::NoResult);
  195. ResultIndex = Semantics.size() - 1;
  196. // An OVE is not unique if it is used as the result expression.
  197. if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantics.back()))
  198. OVE->setIsUnique(false);
  199. }
  200. /// Return true if assignments have a non-void result.
  201. static bool CanCaptureValue(Expr *exp) {
  202. if (exp->isGLValue())
  203. return true;
  204. QualType ty = exp->getType();
  205. assert(!ty->isIncompleteType());
  206. assert(!ty->isDependentType());
  207. if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
  208. return ClassDecl->isTriviallyCopyable();
  209. return true;
  210. }
  211. virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
  212. virtual ExprResult buildGet() = 0;
  213. virtual ExprResult buildSet(Expr *, SourceLocation,
  214. bool captureSetValueAsResult) = 0;
  215. /// Should the result of an assignment be the formal result of the
  216. /// setter call or the value that was passed to the setter?
  217. ///
  218. /// Different pseudo-object language features use different language rules
  219. /// for this.
  220. /// The default is to use the set value. Currently, this affects the
  221. /// behavior of simple assignments, compound assignments, and prefix
  222. /// increment and decrement.
  223. /// Postfix increment and decrement always use the getter result as the
  224. /// expression result.
  225. ///
  226. /// If this method returns true, and the set value isn't capturable for
  227. /// some reason, the result of the expression will be void.
  228. virtual bool captureSetValueAsResult() const { return true; }
  229. };
  230. /// A PseudoOpBuilder for Objective-C \@properties.
  231. class ObjCPropertyOpBuilder : public PseudoOpBuilder {
  232. ObjCPropertyRefExpr *RefExpr;
  233. ObjCPropertyRefExpr *SyntacticRefExpr;
  234. OpaqueValueExpr *InstanceReceiver;
  235. ObjCMethodDecl *Getter;
  236. ObjCMethodDecl *Setter;
  237. Selector SetterSelector;
  238. Selector GetterSelector;
  239. public:
  240. ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr, bool IsUnique)
  241. : PseudoOpBuilder(S, refExpr->getLocation(), IsUnique),
  242. RefExpr(refExpr), SyntacticRefExpr(nullptr),
  243. InstanceReceiver(nullptr), Getter(nullptr), Setter(nullptr) {
  244. }
  245. ExprResult buildRValueOperation(Expr *op);
  246. ExprResult buildAssignmentOperation(Scope *Sc,
  247. SourceLocation opLoc,
  248. BinaryOperatorKind opcode,
  249. Expr *LHS, Expr *RHS);
  250. ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
  251. UnaryOperatorKind opcode,
  252. Expr *op);
  253. bool tryBuildGetOfReference(Expr *op, ExprResult &result);
  254. bool findSetter(bool warn=true);
  255. bool findGetter();
  256. void DiagnoseUnsupportedPropertyUse();
  257. Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
  258. ExprResult buildGet() override;
  259. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  260. ExprResult complete(Expr *SyntacticForm) override;
  261. bool isWeakProperty() const;
  262. };
  263. /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
  264. class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
  265. ObjCSubscriptRefExpr *RefExpr;
  266. OpaqueValueExpr *InstanceBase;
  267. OpaqueValueExpr *InstanceKey;
  268. ObjCMethodDecl *AtIndexGetter;
  269. Selector AtIndexGetterSelector;
  270. ObjCMethodDecl *AtIndexSetter;
  271. Selector AtIndexSetterSelector;
  272. public:
  273. ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr, bool IsUnique)
  274. : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
  275. RefExpr(refExpr), InstanceBase(nullptr), InstanceKey(nullptr),
  276. AtIndexGetter(nullptr), AtIndexSetter(nullptr) {}
  277. ExprResult buildRValueOperation(Expr *op);
  278. ExprResult buildAssignmentOperation(Scope *Sc,
  279. SourceLocation opLoc,
  280. BinaryOperatorKind opcode,
  281. Expr *LHS, Expr *RHS);
  282. Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
  283. bool findAtIndexGetter();
  284. bool findAtIndexSetter();
  285. ExprResult buildGet() override;
  286. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  287. };
  288. class MSPropertyOpBuilder : public PseudoOpBuilder {
  289. MSPropertyRefExpr *RefExpr;
  290. OpaqueValueExpr *InstanceBase;
  291. SmallVector<Expr *, 4> CallArgs;
  292. MSPropertyRefExpr *getBaseMSProperty(MSPropertySubscriptExpr *E);
  293. public:
  294. MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr, bool IsUnique)
  295. : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
  296. RefExpr(refExpr), InstanceBase(nullptr) {}
  297. MSPropertyOpBuilder(Sema &S, MSPropertySubscriptExpr *refExpr, bool IsUnique)
  298. : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
  299. InstanceBase(nullptr) {
  300. RefExpr = getBaseMSProperty(refExpr);
  301. }
  302. Expr *rebuildAndCaptureObject(Expr *) override;
  303. ExprResult buildGet() override;
  304. ExprResult buildSet(Expr *op, SourceLocation, bool) override;
  305. bool captureSetValueAsResult() const override { return false; }
  306. };
  307. }
  308. /// Capture the given expression in an OpaqueValueExpr.
  309. OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
  310. // Make a new OVE whose source is the given expression.
  311. OpaqueValueExpr *captured =
  312. new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
  313. e->getValueKind(), e->getObjectKind(),
  314. e);
  315. if (IsUnique)
  316. captured->setIsUnique(true);
  317. // Make sure we bind that in the semantics.
  318. addSemanticExpr(captured);
  319. return captured;
  320. }
  321. /// Capture the given expression as the result of this pseudo-object
  322. /// operation. This routine is safe against expressions which may
  323. /// already be captured.
  324. ///
  325. /// \returns the captured expression, which will be the
  326. /// same as the input if the input was already captured
  327. OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
  328. assert(ResultIndex == PseudoObjectExpr::NoResult);
  329. // If the expression hasn't already been captured, just capture it
  330. // and set the new semantic
  331. if (!isa<OpaqueValueExpr>(e)) {
  332. OpaqueValueExpr *cap = capture(e);
  333. setResultToLastSemantic();
  334. return cap;
  335. }
  336. // Otherwise, it must already be one of our semantic expressions;
  337. // set ResultIndex to its index.
  338. unsigned index = 0;
  339. for (;; ++index) {
  340. assert(index < Semantics.size() &&
  341. "captured expression not found in semantics!");
  342. if (e == Semantics[index]) break;
  343. }
  344. ResultIndex = index;
  345. // An OVE is not unique if it is used as the result expression.
  346. cast<OpaqueValueExpr>(e)->setIsUnique(false);
  347. return cast<OpaqueValueExpr>(e);
  348. }
  349. /// The routine which creates the final PseudoObjectExpr.
  350. ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
  351. return PseudoObjectExpr::Create(S.Context, syntactic,
  352. Semantics, ResultIndex);
  353. }
  354. /// The main skeleton for building an r-value operation.
  355. ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
  356. Expr *syntacticBase = rebuildAndCaptureObject(op);
  357. ExprResult getExpr = buildGet();
  358. if (getExpr.isInvalid()) return ExprError();
  359. addResultSemanticExpr(getExpr.get());
  360. return complete(syntacticBase);
  361. }
  362. /// The basic skeleton for building a simple or compound
  363. /// assignment operation.
  364. ExprResult
  365. PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
  366. BinaryOperatorKind opcode,
  367. Expr *LHS, Expr *RHS) {
  368. assert(BinaryOperator::isAssignmentOp(opcode));
  369. Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
  370. OpaqueValueExpr *capturedRHS = capture(RHS);
  371. // In some very specific cases, semantic analysis of the RHS as an
  372. // expression may require it to be rewritten. In these cases, we
  373. // cannot safely keep the OVE around. Fortunately, we don't really
  374. // need to: we don't use this particular OVE in multiple places, and
  375. // no clients rely that closely on matching up expressions in the
  376. // semantic expression with expressions from the syntactic form.
  377. Expr *semanticRHS = capturedRHS;
  378. if (RHS->hasPlaceholderType() || isa<InitListExpr>(RHS)) {
  379. semanticRHS = RHS;
  380. Semantics.pop_back();
  381. }
  382. Expr *syntactic;
  383. ExprResult result;
  384. if (opcode == BO_Assign) {
  385. result = semanticRHS;
  386. syntactic = BinaryOperator::Create(S.Context, syntacticLHS, capturedRHS,
  387. opcode, capturedRHS->getType(),
  388. capturedRHS->getValueKind(), OK_Ordinary,
  389. opcLoc, S.CurFPFeatureOverrides());
  390. } else {
  391. ExprResult opLHS = buildGet();
  392. if (opLHS.isInvalid()) return ExprError();
  393. // Build an ordinary, non-compound operation.
  394. BinaryOperatorKind nonCompound =
  395. BinaryOperator::getOpForCompoundAssignment(opcode);
  396. result = S.BuildBinOp(Sc, opcLoc, nonCompound, opLHS.get(), semanticRHS);
  397. if (result.isInvalid()) return ExprError();
  398. syntactic = CompoundAssignOperator::Create(
  399. S.Context, syntacticLHS, capturedRHS, opcode, result.get()->getType(),
  400. result.get()->getValueKind(), OK_Ordinary, opcLoc,
  401. S.CurFPFeatureOverrides(), opLHS.get()->getType(),
  402. result.get()->getType());
  403. }
  404. // The result of the assignment, if not void, is the value set into
  405. // the l-value.
  406. result = buildSet(result.get(), opcLoc, captureSetValueAsResult());
  407. if (result.isInvalid()) return ExprError();
  408. addSemanticExpr(result.get());
  409. if (!captureSetValueAsResult() && !result.get()->getType()->isVoidType() &&
  410. (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
  411. setResultToLastSemantic();
  412. return complete(syntactic);
  413. }
  414. /// The basic skeleton for building an increment or decrement
  415. /// operation.
  416. ExprResult
  417. PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
  418. UnaryOperatorKind opcode,
  419. Expr *op) {
  420. assert(UnaryOperator::isIncrementDecrementOp(opcode));
  421. Expr *syntacticOp = rebuildAndCaptureObject(op);
  422. // Load the value.
  423. ExprResult result = buildGet();
  424. if (result.isInvalid()) return ExprError();
  425. QualType resultType = result.get()->getType();
  426. // That's the postfix result.
  427. if (UnaryOperator::isPostfix(opcode) &&
  428. (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
  429. result = capture(result.get());
  430. setResultToLastSemantic();
  431. }
  432. // Add or subtract a literal 1.
  433. llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
  434. Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
  435. GenericLoc);
  436. if (UnaryOperator::isIncrementOp(opcode)) {
  437. result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one);
  438. } else {
  439. result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one);
  440. }
  441. if (result.isInvalid()) return ExprError();
  442. // Store that back into the result. The value stored is the result
  443. // of a prefix operation.
  444. result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode) &&
  445. captureSetValueAsResult());
  446. if (result.isInvalid()) return ExprError();
  447. addSemanticExpr(result.get());
  448. if (UnaryOperator::isPrefix(opcode) && !captureSetValueAsResult() &&
  449. !result.get()->getType()->isVoidType() &&
  450. (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
  451. setResultToLastSemantic();
  452. UnaryOperator *syntactic =
  453. UnaryOperator::Create(S.Context, syntacticOp, opcode, resultType,
  454. VK_LValue, OK_Ordinary, opcLoc,
  455. !resultType->isDependentType()
  456. ? S.Context.getTypeSize(resultType) >=
  457. S.Context.getTypeSize(S.Context.IntTy)
  458. : false,
  459. S.CurFPFeatureOverrides());
  460. return complete(syntactic);
  461. }
  462. //===----------------------------------------------------------------------===//
  463. // Objective-C @property and implicit property references
  464. //===----------------------------------------------------------------------===//
  465. /// Look up a method in the receiver type of an Objective-C property
  466. /// reference.
  467. static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
  468. const ObjCPropertyRefExpr *PRE) {
  469. if (PRE->isObjectReceiver()) {
  470. const ObjCObjectPointerType *PT =
  471. PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
  472. // Special case for 'self' in class method implementations.
  473. if (PT->isObjCClassType() &&
  474. S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
  475. // This cast is safe because isSelfExpr is only true within
  476. // methods.
  477. ObjCMethodDecl *method =
  478. cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
  479. return S.LookupMethodInObjectType(sel,
  480. S.Context.getObjCInterfaceType(method->getClassInterface()),
  481. /*instance*/ false);
  482. }
  483. return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
  484. }
  485. if (PRE->isSuperReceiver()) {
  486. if (const ObjCObjectPointerType *PT =
  487. PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
  488. return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
  489. return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
  490. }
  491. assert(PRE->isClassReceiver() && "Invalid expression");
  492. QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
  493. return S.LookupMethodInObjectType(sel, IT, false);
  494. }
  495. bool ObjCPropertyOpBuilder::isWeakProperty() const {
  496. QualType T;
  497. if (RefExpr->isExplicitProperty()) {
  498. const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
  499. if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
  500. return true;
  501. T = Prop->getType();
  502. } else if (Getter) {
  503. T = Getter->getReturnType();
  504. } else {
  505. return false;
  506. }
  507. return T.getObjCLifetime() == Qualifiers::OCL_Weak;
  508. }
  509. bool ObjCPropertyOpBuilder::findGetter() {
  510. if (Getter) return true;
  511. // For implicit properties, just trust the lookup we already did.
  512. if (RefExpr->isImplicitProperty()) {
  513. if ((Getter = RefExpr->getImplicitPropertyGetter())) {
  514. GetterSelector = Getter->getSelector();
  515. return true;
  516. }
  517. else {
  518. // Must build the getter selector the hard way.
  519. ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
  520. assert(setter && "both setter and getter are null - cannot happen");
  521. IdentifierInfo *setterName =
  522. setter->getSelector().getIdentifierInfoForSlot(0);
  523. IdentifierInfo *getterName =
  524. &S.Context.Idents.get(setterName->getName().substr(3));
  525. GetterSelector =
  526. S.PP.getSelectorTable().getNullarySelector(getterName);
  527. return false;
  528. }
  529. }
  530. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
  531. Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
  532. return (Getter != nullptr);
  533. }
  534. /// Try to find the most accurate setter declaration for the property
  535. /// reference.
  536. ///
  537. /// \return true if a setter was found, in which case Setter
  538. bool ObjCPropertyOpBuilder::findSetter(bool warn) {
  539. // For implicit properties, just trust the lookup we already did.
  540. if (RefExpr->isImplicitProperty()) {
  541. if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
  542. Setter = setter;
  543. SetterSelector = setter->getSelector();
  544. return true;
  545. } else {
  546. IdentifierInfo *getterName =
  547. RefExpr->getImplicitPropertyGetter()->getSelector()
  548. .getIdentifierInfoForSlot(0);
  549. SetterSelector =
  550. SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
  551. S.PP.getSelectorTable(),
  552. getterName);
  553. return false;
  554. }
  555. }
  556. // For explicit properties, this is more involved.
  557. ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
  558. SetterSelector = prop->getSetterName();
  559. // Do a normal method lookup first.
  560. if (ObjCMethodDecl *setter =
  561. LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
  562. if (setter->isPropertyAccessor() && warn)
  563. if (const ObjCInterfaceDecl *IFace =
  564. dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
  565. StringRef thisPropertyName = prop->getName();
  566. // Try flipping the case of the first character.
  567. char front = thisPropertyName.front();
  568. front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
  569. SmallString<100> PropertyName = thisPropertyName;
  570. PropertyName[0] = front;
  571. IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
  572. if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(
  573. AltMember, prop->getQueryKind()))
  574. if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
  575. S.Diag(RefExpr->getExprLoc(), diag::err_property_setter_ambiguous_use)
  576. << prop << prop1 << setter->getSelector();
  577. S.Diag(prop->getLocation(), diag::note_property_declare);
  578. S.Diag(prop1->getLocation(), diag::note_property_declare);
  579. }
  580. }
  581. Setter = setter;
  582. return true;
  583. }
  584. // That can fail in the somewhat crazy situation that we're
  585. // type-checking a message send within the @interface declaration
  586. // that declared the @property. But it's not clear that that's
  587. // valuable to support.
  588. return false;
  589. }
  590. void ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() {
  591. if (S.getCurLexicalContext()->isObjCContainer() &&
  592. S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  593. S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) {
  594. if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) {
  595. S.Diag(RefExpr->getLocation(),
  596. diag::err_property_function_in_objc_container);
  597. S.Diag(prop->getLocation(), diag::note_property_declare);
  598. }
  599. }
  600. }
  601. /// Capture the base object of an Objective-C property expression.
  602. Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  603. assert(InstanceReceiver == nullptr);
  604. // If we have a base, capture it in an OVE and rebuild the syntactic
  605. // form to use the OVE as its base.
  606. if (RefExpr->isObjectReceiver()) {
  607. InstanceReceiver = capture(RefExpr->getBase());
  608. syntacticBase = Rebuilder(S, [=](Expr *, unsigned) -> Expr * {
  609. return InstanceReceiver;
  610. }).rebuild(syntacticBase);
  611. }
  612. if (ObjCPropertyRefExpr *
  613. refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
  614. SyntacticRefExpr = refE;
  615. return syntacticBase;
  616. }
  617. /// Load from an Objective-C property reference.
  618. ExprResult ObjCPropertyOpBuilder::buildGet() {
  619. findGetter();
  620. if (!Getter) {
  621. DiagnoseUnsupportedPropertyUse();
  622. return ExprError();
  623. }
  624. if (SyntacticRefExpr)
  625. SyntacticRefExpr->setIsMessagingGetter();
  626. QualType receiverType = RefExpr->getReceiverType(S.Context);
  627. if (!Getter->isImplicit())
  628. S.DiagnoseUseOfDecl(Getter, GenericLoc, nullptr, true);
  629. // Build a message-send.
  630. ExprResult msg;
  631. if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
  632. RefExpr->isObjectReceiver()) {
  633. assert(InstanceReceiver || RefExpr->isSuperReceiver());
  634. msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
  635. GenericLoc, Getter->getSelector(),
  636. Getter, std::nullopt);
  637. } else {
  638. msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
  639. GenericLoc, Getter->getSelector(), Getter,
  640. std::nullopt);
  641. }
  642. return msg;
  643. }
  644. /// Store to an Objective-C property reference.
  645. ///
  646. /// \param captureSetValueAsResult If true, capture the actual
  647. /// value being set as the value of the property operation.
  648. ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
  649. bool captureSetValueAsResult) {
  650. if (!findSetter(false)) {
  651. DiagnoseUnsupportedPropertyUse();
  652. return ExprError();
  653. }
  654. if (SyntacticRefExpr)
  655. SyntacticRefExpr->setIsMessagingSetter();
  656. QualType receiverType = RefExpr->getReceiverType(S.Context);
  657. // Use assignment constraints when possible; they give us better
  658. // diagnostics. "When possible" basically means anything except a
  659. // C++ class type.
  660. if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
  661. QualType paramType = (*Setter->param_begin())->getType()
  662. .substObjCMemberType(
  663. receiverType,
  664. Setter->getDeclContext(),
  665. ObjCSubstitutionContext::Parameter);
  666. if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
  667. ExprResult opResult = op;
  668. Sema::AssignConvertType assignResult
  669. = S.CheckSingleAssignmentConstraints(paramType, opResult);
  670. if (opResult.isInvalid() ||
  671. S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
  672. op->getType(), opResult.get(),
  673. Sema::AA_Assigning))
  674. return ExprError();
  675. op = opResult.get();
  676. assert(op && "successful assignment left argument invalid?");
  677. }
  678. }
  679. // Arguments.
  680. Expr *args[] = { op };
  681. // Build a message-send.
  682. ExprResult msg;
  683. if (!Setter->isImplicit())
  684. S.DiagnoseUseOfDecl(Setter, GenericLoc, nullptr, true);
  685. if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
  686. RefExpr->isObjectReceiver()) {
  687. msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
  688. GenericLoc, SetterSelector, Setter,
  689. MultiExprArg(args, 1));
  690. } else {
  691. msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
  692. GenericLoc,
  693. SetterSelector, Setter,
  694. MultiExprArg(args, 1));
  695. }
  696. if (!msg.isInvalid() && captureSetValueAsResult) {
  697. ObjCMessageExpr *msgExpr =
  698. cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
  699. Expr *arg = msgExpr->getArg(0);
  700. if (CanCaptureValue(arg))
  701. msgExpr->setArg(0, captureValueAsResult(arg));
  702. }
  703. return msg;
  704. }
  705. /// @property-specific behavior for doing lvalue-to-rvalue conversion.
  706. ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
  707. // Explicit properties always have getters, but implicit ones don't.
  708. // Check that before proceeding.
  709. if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
  710. S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
  711. << RefExpr->getSourceRange();
  712. return ExprError();
  713. }
  714. ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
  715. if (result.isInvalid()) return ExprError();
  716. if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
  717. S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
  718. Getter, RefExpr->getLocation());
  719. // As a special case, if the method returns 'id', try to get
  720. // a better type from the property.
  721. if (RefExpr->isExplicitProperty() && result.get()->isPRValue()) {
  722. QualType receiverType = RefExpr->getReceiverType(S.Context);
  723. QualType propType = RefExpr->getExplicitProperty()
  724. ->getUsageType(receiverType);
  725. if (result.get()->getType()->isObjCIdType()) {
  726. if (const ObjCObjectPointerType *ptr
  727. = propType->getAs<ObjCObjectPointerType>()) {
  728. if (!ptr->isObjCIdType())
  729. result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
  730. }
  731. }
  732. if (propType.getObjCLifetime() == Qualifiers::OCL_Weak &&
  733. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  734. RefExpr->getLocation()))
  735. S.getCurFunction()->markSafeWeakUse(RefExpr);
  736. }
  737. return result;
  738. }
  739. /// Try to build this as a call to a getter that returns a reference.
  740. ///
  741. /// \return true if it was possible, whether or not it actually
  742. /// succeeded
  743. bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
  744. ExprResult &result) {
  745. if (!S.getLangOpts().CPlusPlus) return false;
  746. findGetter();
  747. if (!Getter) {
  748. // The property has no setter and no getter! This can happen if the type is
  749. // invalid. Error have already been reported.
  750. result = ExprError();
  751. return true;
  752. }
  753. // Only do this if the getter returns an l-value reference type.
  754. QualType resultType = Getter->getReturnType();
  755. if (!resultType->isLValueReferenceType()) return false;
  756. result = buildRValueOperation(op);
  757. return true;
  758. }
  759. /// @property-specific behavior for doing assignments.
  760. ExprResult
  761. ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
  762. SourceLocation opcLoc,
  763. BinaryOperatorKind opcode,
  764. Expr *LHS, Expr *RHS) {
  765. assert(BinaryOperator::isAssignmentOp(opcode));
  766. // If there's no setter, we have no choice but to try to assign to
  767. // the result of the getter.
  768. if (!findSetter()) {
  769. ExprResult result;
  770. if (tryBuildGetOfReference(LHS, result)) {
  771. if (result.isInvalid()) return ExprError();
  772. return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS);
  773. }
  774. // Otherwise, it's an error.
  775. S.Diag(opcLoc, diag::err_nosetter_property_assignment)
  776. << unsigned(RefExpr->isImplicitProperty())
  777. << SetterSelector
  778. << LHS->getSourceRange() << RHS->getSourceRange();
  779. return ExprError();
  780. }
  781. // If there is a setter, we definitely want to use it.
  782. // Verify that we can do a compound assignment.
  783. if (opcode != BO_Assign && !findGetter()) {
  784. S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
  785. << LHS->getSourceRange() << RHS->getSourceRange();
  786. return ExprError();
  787. }
  788. ExprResult result =
  789. PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
  790. if (result.isInvalid()) return ExprError();
  791. // Various warnings about property assignments in ARC.
  792. if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
  793. S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
  794. S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
  795. }
  796. return result;
  797. }
  798. /// @property-specific behavior for doing increments and decrements.
  799. ExprResult
  800. ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
  801. UnaryOperatorKind opcode,
  802. Expr *op) {
  803. // If there's no setter, we have no choice but to try to assign to
  804. // the result of the getter.
  805. if (!findSetter()) {
  806. ExprResult result;
  807. if (tryBuildGetOfReference(op, result)) {
  808. if (result.isInvalid()) return ExprError();
  809. return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get());
  810. }
  811. // Otherwise, it's an error.
  812. S.Diag(opcLoc, diag::err_nosetter_property_incdec)
  813. << unsigned(RefExpr->isImplicitProperty())
  814. << unsigned(UnaryOperator::isDecrementOp(opcode))
  815. << SetterSelector
  816. << op->getSourceRange();
  817. return ExprError();
  818. }
  819. // If there is a setter, we definitely want to use it.
  820. // We also need a getter.
  821. if (!findGetter()) {
  822. assert(RefExpr->isImplicitProperty());
  823. S.Diag(opcLoc, diag::err_nogetter_property_incdec)
  824. << unsigned(UnaryOperator::isDecrementOp(opcode))
  825. << GetterSelector
  826. << op->getSourceRange();
  827. return ExprError();
  828. }
  829. return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
  830. }
  831. ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
  832. if (isWeakProperty() && !S.isUnevaluatedContext() &&
  833. !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  834. SyntacticForm->getBeginLoc()))
  835. S.getCurFunction()->recordUseOfWeak(SyntacticRefExpr,
  836. SyntacticRefExpr->isMessagingGetter());
  837. return PseudoOpBuilder::complete(SyntacticForm);
  838. }
  839. // ObjCSubscript build stuff.
  840. //
  841. /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
  842. /// conversion.
  843. /// FIXME. Remove this routine if it is proven that no additional
  844. /// specifity is needed.
  845. ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
  846. ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
  847. if (result.isInvalid()) return ExprError();
  848. return result;
  849. }
  850. /// objective-c subscripting-specific behavior for doing assignments.
  851. ExprResult
  852. ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
  853. SourceLocation opcLoc,
  854. BinaryOperatorKind opcode,
  855. Expr *LHS, Expr *RHS) {
  856. assert(BinaryOperator::isAssignmentOp(opcode));
  857. // There must be a method to do the Index'ed assignment.
  858. if (!findAtIndexSetter())
  859. return ExprError();
  860. // Verify that we can do a compound assignment.
  861. if (opcode != BO_Assign && !findAtIndexGetter())
  862. return ExprError();
  863. ExprResult result =
  864. PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
  865. if (result.isInvalid()) return ExprError();
  866. // Various warnings about objc Index'ed assignments in ARC.
  867. if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
  868. S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
  869. S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
  870. }
  871. return result;
  872. }
  873. /// Capture the base object of an Objective-C Index'ed expression.
  874. Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  875. assert(InstanceBase == nullptr);
  876. // Capture base expression in an OVE and rebuild the syntactic
  877. // form to use the OVE as its base expression.
  878. InstanceBase = capture(RefExpr->getBaseExpr());
  879. InstanceKey = capture(RefExpr->getKeyExpr());
  880. syntacticBase =
  881. Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
  882. switch (Idx) {
  883. case 0:
  884. return InstanceBase;
  885. case 1:
  886. return InstanceKey;
  887. default:
  888. llvm_unreachable("Unexpected index for ObjCSubscriptExpr");
  889. }
  890. }).rebuild(syntacticBase);
  891. return syntacticBase;
  892. }
  893. /// CheckSubscriptingKind - This routine decide what type
  894. /// of indexing represented by "FromE" is being done.
  895. Sema::ObjCSubscriptKind
  896. Sema::CheckSubscriptingKind(Expr *FromE) {
  897. // If the expression already has integral or enumeration type, we're golden.
  898. QualType T = FromE->getType();
  899. if (T->isIntegralOrEnumerationType())
  900. return OS_Array;
  901. // If we don't have a class type in C++, there's no way we can get an
  902. // expression of integral or enumeration type.
  903. const RecordType *RecordTy = T->getAs<RecordType>();
  904. if (!RecordTy &&
  905. (T->isObjCObjectPointerType() || T->isVoidPointerType()))
  906. // All other scalar cases are assumed to be dictionary indexing which
  907. // caller handles, with diagnostics if needed.
  908. return OS_Dictionary;
  909. if (!getLangOpts().CPlusPlus ||
  910. !RecordTy || RecordTy->isIncompleteType()) {
  911. // No indexing can be done. Issue diagnostics and quit.
  912. const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
  913. if (isa<StringLiteral>(IndexExpr))
  914. Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
  915. << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
  916. else
  917. Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
  918. << T;
  919. return OS_Error;
  920. }
  921. // We must have a complete class type.
  922. if (RequireCompleteType(FromE->getExprLoc(), T,
  923. diag::err_objc_index_incomplete_class_type, FromE))
  924. return OS_Error;
  925. // Look for a conversion to an integral, enumeration type, or
  926. // objective-C pointer type.
  927. int NoIntegrals=0, NoObjCIdPointers=0;
  928. SmallVector<CXXConversionDecl *, 4> ConversionDecls;
  929. for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
  930. ->getVisibleConversionFunctions()) {
  931. if (CXXConversionDecl *Conversion =
  932. dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
  933. QualType CT = Conversion->getConversionType().getNonReferenceType();
  934. if (CT->isIntegralOrEnumerationType()) {
  935. ++NoIntegrals;
  936. ConversionDecls.push_back(Conversion);
  937. }
  938. else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
  939. ++NoObjCIdPointers;
  940. ConversionDecls.push_back(Conversion);
  941. }
  942. }
  943. }
  944. if (NoIntegrals ==1 && NoObjCIdPointers == 0)
  945. return OS_Array;
  946. if (NoIntegrals == 0 && NoObjCIdPointers == 1)
  947. return OS_Dictionary;
  948. if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
  949. // No conversion function was found. Issue diagnostic and return.
  950. Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
  951. << FromE->getType();
  952. return OS_Error;
  953. }
  954. Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
  955. << FromE->getType();
  956. for (unsigned int i = 0; i < ConversionDecls.size(); i++)
  957. Diag(ConversionDecls[i]->getLocation(),
  958. diag::note_conv_function_declared_at);
  959. return OS_Error;
  960. }
  961. /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
  962. /// objects used as dictionary subscript key objects.
  963. static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
  964. Expr *Key) {
  965. if (ContainerT.isNull())
  966. return;
  967. // dictionary subscripting.
  968. // - (id)objectForKeyedSubscript:(id)key;
  969. IdentifierInfo *KeyIdents[] = {
  970. &S.Context.Idents.get("objectForKeyedSubscript")
  971. };
  972. Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  973. ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
  974. true /*instance*/);
  975. if (!Getter)
  976. return;
  977. QualType T = Getter->parameters()[0]->getType();
  978. S.CheckObjCConversion(Key->getSourceRange(), T, Key,
  979. Sema::CCK_ImplicitConversion);
  980. }
  981. bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
  982. if (AtIndexGetter)
  983. return true;
  984. Expr *BaseExpr = RefExpr->getBaseExpr();
  985. QualType BaseT = BaseExpr->getType();
  986. QualType ResultType;
  987. if (const ObjCObjectPointerType *PTy =
  988. BaseT->getAs<ObjCObjectPointerType>()) {
  989. ResultType = PTy->getPointeeType();
  990. }
  991. Sema::ObjCSubscriptKind Res =
  992. S.CheckSubscriptingKind(RefExpr->getKeyExpr());
  993. if (Res == Sema::OS_Error) {
  994. if (S.getLangOpts().ObjCAutoRefCount)
  995. CheckKeyForObjCARCConversion(S, ResultType,
  996. RefExpr->getKeyExpr());
  997. return false;
  998. }
  999. bool arrayRef = (Res == Sema::OS_Array);
  1000. if (ResultType.isNull()) {
  1001. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
  1002. << BaseExpr->getType() << arrayRef;
  1003. return false;
  1004. }
  1005. if (!arrayRef) {
  1006. // dictionary subscripting.
  1007. // - (id)objectForKeyedSubscript:(id)key;
  1008. IdentifierInfo *KeyIdents[] = {
  1009. &S.Context.Idents.get("objectForKeyedSubscript")
  1010. };
  1011. AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  1012. }
  1013. else {
  1014. // - (id)objectAtIndexedSubscript:(size_t)index;
  1015. IdentifierInfo *KeyIdents[] = {
  1016. &S.Context.Idents.get("objectAtIndexedSubscript")
  1017. };
  1018. AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
  1019. }
  1020. AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
  1021. true /*instance*/);
  1022. if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
  1023. AtIndexGetter = ObjCMethodDecl::Create(
  1024. S.Context, SourceLocation(), SourceLocation(), AtIndexGetterSelector,
  1025. S.Context.getObjCIdType() /*ReturnType*/, nullptr /*TypeSourceInfo */,
  1026. S.Context.getTranslationUnitDecl(), true /*Instance*/,
  1027. false /*isVariadic*/,
  1028. /*isPropertyAccessor=*/false,
  1029. /*isSynthesizedAccessorStub=*/false,
  1030. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  1031. ObjCMethodDecl::Required, false);
  1032. ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
  1033. SourceLocation(), SourceLocation(),
  1034. arrayRef ? &S.Context.Idents.get("index")
  1035. : &S.Context.Idents.get("key"),
  1036. arrayRef ? S.Context.UnsignedLongTy
  1037. : S.Context.getObjCIdType(),
  1038. /*TInfo=*/nullptr,
  1039. SC_None,
  1040. nullptr);
  1041. AtIndexGetter->setMethodParams(S.Context, Argument, std::nullopt);
  1042. }
  1043. if (!AtIndexGetter) {
  1044. if (!BaseT->isObjCIdType()) {
  1045. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
  1046. << BaseExpr->getType() << 0 << arrayRef;
  1047. return false;
  1048. }
  1049. AtIndexGetter =
  1050. S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
  1051. RefExpr->getSourceRange(),
  1052. true);
  1053. }
  1054. if (AtIndexGetter) {
  1055. QualType T = AtIndexGetter->parameters()[0]->getType();
  1056. if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
  1057. (!arrayRef && !T->isObjCObjectPointerType())) {
  1058. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1059. arrayRef ? diag::err_objc_subscript_index_type
  1060. : diag::err_objc_subscript_key_type) << T;
  1061. S.Diag(AtIndexGetter->parameters()[0]->getLocation(),
  1062. diag::note_parameter_type) << T;
  1063. return false;
  1064. }
  1065. QualType R = AtIndexGetter->getReturnType();
  1066. if (!R->isObjCObjectPointerType()) {
  1067. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1068. diag::err_objc_indexing_method_result_type) << R << arrayRef;
  1069. S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
  1070. AtIndexGetter->getDeclName();
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
  1076. if (AtIndexSetter)
  1077. return true;
  1078. Expr *BaseExpr = RefExpr->getBaseExpr();
  1079. QualType BaseT = BaseExpr->getType();
  1080. QualType ResultType;
  1081. if (const ObjCObjectPointerType *PTy =
  1082. BaseT->getAs<ObjCObjectPointerType>()) {
  1083. ResultType = PTy->getPointeeType();
  1084. }
  1085. Sema::ObjCSubscriptKind Res =
  1086. S.CheckSubscriptingKind(RefExpr->getKeyExpr());
  1087. if (Res == Sema::OS_Error) {
  1088. if (S.getLangOpts().ObjCAutoRefCount)
  1089. CheckKeyForObjCARCConversion(S, ResultType,
  1090. RefExpr->getKeyExpr());
  1091. return false;
  1092. }
  1093. bool arrayRef = (Res == Sema::OS_Array);
  1094. if (ResultType.isNull()) {
  1095. S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
  1096. << BaseExpr->getType() << arrayRef;
  1097. return false;
  1098. }
  1099. if (!arrayRef) {
  1100. // dictionary subscripting.
  1101. // - (void)setObject:(id)object forKeyedSubscript:(id)key;
  1102. IdentifierInfo *KeyIdents[] = {
  1103. &S.Context.Idents.get("setObject"),
  1104. &S.Context.Idents.get("forKeyedSubscript")
  1105. };
  1106. AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
  1107. }
  1108. else {
  1109. // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
  1110. IdentifierInfo *KeyIdents[] = {
  1111. &S.Context.Idents.get("setObject"),
  1112. &S.Context.Idents.get("atIndexedSubscript")
  1113. };
  1114. AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
  1115. }
  1116. AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
  1117. true /*instance*/);
  1118. if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
  1119. TypeSourceInfo *ReturnTInfo = nullptr;
  1120. QualType ReturnType = S.Context.VoidTy;
  1121. AtIndexSetter = ObjCMethodDecl::Create(
  1122. S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
  1123. ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
  1124. true /*Instance*/, false /*isVariadic*/,
  1125. /*isPropertyAccessor=*/false,
  1126. /*isSynthesizedAccessorStub=*/false,
  1127. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  1128. ObjCMethodDecl::Required, false);
  1129. SmallVector<ParmVarDecl *, 2> Params;
  1130. ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
  1131. SourceLocation(), SourceLocation(),
  1132. &S.Context.Idents.get("object"),
  1133. S.Context.getObjCIdType(),
  1134. /*TInfo=*/nullptr,
  1135. SC_None,
  1136. nullptr);
  1137. Params.push_back(object);
  1138. ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
  1139. SourceLocation(), SourceLocation(),
  1140. arrayRef ? &S.Context.Idents.get("index")
  1141. : &S.Context.Idents.get("key"),
  1142. arrayRef ? S.Context.UnsignedLongTy
  1143. : S.Context.getObjCIdType(),
  1144. /*TInfo=*/nullptr,
  1145. SC_None,
  1146. nullptr);
  1147. Params.push_back(key);
  1148. AtIndexSetter->setMethodParams(S.Context, Params, std::nullopt);
  1149. }
  1150. if (!AtIndexSetter) {
  1151. if (!BaseT->isObjCIdType()) {
  1152. S.Diag(BaseExpr->getExprLoc(),
  1153. diag::err_objc_subscript_method_not_found)
  1154. << BaseExpr->getType() << 1 << arrayRef;
  1155. return false;
  1156. }
  1157. AtIndexSetter =
  1158. S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
  1159. RefExpr->getSourceRange(),
  1160. true);
  1161. }
  1162. bool err = false;
  1163. if (AtIndexSetter && arrayRef) {
  1164. QualType T = AtIndexSetter->parameters()[1]->getType();
  1165. if (!T->isIntegralOrEnumerationType()) {
  1166. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1167. diag::err_objc_subscript_index_type) << T;
  1168. S.Diag(AtIndexSetter->parameters()[1]->getLocation(),
  1169. diag::note_parameter_type) << T;
  1170. err = true;
  1171. }
  1172. T = AtIndexSetter->parameters()[0]->getType();
  1173. if (!T->isObjCObjectPointerType()) {
  1174. S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
  1175. diag::err_objc_subscript_object_type) << T << arrayRef;
  1176. S.Diag(AtIndexSetter->parameters()[0]->getLocation(),
  1177. diag::note_parameter_type) << T;
  1178. err = true;
  1179. }
  1180. }
  1181. else if (AtIndexSetter && !arrayRef)
  1182. for (unsigned i=0; i <2; i++) {
  1183. QualType T = AtIndexSetter->parameters()[i]->getType();
  1184. if (!T->isObjCObjectPointerType()) {
  1185. if (i == 1)
  1186. S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
  1187. diag::err_objc_subscript_key_type) << T;
  1188. else
  1189. S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
  1190. diag::err_objc_subscript_dic_object_type) << T;
  1191. S.Diag(AtIndexSetter->parameters()[i]->getLocation(),
  1192. diag::note_parameter_type) << T;
  1193. err = true;
  1194. }
  1195. }
  1196. return !err;
  1197. }
  1198. // Get the object at "Index" position in the container.
  1199. // [BaseExpr objectAtIndexedSubscript : IndexExpr];
  1200. ExprResult ObjCSubscriptOpBuilder::buildGet() {
  1201. if (!findAtIndexGetter())
  1202. return ExprError();
  1203. QualType receiverType = InstanceBase->getType();
  1204. // Build a message-send.
  1205. ExprResult msg;
  1206. Expr *Index = InstanceKey;
  1207. // Arguments.
  1208. Expr *args[] = { Index };
  1209. assert(InstanceBase);
  1210. if (AtIndexGetter)
  1211. S.DiagnoseUseOfDecl(AtIndexGetter, GenericLoc);
  1212. msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
  1213. GenericLoc,
  1214. AtIndexGetterSelector, AtIndexGetter,
  1215. MultiExprArg(args, 1));
  1216. return msg;
  1217. }
  1218. /// Store into the container the "op" object at "Index"'ed location
  1219. /// by building this messaging expression:
  1220. /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
  1221. /// \param captureSetValueAsResult If true, capture the actual
  1222. /// value being set as the value of the property operation.
  1223. ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
  1224. bool captureSetValueAsResult) {
  1225. if (!findAtIndexSetter())
  1226. return ExprError();
  1227. if (AtIndexSetter)
  1228. S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc);
  1229. QualType receiverType = InstanceBase->getType();
  1230. Expr *Index = InstanceKey;
  1231. // Arguments.
  1232. Expr *args[] = { op, Index };
  1233. // Build a message-send.
  1234. ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
  1235. GenericLoc,
  1236. AtIndexSetterSelector,
  1237. AtIndexSetter,
  1238. MultiExprArg(args, 2));
  1239. if (!msg.isInvalid() && captureSetValueAsResult) {
  1240. ObjCMessageExpr *msgExpr =
  1241. cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
  1242. Expr *arg = msgExpr->getArg(0);
  1243. if (CanCaptureValue(arg))
  1244. msgExpr->setArg(0, captureValueAsResult(arg));
  1245. }
  1246. return msg;
  1247. }
  1248. //===----------------------------------------------------------------------===//
  1249. // MSVC __declspec(property) references
  1250. //===----------------------------------------------------------------------===//
  1251. MSPropertyRefExpr *
  1252. MSPropertyOpBuilder::getBaseMSProperty(MSPropertySubscriptExpr *E) {
  1253. CallArgs.insert(CallArgs.begin(), E->getIdx());
  1254. Expr *Base = E->getBase()->IgnoreParens();
  1255. while (auto *MSPropSubscript = dyn_cast<MSPropertySubscriptExpr>(Base)) {
  1256. CallArgs.insert(CallArgs.begin(), MSPropSubscript->getIdx());
  1257. Base = MSPropSubscript->getBase()->IgnoreParens();
  1258. }
  1259. return cast<MSPropertyRefExpr>(Base);
  1260. }
  1261. Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
  1262. InstanceBase = capture(RefExpr->getBaseExpr());
  1263. llvm::for_each(CallArgs, [this](Expr *&Arg) { Arg = capture(Arg); });
  1264. syntacticBase = Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
  1265. switch (Idx) {
  1266. case 0:
  1267. return InstanceBase;
  1268. default:
  1269. assert(Idx <= CallArgs.size());
  1270. return CallArgs[Idx - 1];
  1271. }
  1272. }).rebuild(syntacticBase);
  1273. return syntacticBase;
  1274. }
  1275. ExprResult MSPropertyOpBuilder::buildGet() {
  1276. if (!RefExpr->getPropertyDecl()->hasGetter()) {
  1277. S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
  1278. << 0 /* getter */ << RefExpr->getPropertyDecl();
  1279. return ExprError();
  1280. }
  1281. UnqualifiedId GetterName;
  1282. IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
  1283. GetterName.setIdentifier(II, RefExpr->getMemberLoc());
  1284. CXXScopeSpec SS;
  1285. SS.Adopt(RefExpr->getQualifierLoc());
  1286. ExprResult GetterExpr =
  1287. S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
  1288. RefExpr->isArrow() ? tok::arrow : tok::period, SS,
  1289. SourceLocation(), GetterName, nullptr);
  1290. if (GetterExpr.isInvalid()) {
  1291. S.Diag(RefExpr->getMemberLoc(),
  1292. diag::err_cannot_find_suitable_accessor) << 0 /* getter */
  1293. << RefExpr->getPropertyDecl();
  1294. return ExprError();
  1295. }
  1296. return S.BuildCallExpr(S.getCurScope(), GetterExpr.get(),
  1297. RefExpr->getSourceRange().getBegin(), CallArgs,
  1298. RefExpr->getSourceRange().getEnd());
  1299. }
  1300. ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
  1301. bool captureSetValueAsResult) {
  1302. if (!RefExpr->getPropertyDecl()->hasSetter()) {
  1303. S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
  1304. << 1 /* setter */ << RefExpr->getPropertyDecl();
  1305. return ExprError();
  1306. }
  1307. UnqualifiedId SetterName;
  1308. IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
  1309. SetterName.setIdentifier(II, RefExpr->getMemberLoc());
  1310. CXXScopeSpec SS;
  1311. SS.Adopt(RefExpr->getQualifierLoc());
  1312. ExprResult SetterExpr =
  1313. S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
  1314. RefExpr->isArrow() ? tok::arrow : tok::period, SS,
  1315. SourceLocation(), SetterName, nullptr);
  1316. if (SetterExpr.isInvalid()) {
  1317. S.Diag(RefExpr->getMemberLoc(),
  1318. diag::err_cannot_find_suitable_accessor) << 1 /* setter */
  1319. << RefExpr->getPropertyDecl();
  1320. return ExprError();
  1321. }
  1322. SmallVector<Expr*, 4> ArgExprs;
  1323. ArgExprs.append(CallArgs.begin(), CallArgs.end());
  1324. ArgExprs.push_back(op);
  1325. return S.BuildCallExpr(S.getCurScope(), SetterExpr.get(),
  1326. RefExpr->getSourceRange().getBegin(), ArgExprs,
  1327. op->getSourceRange().getEnd());
  1328. }
  1329. //===----------------------------------------------------------------------===//
  1330. // General Sema routines.
  1331. //===----------------------------------------------------------------------===//
  1332. ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
  1333. Expr *opaqueRef = E->IgnoreParens();
  1334. if (ObjCPropertyRefExpr *refExpr
  1335. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1336. ObjCPropertyOpBuilder builder(*this, refExpr, true);
  1337. return builder.buildRValueOperation(E);
  1338. }
  1339. else if (ObjCSubscriptRefExpr *refExpr
  1340. = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
  1341. ObjCSubscriptOpBuilder builder(*this, refExpr, true);
  1342. return builder.buildRValueOperation(E);
  1343. } else if (MSPropertyRefExpr *refExpr
  1344. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1345. MSPropertyOpBuilder builder(*this, refExpr, true);
  1346. return builder.buildRValueOperation(E);
  1347. } else if (MSPropertySubscriptExpr *RefExpr =
  1348. dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1349. MSPropertyOpBuilder Builder(*this, RefExpr, true);
  1350. return Builder.buildRValueOperation(E);
  1351. } else {
  1352. llvm_unreachable("unknown pseudo-object kind!");
  1353. }
  1354. }
  1355. /// Check an increment or decrement of a pseudo-object expression.
  1356. ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
  1357. UnaryOperatorKind opcode, Expr *op) {
  1358. // Do nothing if the operand is dependent.
  1359. if (op->isTypeDependent())
  1360. return UnaryOperator::Create(Context, op, opcode, Context.DependentTy,
  1361. VK_PRValue, OK_Ordinary, opcLoc, false,
  1362. CurFPFeatureOverrides());
  1363. assert(UnaryOperator::isIncrementDecrementOp(opcode));
  1364. Expr *opaqueRef = op->IgnoreParens();
  1365. if (ObjCPropertyRefExpr *refExpr
  1366. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1367. ObjCPropertyOpBuilder builder(*this, refExpr, false);
  1368. return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1369. } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
  1370. Diag(opcLoc, diag::err_illegal_container_subscripting_op);
  1371. return ExprError();
  1372. } else if (MSPropertyRefExpr *refExpr
  1373. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1374. MSPropertyOpBuilder builder(*this, refExpr, false);
  1375. return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1376. } else if (MSPropertySubscriptExpr *RefExpr
  1377. = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1378. MSPropertyOpBuilder Builder(*this, RefExpr, false);
  1379. return Builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
  1380. } else {
  1381. llvm_unreachable("unknown pseudo-object kind!");
  1382. }
  1383. }
  1384. ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
  1385. BinaryOperatorKind opcode,
  1386. Expr *LHS, Expr *RHS) {
  1387. // Do nothing if either argument is dependent.
  1388. if (LHS->isTypeDependent() || RHS->isTypeDependent())
  1389. return BinaryOperator::Create(Context, LHS, RHS, opcode,
  1390. Context.DependentTy, VK_PRValue, OK_Ordinary,
  1391. opcLoc, CurFPFeatureOverrides());
  1392. // Filter out non-overload placeholder types in the RHS.
  1393. if (RHS->getType()->isNonOverloadPlaceholderType()) {
  1394. ExprResult result = CheckPlaceholderExpr(RHS);
  1395. if (result.isInvalid()) return ExprError();
  1396. RHS = result.get();
  1397. }
  1398. bool IsSimpleAssign = opcode == BO_Assign;
  1399. Expr *opaqueRef = LHS->IgnoreParens();
  1400. if (ObjCPropertyRefExpr *refExpr
  1401. = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
  1402. ObjCPropertyOpBuilder builder(*this, refExpr, IsSimpleAssign);
  1403. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1404. } else if (ObjCSubscriptRefExpr *refExpr
  1405. = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
  1406. ObjCSubscriptOpBuilder builder(*this, refExpr, IsSimpleAssign);
  1407. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1408. } else if (MSPropertyRefExpr *refExpr
  1409. = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
  1410. MSPropertyOpBuilder builder(*this, refExpr, IsSimpleAssign);
  1411. return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1412. } else if (MSPropertySubscriptExpr *RefExpr
  1413. = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
  1414. MSPropertyOpBuilder Builder(*this, RefExpr, IsSimpleAssign);
  1415. return Builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
  1416. } else {
  1417. llvm_unreachable("unknown pseudo-object kind!");
  1418. }
  1419. }
  1420. /// Given a pseudo-object reference, rebuild it without the opaque
  1421. /// values. Basically, undo the behavior of rebuildAndCaptureObject.
  1422. /// This should never operate in-place.
  1423. static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
  1424. return Rebuilder(S,
  1425. [=](Expr *E, unsigned) -> Expr * {
  1426. return cast<OpaqueValueExpr>(E)->getSourceExpr();
  1427. })
  1428. .rebuild(E);
  1429. }
  1430. /// Given a pseudo-object expression, recreate what it looks like
  1431. /// syntactically without the attendant OpaqueValueExprs.
  1432. ///
  1433. /// This is a hack which should be removed when TreeTransform is
  1434. /// capable of rebuilding a tree without stripping implicit
  1435. /// operations.
  1436. Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
  1437. Expr *syntax = E->getSyntacticForm();
  1438. if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
  1439. Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
  1440. return UnaryOperator::Create(Context, op, uop->getOpcode(), uop->getType(),
  1441. uop->getValueKind(), uop->getObjectKind(),
  1442. uop->getOperatorLoc(), uop->canOverflow(),
  1443. CurFPFeatureOverrides());
  1444. } else if (CompoundAssignOperator *cop
  1445. = dyn_cast<CompoundAssignOperator>(syntax)) {
  1446. Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
  1447. Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
  1448. return CompoundAssignOperator::Create(
  1449. Context, lhs, rhs, cop->getOpcode(), cop->getType(),
  1450. cop->getValueKind(), cop->getObjectKind(), cop->getOperatorLoc(),
  1451. CurFPFeatureOverrides(), cop->getComputationLHSType(),
  1452. cop->getComputationResultType());
  1453. } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
  1454. Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
  1455. Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
  1456. return BinaryOperator::Create(Context, lhs, rhs, bop->getOpcode(),
  1457. bop->getType(), bop->getValueKind(),
  1458. bop->getObjectKind(), bop->getOperatorLoc(),
  1459. CurFPFeatureOverrides());
  1460. } else if (isa<CallExpr>(syntax)) {
  1461. return syntax;
  1462. } else {
  1463. assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
  1464. return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
  1465. }
  1466. }