SemaPseudoObject.cpp 65 KB

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