clang 19.0.0git
SemaPseudoObject.cpp
Go to the documentation of this file.
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
33#include "clang/AST/ExprCXX.h"
34#include "clang/AST/ExprObjC.h"
39#include "llvm/ADT/SmallString.h"
40
41using namespace clang;
42using namespace sema;
43
44namespace {
45 // Basically just a very focused copy of TreeTransform.
46 struct Rebuilder {
47 Sema &S;
48 unsigned MSPropertySubscriptCount;
49 typedef llvm::function_ref<Expr *(Expr *, unsigned)> SpecificRebuilderRefTy;
50 const SpecificRebuilderRefTy &SpecificCallback;
51 Rebuilder(Sema &S, const SpecificRebuilderRefTy &SpecificCallback)
52 : S(S), MSPropertySubscriptCount(0),
53 SpecificCallback(SpecificCallback) {}
54
55 Expr *rebuildObjCPropertyRefExpr(ObjCPropertyRefExpr *refExpr) {
56 // Fortunately, the constraint that we're rebuilding something
57 // with a base limits the number of cases here.
58 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
59 return refExpr;
60
61 if (refExpr->isExplicitProperty()) {
62 return new (S.Context) ObjCPropertyRefExpr(
63 refExpr->getExplicitProperty(), refExpr->getType(),
64 refExpr->getValueKind(), refExpr->getObjectKind(),
65 refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
66 }
67 return new (S.Context) ObjCPropertyRefExpr(
69 refExpr->getImplicitPropertySetter(), refExpr->getType(),
70 refExpr->getValueKind(), refExpr->getObjectKind(),
71 refExpr->getLocation(), SpecificCallback(refExpr->getBase(), 0));
72 }
73 Expr *rebuildObjCSubscriptRefExpr(ObjCSubscriptRefExpr *refExpr) {
74 assert(refExpr->getBaseExpr());
75 assert(refExpr->getKeyExpr());
76
77 return new (S.Context) ObjCSubscriptRefExpr(
78 SpecificCallback(refExpr->getBaseExpr(), 0),
79 SpecificCallback(refExpr->getKeyExpr(), 1), refExpr->getType(),
80 refExpr->getValueKind(), refExpr->getObjectKind(),
81 refExpr->getAtIndexMethodDecl(), refExpr->setAtIndexMethodDecl(),
82 refExpr->getRBracket());
83 }
84 Expr *rebuildMSPropertyRefExpr(MSPropertyRefExpr *refExpr) {
85 assert(refExpr->getBaseExpr());
86
87 return new (S.Context) MSPropertyRefExpr(
88 SpecificCallback(refExpr->getBaseExpr(), 0),
89 refExpr->getPropertyDecl(), refExpr->isArrow(), refExpr->getType(),
90 refExpr->getValueKind(), refExpr->getQualifierLoc(),
91 refExpr->getMemberLoc());
92 }
93 Expr *rebuildMSPropertySubscriptExpr(MSPropertySubscriptExpr *refExpr) {
94 assert(refExpr->getBase());
95 assert(refExpr->getIdx());
96
97 auto *NewBase = rebuild(refExpr->getBase());
98 ++MSPropertySubscriptCount;
99 return new (S.Context) MSPropertySubscriptExpr(
100 NewBase,
101 SpecificCallback(refExpr->getIdx(), MSPropertySubscriptCount),
102 refExpr->getType(), refExpr->getValueKind(), refExpr->getObjectKind(),
103 refExpr->getRBracketLoc());
104 }
105
106 Expr *rebuild(Expr *e) {
107 // Fast path: nothing to look through.
108 if (auto *PRE = dyn_cast<ObjCPropertyRefExpr>(e))
109 return rebuildObjCPropertyRefExpr(PRE);
110 if (auto *SRE = dyn_cast<ObjCSubscriptRefExpr>(e))
111 return rebuildObjCSubscriptRefExpr(SRE);
112 if (auto *MSPRE = dyn_cast<MSPropertyRefExpr>(e))
113 return rebuildMSPropertyRefExpr(MSPRE);
114 if (auto *MSPSE = dyn_cast<MSPropertySubscriptExpr>(e))
115 return rebuildMSPropertySubscriptExpr(MSPSE);
116
117 // Otherwise, we should look through and rebuild anything that
118 // IgnoreParens would.
119
120 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
121 e = rebuild(parens->getSubExpr());
122 return new (S.Context) ParenExpr(parens->getLParen(),
123 parens->getRParen(),
124 e);
125 }
126
127 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
128 assert(uop->getOpcode() == UO_Extension);
129 e = rebuild(uop->getSubExpr());
131 S.Context, e, uop->getOpcode(), uop->getType(), uop->getValueKind(),
132 uop->getObjectKind(), uop->getOperatorLoc(), uop->canOverflow(),
134 }
135
136 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
137 assert(!gse->isResultDependent());
138 unsigned resultIndex = gse->getResultIndex();
139 unsigned numAssocs = gse->getNumAssocs();
140
141 SmallVector<Expr *, 8> assocExprs;
143 assocExprs.reserve(numAssocs);
144 assocTypes.reserve(numAssocs);
145
146 for (const GenericSelectionExpr::Association assoc :
147 gse->associations()) {
148 Expr *assocExpr = assoc.getAssociationExpr();
149 if (assoc.isSelected())
150 assocExpr = rebuild(assocExpr);
151 assocExprs.push_back(assocExpr);
152 assocTypes.push_back(assoc.getTypeSourceInfo());
153 }
154
155 if (gse->isExprPredicate())
157 S.Context, gse->getGenericLoc(), gse->getControllingExpr(),
158 assocTypes, assocExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
159 gse->containsUnexpandedParameterPack(), resultIndex);
161 S.Context, gse->getGenericLoc(), gse->getControllingType(),
162 assocTypes, assocExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
163 gse->containsUnexpandedParameterPack(), resultIndex);
164 }
165
166 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
167 assert(!ce->isConditionDependent());
168
169 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
170 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
171 rebuiltExpr = rebuild(rebuiltExpr);
172
173 return new (S.Context)
174 ChooseExpr(ce->getBuiltinLoc(), ce->getCond(), LHS, RHS,
175 rebuiltExpr->getType(), rebuiltExpr->getValueKind(),
176 rebuiltExpr->getObjectKind(), ce->getRParenLoc(),
177 ce->isConditionTrue());
178 }
179
180 llvm_unreachable("bad expression to rebuild!");
181 }
182 };
183
184 class PseudoOpBuilder {
185 public:
186 Sema &S;
187 unsigned ResultIndex;
188 SourceLocation GenericLoc;
189 bool IsUnique;
190 SmallVector<Expr *, 4> Semantics;
191
192 PseudoOpBuilder(Sema &S, SourceLocation genericLoc, bool IsUnique)
193 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
194 GenericLoc(genericLoc), IsUnique(IsUnique) {}
195
196 virtual ~PseudoOpBuilder() {}
197
198 /// Add a normal semantic expression.
199 void addSemanticExpr(Expr *semantic) {
200 Semantics.push_back(semantic);
201 }
202
203 /// Add the 'result' semantic expression.
204 void addResultSemanticExpr(Expr *resultExpr) {
205 assert(ResultIndex == PseudoObjectExpr::NoResult);
206 ResultIndex = Semantics.size();
207 Semantics.push_back(resultExpr);
208 // An OVE is not unique if it is used as the result expression.
209 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantics.back()))
210 OVE->setIsUnique(false);
211 }
212
213 ExprResult buildRValueOperation(Expr *op);
214 ExprResult buildAssignmentOperation(Scope *Sc,
215 SourceLocation opLoc,
216 BinaryOperatorKind opcode,
217 Expr *LHS, Expr *RHS);
218 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
219 UnaryOperatorKind opcode,
220 Expr *op);
221
222 virtual ExprResult complete(Expr *syntacticForm);
223
224 OpaqueValueExpr *capture(Expr *op);
225 OpaqueValueExpr *captureValueAsResult(Expr *op);
226
227 void setResultToLastSemantic() {
228 assert(ResultIndex == PseudoObjectExpr::NoResult);
229 ResultIndex = Semantics.size() - 1;
230 // An OVE is not unique if it is used as the result expression.
231 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantics.back()))
232 OVE->setIsUnique(false);
233 }
234
235 /// Return true if assignments have a non-void result.
236 static bool CanCaptureValue(Expr *exp) {
237 if (exp->isGLValue())
238 return true;
239 QualType ty = exp->getType();
240 assert(!ty->isIncompleteType());
241 assert(!ty->isDependentType());
242
243 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
244 return ClassDecl->isTriviallyCopyable();
245 return true;
246 }
247
248 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
249 virtual ExprResult buildGet() = 0;
250 virtual ExprResult buildSet(Expr *, SourceLocation,
251 bool captureSetValueAsResult) = 0;
252 /// Should the result of an assignment be the formal result of the
253 /// setter call or the value that was passed to the setter?
254 ///
255 /// Different pseudo-object language features use different language rules
256 /// for this.
257 /// The default is to use the set value. Currently, this affects the
258 /// behavior of simple assignments, compound assignments, and prefix
259 /// increment and decrement.
260 /// Postfix increment and decrement always use the getter result as the
261 /// expression result.
262 ///
263 /// If this method returns true, and the set value isn't capturable for
264 /// some reason, the result of the expression will be void.
265 virtual bool captureSetValueAsResult() const { return true; }
266 };
267
268 /// A PseudoOpBuilder for Objective-C \@properties.
269 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
270 ObjCPropertyRefExpr *RefExpr;
271 ObjCPropertyRefExpr *SyntacticRefExpr;
272 OpaqueValueExpr *InstanceReceiver;
273 ObjCMethodDecl *Getter;
274
275 ObjCMethodDecl *Setter;
276 Selector SetterSelector;
277 Selector GetterSelector;
278
279 public:
280 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr, bool IsUnique)
281 : PseudoOpBuilder(S, refExpr->getLocation(), IsUnique),
282 RefExpr(refExpr), SyntacticRefExpr(nullptr),
283 InstanceReceiver(nullptr), Getter(nullptr), Setter(nullptr) {
284 }
285
286 ExprResult buildRValueOperation(Expr *op);
287 ExprResult buildAssignmentOperation(Scope *Sc,
288 SourceLocation opLoc,
289 BinaryOperatorKind opcode,
290 Expr *LHS, Expr *RHS);
291 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
292 UnaryOperatorKind opcode,
293 Expr *op);
294
295 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
296 bool findSetter(bool warn=true);
297 bool findGetter();
298 void DiagnoseUnsupportedPropertyUse();
299
300 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
301 ExprResult buildGet() override;
302 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
303 ExprResult complete(Expr *SyntacticForm) override;
304
305 bool isWeakProperty() const;
306 };
307
308 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
309 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
310 ObjCSubscriptRefExpr *RefExpr;
311 OpaqueValueExpr *InstanceBase;
312 OpaqueValueExpr *InstanceKey;
313 ObjCMethodDecl *AtIndexGetter;
314 Selector AtIndexGetterSelector;
315
316 ObjCMethodDecl *AtIndexSetter;
317 Selector AtIndexSetterSelector;
318
319 public:
320 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr, bool IsUnique)
321 : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
322 RefExpr(refExpr), InstanceBase(nullptr), InstanceKey(nullptr),
323 AtIndexGetter(nullptr), AtIndexSetter(nullptr) {}
324
325 ExprResult buildRValueOperation(Expr *op);
326 ExprResult buildAssignmentOperation(Scope *Sc,
327 SourceLocation opLoc,
328 BinaryOperatorKind opcode,
329 Expr *LHS, Expr *RHS);
330 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
331
332 bool findAtIndexGetter();
333 bool findAtIndexSetter();
334
335 ExprResult buildGet() override;
336 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
337 };
338
339 class MSPropertyOpBuilder : public PseudoOpBuilder {
340 MSPropertyRefExpr *RefExpr;
341 OpaqueValueExpr *InstanceBase;
342 SmallVector<Expr *, 4> CallArgs;
343
344 MSPropertyRefExpr *getBaseMSProperty(MSPropertySubscriptExpr *E);
345
346 public:
347 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr, bool IsUnique)
348 : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
349 RefExpr(refExpr), InstanceBase(nullptr) {}
350 MSPropertyOpBuilder(Sema &S, MSPropertySubscriptExpr *refExpr, bool IsUnique)
351 : PseudoOpBuilder(S, refExpr->getSourceRange().getBegin(), IsUnique),
352 InstanceBase(nullptr) {
353 RefExpr = getBaseMSProperty(refExpr);
354 }
355
356 Expr *rebuildAndCaptureObject(Expr *) override;
357 ExprResult buildGet() override;
358 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
359 bool captureSetValueAsResult() const override { return false; }
360 };
361}
362
363/// Capture the given expression in an OpaqueValueExpr.
364OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
365 // Make a new OVE whose source is the given expression.
366 OpaqueValueExpr *captured =
367 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
368 e->getValueKind(), e->getObjectKind(),
369 e);
370 if (IsUnique)
371 captured->setIsUnique(true);
372
373 // Make sure we bind that in the semantics.
374 addSemanticExpr(captured);
375 return captured;
376}
377
378/// Capture the given expression as the result of this pseudo-object
379/// operation. This routine is safe against expressions which may
380/// already be captured.
381///
382/// \returns the captured expression, which will be the
383/// same as the input if the input was already captured
384OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
385 assert(ResultIndex == PseudoObjectExpr::NoResult);
386
387 // If the expression hasn't already been captured, just capture it
388 // and set the new semantic
389 if (!isa<OpaqueValueExpr>(e)) {
390 OpaqueValueExpr *cap = capture(e);
391 setResultToLastSemantic();
392 return cap;
393 }
394
395 // Otherwise, it must already be one of our semantic expressions;
396 // set ResultIndex to its index.
397 unsigned index = 0;
398 for (;; ++index) {
399 assert(index < Semantics.size() &&
400 "captured expression not found in semantics!");
401 if (e == Semantics[index]) break;
402 }
403 ResultIndex = index;
404 // An OVE is not unique if it is used as the result expression.
405 cast<OpaqueValueExpr>(e)->setIsUnique(false);
406 return cast<OpaqueValueExpr>(e);
407}
408
409/// The routine which creates the final PseudoObjectExpr.
410ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
411 return PseudoObjectExpr::Create(S.Context, syntactic,
412 Semantics, ResultIndex);
413}
414
415/// The main skeleton for building an r-value operation.
416ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
417 Expr *syntacticBase = rebuildAndCaptureObject(op);
418
419 ExprResult getExpr = buildGet();
420 if (getExpr.isInvalid()) return ExprError();
421 addResultSemanticExpr(getExpr.get());
422
423 return complete(syntacticBase);
424}
425
426/// The basic skeleton for building a simple or compound
427/// assignment operation.
429PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
430 BinaryOperatorKind opcode,
431 Expr *LHS, Expr *RHS) {
432 assert(BinaryOperator::isAssignmentOp(opcode));
433
434 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
435 OpaqueValueExpr *capturedRHS = capture(RHS);
436
437 // In some very specific cases, semantic analysis of the RHS as an
438 // expression may require it to be rewritten. In these cases, we
439 // cannot safely keep the OVE around. Fortunately, we don't really
440 // need to: we don't use this particular OVE in multiple places, and
441 // no clients rely that closely on matching up expressions in the
442 // semantic expression with expressions from the syntactic form.
443 Expr *semanticRHS = capturedRHS;
444 if (RHS->hasPlaceholderType() || isa<InitListExpr>(RHS)) {
445 semanticRHS = RHS;
446 Semantics.pop_back();
447 }
448
449 Expr *syntactic;
450
451 ExprResult result;
452 if (opcode == BO_Assign) {
453 result = semanticRHS;
454 syntactic = BinaryOperator::Create(S.Context, syntacticLHS, capturedRHS,
455 opcode, capturedRHS->getType(),
456 capturedRHS->getValueKind(), OK_Ordinary,
457 opcLoc, S.CurFPFeatureOverrides());
458
459 } else {
460 ExprResult opLHS = buildGet();
461 if (opLHS.isInvalid()) return ExprError();
462
463 // Build an ordinary, non-compound operation.
464 BinaryOperatorKind nonCompound =
466 result = S.BuildBinOp(Sc, opcLoc, nonCompound, opLHS.get(), semanticRHS);
467 if (result.isInvalid()) return ExprError();
468
470 S.Context, syntacticLHS, capturedRHS, opcode, result.get()->getType(),
471 result.get()->getValueKind(), OK_Ordinary, opcLoc,
472 S.CurFPFeatureOverrides(), opLHS.get()->getType(),
473 result.get()->getType());
474 }
475
476 // The result of the assignment, if not void, is the value set into
477 // the l-value.
478 result = buildSet(result.get(), opcLoc, captureSetValueAsResult());
479 if (result.isInvalid()) return ExprError();
480 addSemanticExpr(result.get());
481 if (!captureSetValueAsResult() && !result.get()->getType()->isVoidType() &&
482 (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
483 setResultToLastSemantic();
484
485 return complete(syntactic);
486}
487
488/// The basic skeleton for building an increment or decrement
489/// operation.
491PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
492 UnaryOperatorKind opcode,
493 Expr *op) {
495
496 Expr *syntacticOp = rebuildAndCaptureObject(op);
497
498 // Load the value.
499 ExprResult result = buildGet();
500 if (result.isInvalid()) return ExprError();
501
502 QualType resultType = result.get()->getType();
503
504 // That's the postfix result.
505 if (UnaryOperator::isPostfix(opcode) &&
506 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
507 result = capture(result.get());
508 setResultToLastSemantic();
509 }
510
511 // Add or subtract a literal 1.
512 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
514 GenericLoc);
515
516 if (UnaryOperator::isIncrementOp(opcode)) {
517 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one);
518 } else {
519 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one);
520 }
521 if (result.isInvalid()) return ExprError();
522
523 // Store that back into the result. The value stored is the result
524 // of a prefix operation.
525 result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode) &&
526 captureSetValueAsResult());
527 if (result.isInvalid()) return ExprError();
528 addSemanticExpr(result.get());
529 if (UnaryOperator::isPrefix(opcode) && !captureSetValueAsResult() &&
530 !result.get()->getType()->isVoidType() &&
531 (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
532 setResultToLastSemantic();
533
534 UnaryOperator *syntactic =
535 UnaryOperator::Create(S.Context, syntacticOp, opcode, resultType,
536 VK_LValue, OK_Ordinary, opcLoc,
537 !resultType->isDependentType()
538 ? S.Context.getTypeSize(resultType) >=
540 : false,
542 return complete(syntactic);
543}
544
545
546//===----------------------------------------------------------------------===//
547// Objective-C @property and implicit property references
548//===----------------------------------------------------------------------===//
549
550/// Look up a method in the receiver type of an Objective-C property
551/// reference.
553 const ObjCPropertyRefExpr *PRE) {
554 if (PRE->isObjectReceiver()) {
555 const ObjCObjectPointerType *PT =
557
558 // Special case for 'self' in class method implementations.
559 if (PT->isObjCClassType() &&
560 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
561 // This cast is safe because isSelfExpr is only true within
562 // methods.
563 ObjCMethodDecl *method =
564 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
565 return S.LookupMethodInObjectType(sel,
567 /*instance*/ false);
568 }
569
570 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
571 }
572
573 if (PRE->isSuperReceiver()) {
574 if (const ObjCObjectPointerType *PT =
576 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
577
578 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
579 }
580
581 assert(PRE->isClassReceiver() && "Invalid expression");
583 return S.LookupMethodInObjectType(sel, IT, false);
584}
585
586bool ObjCPropertyOpBuilder::isWeakProperty() const {
587 QualType T;
588 if (RefExpr->isExplicitProperty()) {
589 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
591 return true;
592
593 T = Prop->getType();
594 } else if (Getter) {
595 T = Getter->getReturnType();
596 } else {
597 return false;
598 }
599
600 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
601}
602
603bool ObjCPropertyOpBuilder::findGetter() {
604 if (Getter) return true;
605
606 // For implicit properties, just trust the lookup we already did.
607 if (RefExpr->isImplicitProperty()) {
608 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
609 GetterSelector = Getter->getSelector();
610 return true;
611 }
612 else {
613 // Must build the getter selector the hard way.
614 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
615 assert(setter && "both setter and getter are null - cannot happen");
616 const IdentifierInfo *setterName =
618 const IdentifierInfo *getterName =
619 &S.Context.Idents.get(setterName->getName().substr(3));
620 GetterSelector =
621 S.PP.getSelectorTable().getNullarySelector(getterName);
622 return false;
623 }
624 }
625
626 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
627 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
628 return (Getter != nullptr);
629}
630
631/// Try to find the most accurate setter declaration for the property
632/// reference.
633///
634/// \return true if a setter was found, in which case Setter
635bool ObjCPropertyOpBuilder::findSetter(bool warn) {
636 // For implicit properties, just trust the lookup we already did.
637 if (RefExpr->isImplicitProperty()) {
638 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
639 Setter = setter;
640 SetterSelector = setter->getSelector();
641 return true;
642 } else {
643 const IdentifierInfo *getterName = RefExpr->getImplicitPropertyGetter()
644 ->getSelector()
645 .getIdentifierInfoForSlot(0);
646 SetterSelector =
649 getterName);
650 return false;
651 }
652 }
653
654 // For explicit properties, this is more involved.
655 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
656 SetterSelector = prop->getSetterName();
657
658 // Do a normal method lookup first.
659 if (ObjCMethodDecl *setter =
660 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
661 if (setter->isPropertyAccessor() && warn)
662 if (const ObjCInterfaceDecl *IFace =
663 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
664 StringRef thisPropertyName = prop->getName();
665 // Try flipping the case of the first character.
666 char front = thisPropertyName.front();
667 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
668 SmallString<100> PropertyName = thisPropertyName;
669 PropertyName[0] = front;
670 const IdentifierInfo *AltMember =
671 &S.PP.getIdentifierTable().get(PropertyName);
672 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(
673 AltMember, prop->getQueryKind()))
674 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
675 S.Diag(RefExpr->getExprLoc(), diag::err_property_setter_ambiguous_use)
676 << prop << prop1 << setter->getSelector();
677 S.Diag(prop->getLocation(), diag::note_property_declare);
678 S.Diag(prop1->getLocation(), diag::note_property_declare);
679 }
680 }
681 Setter = setter;
682 return true;
683 }
684
685 // That can fail in the somewhat crazy situation that we're
686 // type-checking a message send within the @interface declaration
687 // that declared the @property. But it's not clear that that's
688 // valuable to support.
689
690 return false;
691}
692
693void ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() {
695 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
696 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) {
697 if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) {
698 S.Diag(RefExpr->getLocation(),
699 diag::err_property_function_in_objc_container);
700 S.Diag(prop->getLocation(), diag::note_property_declare);
701 }
702 }
703}
704
705/// Capture the base object of an Objective-C property expression.
706Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
707 assert(InstanceReceiver == nullptr);
708
709 // If we have a base, capture it in an OVE and rebuild the syntactic
710 // form to use the OVE as its base.
711 if (RefExpr->isObjectReceiver()) {
712 InstanceReceiver = capture(RefExpr->getBase());
713 syntacticBase = Rebuilder(S, [=](Expr *, unsigned) -> Expr * {
714 return InstanceReceiver;
715 }).rebuild(syntacticBase);
716 }
717
719 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
720 SyntacticRefExpr = refE;
721
722 return syntacticBase;
723}
724
725/// Load from an Objective-C property reference.
726ExprResult ObjCPropertyOpBuilder::buildGet() {
727 findGetter();
728 if (!Getter) {
729 DiagnoseUnsupportedPropertyUse();
730 return ExprError();
731 }
732
733 if (SyntacticRefExpr)
734 SyntacticRefExpr->setIsMessagingGetter();
735
736 QualType receiverType = RefExpr->getReceiverType(S.Context);
737 if (!Getter->isImplicit())
738 S.DiagnoseUseOfDecl(Getter, GenericLoc, nullptr, true);
739 // Build a message-send.
740 ExprResult msg;
741 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
742 RefExpr->isObjectReceiver()) {
743 assert(InstanceReceiver || RefExpr->isSuperReceiver());
744 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
745 GenericLoc, Getter->getSelector(),
746 Getter, std::nullopt);
747 } else {
748 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
749 GenericLoc, Getter->getSelector(), Getter,
750 std::nullopt);
751 }
752 return msg;
753}
754
755/// Store to an Objective-C property reference.
756///
757/// \param captureSetValueAsResult If true, capture the actual
758/// value being set as the value of the property operation.
759ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
760 bool captureSetValueAsResult) {
761 if (!findSetter(false)) {
762 DiagnoseUnsupportedPropertyUse();
763 return ExprError();
764 }
765
766 if (SyntacticRefExpr)
767 SyntacticRefExpr->setIsMessagingSetter();
768
769 QualType receiverType = RefExpr->getReceiverType(S.Context);
770
771 // Use assignment constraints when possible; they give us better
772 // diagnostics. "When possible" basically means anything except a
773 // C++ class type.
774 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
775 QualType paramType = (*Setter->param_begin())->getType()
777 receiverType,
778 Setter->getDeclContext(),
779 ObjCSubstitutionContext::Parameter);
780 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
781 ExprResult opResult = op;
782 Sema::AssignConvertType assignResult
783 = S.CheckSingleAssignmentConstraints(paramType, opResult);
784 if (opResult.isInvalid() ||
785 S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
786 op->getType(), opResult.get(),
788 return ExprError();
789
790 op = opResult.get();
791 assert(op && "successful assignment left argument invalid?");
792 }
793 }
794
795 // Arguments.
796 Expr *args[] = { op };
797
798 // Build a message-send.
799 ExprResult msg;
800 if (!Setter->isImplicit())
801 S.DiagnoseUseOfDecl(Setter, GenericLoc, nullptr, true);
802 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
803 RefExpr->isObjectReceiver()) {
804 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
805 GenericLoc, SetterSelector, Setter,
806 MultiExprArg(args, 1));
807 } else {
808 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
809 GenericLoc,
810 SetterSelector, Setter,
811 MultiExprArg(args, 1));
812 }
813
814 if (!msg.isInvalid() && captureSetValueAsResult) {
815 ObjCMessageExpr *msgExpr =
816 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
817 Expr *arg = msgExpr->getArg(0);
818 if (CanCaptureValue(arg))
819 msgExpr->setArg(0, captureValueAsResult(arg));
820 }
821
822 return msg;
823}
824
825/// @property-specific behavior for doing lvalue-to-rvalue conversion.
826ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
827 // Explicit properties always have getters, but implicit ones don't.
828 // Check that before proceeding.
829 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
830 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
831 << RefExpr->getSourceRange();
832 return ExprError();
833 }
834
835 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
836 if (result.isInvalid()) return ExprError();
837
838 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
839 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
840 Getter, RefExpr->getLocation());
841
842 // As a special case, if the method returns 'id', try to get
843 // a better type from the property.
844 if (RefExpr->isExplicitProperty() && result.get()->isPRValue()) {
845 QualType receiverType = RefExpr->getReceiverType(S.Context);
846 QualType propType = RefExpr->getExplicitProperty()
847 ->getUsageType(receiverType);
848 if (result.get()->getType()->isObjCIdType()) {
849 if (const ObjCObjectPointerType *ptr
850 = propType->getAs<ObjCObjectPointerType>()) {
851 if (!ptr->isObjCIdType())
852 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
853 }
854 }
855 if (propType.getObjCLifetime() == Qualifiers::OCL_Weak &&
856 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
857 RefExpr->getLocation()))
858 S.getCurFunction()->markSafeWeakUse(RefExpr);
859 }
860
861 return result;
862}
863
864/// Try to build this as a call to a getter that returns a reference.
865///
866/// \return true if it was possible, whether or not it actually
867/// succeeded
868bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
869 ExprResult &result) {
870 if (!S.getLangOpts().CPlusPlus) return false;
871
872 findGetter();
873 if (!Getter) {
874 // The property has no setter and no getter! This can happen if the type is
875 // invalid. Error have already been reported.
876 result = ExprError();
877 return true;
878 }
879
880 // Only do this if the getter returns an l-value reference type.
881 QualType resultType = Getter->getReturnType();
882 if (!resultType->isLValueReferenceType()) return false;
883
884 result = buildRValueOperation(op);
885 return true;
886}
887
888/// @property-specific behavior for doing assignments.
890ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
891 SourceLocation opcLoc,
892 BinaryOperatorKind opcode,
893 Expr *LHS, Expr *RHS) {
894 assert(BinaryOperator::isAssignmentOp(opcode));
895
896 // If there's no setter, we have no choice but to try to assign to
897 // the result of the getter.
898 if (!findSetter()) {
899 ExprResult result;
900 if (tryBuildGetOfReference(LHS, result)) {
901 if (result.isInvalid()) return ExprError();
902 return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS);
903 }
904
905 // Otherwise, it's an error.
906 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
907 << unsigned(RefExpr->isImplicitProperty())
908 << SetterSelector
909 << LHS->getSourceRange() << RHS->getSourceRange();
910 return ExprError();
911 }
912
913 // If there is a setter, we definitely want to use it.
914
915 // Verify that we can do a compound assignment.
916 if (opcode != BO_Assign && !findGetter()) {
917 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
918 << LHS->getSourceRange() << RHS->getSourceRange();
919 return ExprError();
920 }
921
922 ExprResult result =
923 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
924 if (result.isInvalid()) return ExprError();
925
926 // Various warnings about property assignments in ARC.
927 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
928 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
929 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
930 }
931
932 return result;
933}
934
935/// @property-specific behavior for doing increments and decrements.
937ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
938 UnaryOperatorKind opcode,
939 Expr *op) {
940 // If there's no setter, we have no choice but to try to assign to
941 // the result of the getter.
942 if (!findSetter()) {
943 ExprResult result;
944 if (tryBuildGetOfReference(op, result)) {
945 if (result.isInvalid()) return ExprError();
946 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get());
947 }
948
949 // Otherwise, it's an error.
950 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
951 << unsigned(RefExpr->isImplicitProperty())
953 << SetterSelector
954 << op->getSourceRange();
955 return ExprError();
956 }
957
958 // If there is a setter, we definitely want to use it.
959
960 // We also need a getter.
961 if (!findGetter()) {
962 assert(RefExpr->isImplicitProperty());
963 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
965 << GetterSelector
966 << op->getSourceRange();
967 return ExprError();
968 }
969
970 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
971}
972
973ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
974 if (isWeakProperty() && !S.isUnevaluatedContext() &&
975 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
976 SyntacticForm->getBeginLoc()))
977 S.getCurFunction()->recordUseOfWeak(SyntacticRefExpr,
978 SyntacticRefExpr->isMessagingGetter());
979
980 return PseudoOpBuilder::complete(SyntacticForm);
981}
982
983// ObjCSubscript build stuff.
984//
985
986/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
987/// conversion.
988/// FIXME. Remove this routine if it is proven that no additional
989/// specifity is needed.
990ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
991 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
992 if (result.isInvalid()) return ExprError();
993 return result;
994}
995
996/// objective-c subscripting-specific behavior for doing assignments.
998ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
999 SourceLocation opcLoc,
1000 BinaryOperatorKind opcode,
1001 Expr *LHS, Expr *RHS) {
1002 assert(BinaryOperator::isAssignmentOp(opcode));
1003 // There must be a method to do the Index'ed assignment.
1004 if (!findAtIndexSetter())
1005 return ExprError();
1006
1007 // Verify that we can do a compound assignment.
1008 if (opcode != BO_Assign && !findAtIndexGetter())
1009 return ExprError();
1010
1011 ExprResult result =
1012 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
1013 if (result.isInvalid()) return ExprError();
1014
1015 // Various warnings about objc Index'ed assignments in ARC.
1016 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
1017 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
1018 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
1019 }
1020
1021 return result;
1022}
1023
1024/// Capture the base object of an Objective-C Index'ed expression.
1025Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1026 assert(InstanceBase == nullptr);
1027
1028 // Capture base expression in an OVE and rebuild the syntactic
1029 // form to use the OVE as its base expression.
1030 InstanceBase = capture(RefExpr->getBaseExpr());
1031 InstanceKey = capture(RefExpr->getKeyExpr());
1032
1033 syntacticBase =
1034 Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
1035 switch (Idx) {
1036 case 0:
1037 return InstanceBase;
1038 case 1:
1039 return InstanceKey;
1040 default:
1041 llvm_unreachable("Unexpected index for ObjCSubscriptExpr");
1042 }
1043 }).rebuild(syntacticBase);
1044
1045 return syntacticBase;
1046}
1047
1048/// CheckSubscriptingKind - This routine decide what type
1049/// of indexing represented by "FromE" is being done.
1052 // If the expression already has integral or enumeration type, we're golden.
1053 QualType T = FromE->getType();
1055 return OS_Array;
1056
1057 // If we don't have a class type in C++, there's no way we can get an
1058 // expression of integral or enumeration type.
1059 const RecordType *RecordTy = T->getAs<RecordType>();
1060 if (!RecordTy &&
1062 // All other scalar cases are assumed to be dictionary indexing which
1063 // caller handles, with diagnostics if needed.
1064 return OS_Dictionary;
1065 if (!getLangOpts().CPlusPlus ||
1066 !RecordTy || RecordTy->isIncompleteType()) {
1067 // No indexing can be done. Issue diagnostics and quit.
1068 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1069 if (isa<StringLiteral>(IndexExpr))
1070 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1071 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1072 else
1073 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1074 << T;
1075 return OS_Error;
1076 }
1077
1078 // We must have a complete class type.
1079 if (RequireCompleteType(FromE->getExprLoc(), T,
1080 diag::err_objc_index_incomplete_class_type, FromE))
1081 return OS_Error;
1082
1083 // Look for a conversion to an integral, enumeration type, or
1084 // objective-C pointer type.
1085 int NoIntegrals=0, NoObjCIdPointers=0;
1087
1088 for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
1089 ->getVisibleConversionFunctions()) {
1090 if (CXXConversionDecl *Conversion =
1091 dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
1092 QualType CT = Conversion->getConversionType().getNonReferenceType();
1093 if (CT->isIntegralOrEnumerationType()) {
1094 ++NoIntegrals;
1095 ConversionDecls.push_back(Conversion);
1096 }
1097 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1098 ++NoObjCIdPointers;
1099 ConversionDecls.push_back(Conversion);
1100 }
1101 }
1102 }
1103 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1104 return OS_Array;
1105 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1106 return OS_Dictionary;
1107 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1108 // No conversion function was found. Issue diagnostic and return.
1109 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1110 << FromE->getType();
1111 return OS_Error;
1112 }
1113 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1114 << FromE->getType();
1115 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1116 Diag(ConversionDecls[i]->getLocation(),
1117 diag::note_conv_function_declared_at);
1118
1119 return OS_Error;
1120}
1121
1122/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1123/// objects used as dictionary subscript key objects.
1124static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1125 Expr *Key) {
1126 if (ContainerT.isNull())
1127 return;
1128 // dictionary subscripting.
1129 // - (id)objectForKeyedSubscript:(id)key;
1130 const IdentifierInfo *KeyIdents[] = {
1131 &S.Context.Idents.get("objectForKeyedSubscript")};
1132 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1133 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1134 true /*instance*/);
1135 if (!Getter)
1136 return;
1137 QualType T = Getter->parameters()[0]->getType();
1138 S.CheckObjCConversion(Key->getSourceRange(), T, Key,
1140}
1141
1142bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1143 if (AtIndexGetter)
1144 return true;
1145
1146 Expr *BaseExpr = RefExpr->getBaseExpr();
1147 QualType BaseT = BaseExpr->getType();
1148
1149 QualType ResultType;
1150 if (const ObjCObjectPointerType *PTy =
1151 BaseT->getAs<ObjCObjectPointerType>()) {
1152 ResultType = PTy->getPointeeType();
1153 }
1155 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1156 if (Res == Sema::OS_Error) {
1157 if (S.getLangOpts().ObjCAutoRefCount)
1158 CheckKeyForObjCARCConversion(S, ResultType,
1159 RefExpr->getKeyExpr());
1160 return false;
1161 }
1162 bool arrayRef = (Res == Sema::OS_Array);
1163
1164 if (ResultType.isNull()) {
1165 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1166 << BaseExpr->getType() << arrayRef;
1167 return false;
1168 }
1169 if (!arrayRef) {
1170 // dictionary subscripting.
1171 // - (id)objectForKeyedSubscript:(id)key;
1172 const IdentifierInfo *KeyIdents[] = {
1173 &S.Context.Idents.get("objectForKeyedSubscript")};
1174 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1175 }
1176 else {
1177 // - (id)objectAtIndexedSubscript:(size_t)index;
1178 const IdentifierInfo *KeyIdents[] = {
1179 &S.Context.Idents.get("objectAtIndexedSubscript")};
1180
1181 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1182 }
1183
1184 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1185 true /*instance*/);
1186
1187 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
1188 AtIndexGetter = ObjCMethodDecl::Create(
1189 S.Context, SourceLocation(), SourceLocation(), AtIndexGetterSelector,
1190 S.Context.getObjCIdType() /*ReturnType*/, nullptr /*TypeSourceInfo */,
1191 S.Context.getTranslationUnitDecl(), true /*Instance*/,
1192 false /*isVariadic*/,
1193 /*isPropertyAccessor=*/false,
1194 /*isSynthesizedAccessorStub=*/false,
1195 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1197 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1199 arrayRef ? &S.Context.Idents.get("index")
1200 : &S.Context.Idents.get("key"),
1201 arrayRef ? S.Context.UnsignedLongTy
1202 : S.Context.getObjCIdType(),
1203 /*TInfo=*/nullptr,
1204 SC_None,
1205 nullptr);
1206 AtIndexGetter->setMethodParams(S.Context, Argument, std::nullopt);
1207 }
1208
1209 if (!AtIndexGetter) {
1210 if (!BaseT->isObjCIdType()) {
1211 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1212 << BaseExpr->getType() << 0 << arrayRef;
1213 return false;
1214 }
1215 AtIndexGetter =
1216 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1217 RefExpr->getSourceRange(),
1218 true);
1219 }
1220
1221 if (AtIndexGetter) {
1222 QualType T = AtIndexGetter->parameters()[0]->getType();
1223 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1224 (!arrayRef && !T->isObjCObjectPointerType())) {
1225 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1226 arrayRef ? diag::err_objc_subscript_index_type
1227 : diag::err_objc_subscript_key_type) << T;
1228 S.Diag(AtIndexGetter->parameters()[0]->getLocation(),
1229 diag::note_parameter_type) << T;
1230 return false;
1231 }
1232 QualType R = AtIndexGetter->getReturnType();
1233 if (!R->isObjCObjectPointerType()) {
1234 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1235 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1236 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1237 AtIndexGetter->getDeclName();
1238 }
1239 }
1240 return true;
1241}
1242
1243bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1244 if (AtIndexSetter)
1245 return true;
1246
1247 Expr *BaseExpr = RefExpr->getBaseExpr();
1248 QualType BaseT = BaseExpr->getType();
1249
1250 QualType ResultType;
1251 if (const ObjCObjectPointerType *PTy =
1252 BaseT->getAs<ObjCObjectPointerType>()) {
1253 ResultType = PTy->getPointeeType();
1254 }
1255
1257 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1258 if (Res == Sema::OS_Error) {
1259 if (S.getLangOpts().ObjCAutoRefCount)
1260 CheckKeyForObjCARCConversion(S, ResultType,
1261 RefExpr->getKeyExpr());
1262 return false;
1263 }
1264 bool arrayRef = (Res == Sema::OS_Array);
1265
1266 if (ResultType.isNull()) {
1267 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1268 << BaseExpr->getType() << arrayRef;
1269 return false;
1270 }
1271
1272 if (!arrayRef) {
1273 // dictionary subscripting.
1274 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1275 const IdentifierInfo *KeyIdents[] = {
1276 &S.Context.Idents.get("setObject"),
1277 &S.Context.Idents.get("forKeyedSubscript")};
1278 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1279 }
1280 else {
1281 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1282 const IdentifierInfo *KeyIdents[] = {
1283 &S.Context.Idents.get("setObject"),
1284 &S.Context.Idents.get("atIndexedSubscript")};
1285 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1286 }
1287 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1288 true /*instance*/);
1289
1290 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
1291 TypeSourceInfo *ReturnTInfo = nullptr;
1292 QualType ReturnType = S.Context.VoidTy;
1293 AtIndexSetter = ObjCMethodDecl::Create(
1294 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1295 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1296 true /*Instance*/, false /*isVariadic*/,
1297 /*isPropertyAccessor=*/false,
1298 /*isSynthesizedAccessorStub=*/false,
1299 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1302 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1304 &S.Context.Idents.get("object"),
1306 /*TInfo=*/nullptr,
1307 SC_None,
1308 nullptr);
1309 Params.push_back(object);
1310 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1312 arrayRef ? &S.Context.Idents.get("index")
1313 : &S.Context.Idents.get("key"),
1314 arrayRef ? S.Context.UnsignedLongTy
1315 : S.Context.getObjCIdType(),
1316 /*TInfo=*/nullptr,
1317 SC_None,
1318 nullptr);
1319 Params.push_back(key);
1320 AtIndexSetter->setMethodParams(S.Context, Params, std::nullopt);
1321 }
1322
1323 if (!AtIndexSetter) {
1324 if (!BaseT->isObjCIdType()) {
1325 S.Diag(BaseExpr->getExprLoc(),
1326 diag::err_objc_subscript_method_not_found)
1327 << BaseExpr->getType() << 1 << arrayRef;
1328 return false;
1329 }
1330 AtIndexSetter =
1331 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1332 RefExpr->getSourceRange(),
1333 true);
1334 }
1335
1336 bool err = false;
1337 if (AtIndexSetter && arrayRef) {
1338 QualType T = AtIndexSetter->parameters()[1]->getType();
1340 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1341 diag::err_objc_subscript_index_type) << T;
1342 S.Diag(AtIndexSetter->parameters()[1]->getLocation(),
1343 diag::note_parameter_type) << T;
1344 err = true;
1345 }
1346 T = AtIndexSetter->parameters()[0]->getType();
1347 if (!T->isObjCObjectPointerType()) {
1348 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1349 diag::err_objc_subscript_object_type) << T << arrayRef;
1350 S.Diag(AtIndexSetter->parameters()[0]->getLocation(),
1351 diag::note_parameter_type) << T;
1352 err = true;
1353 }
1354 }
1355 else if (AtIndexSetter && !arrayRef)
1356 for (unsigned i=0; i <2; i++) {
1357 QualType T = AtIndexSetter->parameters()[i]->getType();
1358 if (!T->isObjCObjectPointerType()) {
1359 if (i == 1)
1360 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1361 diag::err_objc_subscript_key_type) << T;
1362 else
1363 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1364 diag::err_objc_subscript_dic_object_type) << T;
1365 S.Diag(AtIndexSetter->parameters()[i]->getLocation(),
1366 diag::note_parameter_type) << T;
1367 err = true;
1368 }
1369 }
1370
1371 return !err;
1372}
1373
1374// Get the object at "Index" position in the container.
1375// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1376ExprResult ObjCSubscriptOpBuilder::buildGet() {
1377 if (!findAtIndexGetter())
1378 return ExprError();
1379
1380 QualType receiverType = InstanceBase->getType();
1381
1382 // Build a message-send.
1383 ExprResult msg;
1384 Expr *Index = InstanceKey;
1385
1386 // Arguments.
1387 Expr *args[] = { Index };
1388 assert(InstanceBase);
1389 if (AtIndexGetter)
1390 S.DiagnoseUseOfDecl(AtIndexGetter, GenericLoc);
1391 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1392 GenericLoc,
1393 AtIndexGetterSelector, AtIndexGetter,
1394 MultiExprArg(args, 1));
1395 return msg;
1396}
1397
1398/// Store into the container the "op" object at "Index"'ed location
1399/// by building this messaging expression:
1400/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1401/// \param captureSetValueAsResult If true, capture the actual
1402/// value being set as the value of the property operation.
1403ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1404 bool captureSetValueAsResult) {
1405 if (!findAtIndexSetter())
1406 return ExprError();
1407 if (AtIndexSetter)
1408 S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc);
1409 QualType receiverType = InstanceBase->getType();
1410 Expr *Index = InstanceKey;
1411
1412 // Arguments.
1413 Expr *args[] = { op, Index };
1414
1415 // Build a message-send.
1416 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1417 GenericLoc,
1418 AtIndexSetterSelector,
1419 AtIndexSetter,
1420 MultiExprArg(args, 2));
1421
1422 if (!msg.isInvalid() && captureSetValueAsResult) {
1423 ObjCMessageExpr *msgExpr =
1424 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1425 Expr *arg = msgExpr->getArg(0);
1426 if (CanCaptureValue(arg))
1427 msgExpr->setArg(0, captureValueAsResult(arg));
1428 }
1429
1430 return msg;
1431}
1432
1433//===----------------------------------------------------------------------===//
1434// MSVC __declspec(property) references
1435//===----------------------------------------------------------------------===//
1436
1438MSPropertyOpBuilder::getBaseMSProperty(MSPropertySubscriptExpr *E) {
1439 CallArgs.insert(CallArgs.begin(), E->getIdx());
1440 Expr *Base = E->getBase()->IgnoreParens();
1441 while (auto *MSPropSubscript = dyn_cast<MSPropertySubscriptExpr>(Base)) {
1442 CallArgs.insert(CallArgs.begin(), MSPropSubscript->getIdx());
1443 Base = MSPropSubscript->getBase()->IgnoreParens();
1444 }
1445 return cast<MSPropertyRefExpr>(Base);
1446}
1447
1448Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1449 InstanceBase = capture(RefExpr->getBaseExpr());
1450 for (Expr *&Arg : CallArgs)
1451 Arg = capture(Arg);
1452 syntacticBase = Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
1453 switch (Idx) {
1454 case 0:
1455 return InstanceBase;
1456 default:
1457 assert(Idx <= CallArgs.size());
1458 return CallArgs[Idx - 1];
1459 }
1460 }).rebuild(syntacticBase);
1461
1462 return syntacticBase;
1463}
1464
1465ExprResult MSPropertyOpBuilder::buildGet() {
1466 if (!RefExpr->getPropertyDecl()->hasGetter()) {
1467 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
1468 << 0 /* getter */ << RefExpr->getPropertyDecl();
1469 return ExprError();
1470 }
1471
1472 UnqualifiedId GetterName;
1473 const IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1474 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1475 CXXScopeSpec SS;
1476 SS.Adopt(RefExpr->getQualifierLoc());
1477 ExprResult GetterExpr =
1478 S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
1479 RefExpr->isArrow() ? tok::arrow : tok::period, SS,
1480 SourceLocation(), GetterName, nullptr);
1481 if (GetterExpr.isInvalid()) {
1482 S.Diag(RefExpr->getMemberLoc(),
1483 diag::err_cannot_find_suitable_accessor) << 0 /* getter */
1484 << RefExpr->getPropertyDecl();
1485 return ExprError();
1486 }
1487
1488 return S.BuildCallExpr(S.getCurScope(), GetterExpr.get(),
1489 RefExpr->getSourceRange().getBegin(), CallArgs,
1490 RefExpr->getSourceRange().getEnd());
1491}
1492
1493ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1494 bool captureSetValueAsResult) {
1495 if (!RefExpr->getPropertyDecl()->hasSetter()) {
1496 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
1497 << 1 /* setter */ << RefExpr->getPropertyDecl();
1498 return ExprError();
1499 }
1500
1501 UnqualifiedId SetterName;
1502 const IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1503 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1504 CXXScopeSpec SS;
1505 SS.Adopt(RefExpr->getQualifierLoc());
1506 ExprResult SetterExpr =
1507 S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
1508 RefExpr->isArrow() ? tok::arrow : tok::period, SS,
1509 SourceLocation(), SetterName, nullptr);
1510 if (SetterExpr.isInvalid()) {
1511 S.Diag(RefExpr->getMemberLoc(),
1512 diag::err_cannot_find_suitable_accessor) << 1 /* setter */
1513 << RefExpr->getPropertyDecl();
1514 return ExprError();
1515 }
1516
1517 SmallVector<Expr*, 4> ArgExprs;
1518 ArgExprs.append(CallArgs.begin(), CallArgs.end());
1519 ArgExprs.push_back(op);
1520 return S.BuildCallExpr(S.getCurScope(), SetterExpr.get(),
1521 RefExpr->getSourceRange().getBegin(), ArgExprs,
1522 op->getSourceRange().getEnd());
1523}
1524
1525//===----------------------------------------------------------------------===//
1526// General Sema routines.
1527//===----------------------------------------------------------------------===//
1528
1530 Expr *opaqueRef = E->IgnoreParens();
1531 if (ObjCPropertyRefExpr *refExpr
1532 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1533 ObjCPropertyOpBuilder builder(*this, refExpr, true);
1534 return builder.buildRValueOperation(E);
1535 }
1536 else if (ObjCSubscriptRefExpr *refExpr
1537 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1538 ObjCSubscriptOpBuilder builder(*this, refExpr, true);
1539 return builder.buildRValueOperation(E);
1540 } else if (MSPropertyRefExpr *refExpr
1541 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1542 MSPropertyOpBuilder builder(*this, refExpr, true);
1543 return builder.buildRValueOperation(E);
1544 } else if (MSPropertySubscriptExpr *RefExpr =
1545 dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1546 MSPropertyOpBuilder Builder(*this, RefExpr, true);
1547 return Builder.buildRValueOperation(E);
1548 } else {
1549 llvm_unreachable("unknown pseudo-object kind!");
1550 }
1551}
1552
1553/// Check an increment or decrement of a pseudo-object expression.
1555 UnaryOperatorKind opcode, Expr *op) {
1556 // Do nothing if the operand is dependent.
1557 if (op->isTypeDependent())
1559 VK_PRValue, OK_Ordinary, opcLoc, false,
1561
1563 Expr *opaqueRef = op->IgnoreParens();
1564 if (ObjCPropertyRefExpr *refExpr
1565 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1566 ObjCPropertyOpBuilder builder(*this, refExpr, false);
1567 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1568 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1569 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1570 return ExprError();
1571 } else if (MSPropertyRefExpr *refExpr
1572 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1573 MSPropertyOpBuilder builder(*this, refExpr, false);
1574 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1575 } else if (MSPropertySubscriptExpr *RefExpr
1576 = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1577 MSPropertyOpBuilder Builder(*this, RefExpr, false);
1578 return Builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1579 } else {
1580 llvm_unreachable("unknown pseudo-object kind!");
1581 }
1582}
1583
1585 BinaryOperatorKind opcode,
1586 Expr *LHS, Expr *RHS) {
1587 // Do nothing if either argument is dependent.
1588 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1589 return BinaryOperator::Create(Context, LHS, RHS, opcode,
1591 opcLoc, CurFPFeatureOverrides());
1592
1593 // Filter out non-overload placeholder types in the RHS.
1594 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1595 ExprResult result = CheckPlaceholderExpr(RHS);
1596 if (result.isInvalid()) return ExprError();
1597 RHS = result.get();
1598 }
1599
1600 bool IsSimpleAssign = opcode == BO_Assign;
1601 Expr *opaqueRef = LHS->IgnoreParens();
1602 if (ObjCPropertyRefExpr *refExpr
1603 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1604 ObjCPropertyOpBuilder builder(*this, refExpr, IsSimpleAssign);
1605 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1606 } else if (ObjCSubscriptRefExpr *refExpr
1607 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1608 ObjCSubscriptOpBuilder builder(*this, refExpr, IsSimpleAssign);
1609 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1610 } else if (MSPropertyRefExpr *refExpr
1611 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1612 MSPropertyOpBuilder builder(*this, refExpr, IsSimpleAssign);
1613 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1614 } else if (MSPropertySubscriptExpr *RefExpr
1615 = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1616 MSPropertyOpBuilder Builder(*this, RefExpr, IsSimpleAssign);
1617 return Builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1618 } else {
1619 llvm_unreachable("unknown pseudo-object kind!");
1620 }
1621}
1622
1623/// Given a pseudo-object reference, rebuild it without the opaque
1624/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1625/// This should never operate in-place.
1627 return Rebuilder(S,
1628 [=](Expr *E, unsigned) -> Expr * {
1629 return cast<OpaqueValueExpr>(E)->getSourceExpr();
1630 })
1631 .rebuild(E);
1632}
1633
1634/// Given a pseudo-object expression, recreate what it looks like
1635/// syntactically without the attendant OpaqueValueExprs.
1636///
1637/// This is a hack which should be removed when TreeTransform is
1638/// capable of rebuilding a tree without stripping implicit
1639/// operations.
1641 Expr *syntax = E->getSyntacticForm();
1642 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1643 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1644 return UnaryOperator::Create(Context, op, uop->getOpcode(), uop->getType(),
1645 uop->getValueKind(), uop->getObjectKind(),
1646 uop->getOperatorLoc(), uop->canOverflow(),
1648 } else if (CompoundAssignOperator *cop
1649 = dyn_cast<CompoundAssignOperator>(syntax)) {
1650 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1651 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1653 Context, lhs, rhs, cop->getOpcode(), cop->getType(),
1654 cop->getValueKind(), cop->getObjectKind(), cop->getOperatorLoc(),
1655 CurFPFeatureOverrides(), cop->getComputationLHSType(),
1656 cop->getComputationResultType());
1657
1658 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1659 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1660 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1661 return BinaryOperator::Create(Context, lhs, rhs, bop->getOpcode(),
1662 bop->getType(), bop->getValueKind(),
1663 bop->getObjectKind(), bop->getOperatorLoc(),
1665
1666 } else if (isa<CallExpr>(syntax)) {
1667 return syntax;
1668 } else {
1669 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1670 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1671 }
1672}
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::Preprocessor interface.
static ObjCMethodDecl * LookupMethodInReceiverType(Sema &S, Selector sel, const ObjCPropertyRefExpr *PRE)
Look up a method in the receiver type of an Objective-C property reference.
static Expr * stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E)
Given a pseudo-object reference, rebuild it without the opaque values.
static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, Expr *Key)
CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF objects used as dictionary ...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
CanQualType DependentTy
Definition: ASTContext.h:1119
IdentifierTable & Idents
Definition: ASTContext.h:644
SelectorTable & Selectors
Definition: ASTContext.h:645
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2062
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2329
CanQualType VoidTy
Definition: ASTContext.h:1091
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:3986
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4781
bool isAssignmentOp() const
Definition: Expr.h:3978
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2859
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4558
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4088
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4803
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:1177
bool isObjCContainer() const
Definition: DeclBase.h:2104
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2058
SourceLocation getLocation() const
Definition: DeclBase.h:444
DeclContext * getDeclContext()
Definition: DeclBase.h:453
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
bool isPRValue() const
Definition: Expr.h:278
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
QualType getReturnType() const
Definition: Type.h:4363
Represents a C11 generic selection.
Definition: Expr.h:5725
AssociationTy< false > Association
Definition: Expr.h:5956
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4470
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
A member reference to an MSPropertyDecl.
Definition: ExprCXX.h:929
NestedNameSpecifierLoc getQualifierLoc() const
Definition: ExprCXX.h:986
bool isArrow() const
Definition: ExprCXX.h:984
MSPropertyDecl * getPropertyDecl() const
Definition: ExprCXX.h:983
Expr * getBaseExpr() const
Definition: ExprCXX.h:982
SourceLocation getMemberLoc() const
Definition: ExprCXX.h:985
MS property subscript expression.
Definition: ExprCXX.h:1000
SourceLocation getRBracketLoc() const
Definition: ExprCXX.h:1037
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: ExprObjC.h:1395
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: ExprObjC.h:1405
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
bool isPropertyAccessor() const
Definition: DeclObjC.h:436
static ObjCMethodDecl * Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, bool isInstance=true, bool isVariadic=false, bool isPropertyAccessor=false, bool isSynthesizedAccessorStub=false, bool isImplicitlyDeclared=false, bool isDefined=false, ObjCImplementationControl impControl=ObjCImplementationControl::None, bool HasRelatedResultType=false)
Definition: DeclObjC.cpp:852
Selector getSelector() const
Definition: DeclObjC.h:327
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1210
Represents a pointer to an Objective C object.
Definition: Type.h:6798
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6810
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:6862
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
ObjCPropertyQueryKind getQueryKind() const
Definition: DeclObjC.h:858
Selector getSetterName() const
Definition: DeclObjC.h:891
QualType getType() const
Definition: DeclObjC.h:802
Selector getGetterName() const
Definition: DeclObjC.h:883
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:813
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:617
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:706
ObjCMethodDecl * getImplicitPropertyGetter() const
Definition: ExprObjC.h:711
const Expr * getBase() const
Definition: ExprObjC.h:755
bool isObjectReceiver() const
Definition: ExprObjC.h:774
bool isExplicitProperty() const
Definition: ExprObjC.h:704
QualType getSuperReceiverType() const
Definition: ExprObjC.h:766
ObjCMethodDecl * getImplicitPropertySetter() const
Definition: ExprObjC.h:716
ObjCInterfaceDecl * getClassReceiver() const
Definition: ExprObjC.h:770
SourceLocation getLocation() const
Definition: ExprObjC.h:762
bool isClassReceiver() const
Definition: ExprObjC.h:776
bool isSuperReceiver() const
Definition: ExprObjC.h:775
ObjCSubscriptRefExpr - used for array and dictionary subscripting.
Definition: ExprObjC.h:844
Expr * getKeyExpr() const
Definition: ExprObjC.h:886
Expr * getBaseExpr() const
Definition: ExprObjC.h:883
ObjCMethodDecl * getAtIndexMethodDecl() const
Definition: ExprObjC.h:889
SourceLocation getRBracket() const
Definition: ExprObjC.h:874
ObjCMethodDecl * setAtIndexMethodDecl() const
Definition: ExprObjC.h:893
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
void setIsUnique(bool V)
Definition: Expr.h:1220
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
IdentifierTable & getIdentifierTable()
SelectorTable & getSelectorTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6305
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4875
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
Definition: Expr.h:6347
A (possibly-)qualified type.
Definition: Type.h:738
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
QualType substObjCMemberType(QualType objectType, const DeclContext *dc, ObjCSubstitutionContext context) const
Substitute type arguments from an object type for the Objective-C type parameters used in the subject...
Definition: Type.cpp:1602
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5339
RecordDecl * getDecl() const
Definition: Type.h:5349
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static Selector constructSetterSelector(IdentifierTable &Idents, SelectorTable &SelTable, const IdentifierInfo *Name)
Return the default setter selector for the given identifier.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:698
bool isSelfExpr(Expr *RExpr)
Private Helper predicate to check for 'self'.
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: Sema.h:12442
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
ASTContext & Context
Definition: Sema.h:858
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16036
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:645
Expr * recreateSyntacticForm(PseudoObjectExpr *E)
Given a pseudo-object expression, recreate what it looks like syntactically without the attendant Opa...
const LangOptions & getLangOpts() const
Definition: Sema.h:520
Preprocessor & PP
Definition: Sema.h:857
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6655
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE)
CheckSubscriptingKind - This routine decide what type of indexing represented by "FromE" is being don...
ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:702
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:10023
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6286
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6090
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21225
@ AA_Assigning
Definition: Sema.h:5196
ExprResult checkPseudoObjectRValue(Expr *E)
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
DiagnosticsEngine & Diags
Definition: Sema.h:860
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc)
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:17129
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15600
ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args)
ObjCSubscriptKind
Definition: Sema.h:8451
@ OS_Array
Definition: Sema.h:8451
@ OS_Dictionary
Definition: Sema.h:8451
@ OS_Error
Definition: Sema.h:8451
Encodes a location in the source.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
A container of type source information.
Definition: Type.h:7120
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBlockPointerType() const
Definition: Type.h:7410
bool isVoidType() const
Definition: Type.h:7695
bool isVoidPointerType() const
Definition: Type.cpp:654
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7980
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7810
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7689
bool isLValueReferenceType() const
Definition: Type.h:7418
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2443
bool isObjCIdType() const
Definition: Type.h:7567
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isObjCObjectPointerType() const
Definition: Type.h:7534
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
bool isRecordType() const
Definition: Type.h:7496
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
bool isDecrementOp() const
Definition: Expr.h:2279
bool isPostfix() const
Definition: Expr.h:2267
bool isPrefix() const
Definition: Expr.h:2266
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4838
bool isIncrementDecrementOp() const
Definition: Expr.h:2284
bool isIncrementOp() const
Definition: Expr.h:2272
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1112
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition: ScopeInfo.h:1087
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:160
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READONLY char toLowercase(char c)
Converts the given ASCII character to its lowercase equivalent.
Definition: CharInfo.h:224
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
@ SC_None
Definition: Specifiers.h:247
UnaryOperatorKind
LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
Definition: CharInfo.h:121
LLVM_READONLY char toUppercase(char c)
Converts the given ASCII character to its uppercase equivalent.
Definition: CharInfo.h:233
ExprResult ExprError()
Definition: Ownership.h:264
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
@ Implicit
An implicit conversion.
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define exp(__x)
Definition: tgmath.h:431