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