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