]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaPseudoObject.cpp
Merge clang trunk r321017 to contrib/llvm/tools/clang.
[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,
451                                                FPOptions());
452   } else {
453     ExprResult opLHS = buildGet();
454     if (opLHS.isInvalid()) return ExprError();
455
456     // Build an ordinary, non-compound operation.
457     BinaryOperatorKind nonCompound =
458       BinaryOperator::getOpForCompoundAssignment(opcode);
459     result = S.BuildBinOp(Sc, opcLoc, nonCompound, opLHS.get(), semanticRHS);
460     if (result.isInvalid()) return ExprError();
461
462     syntactic =
463       new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
464                                              result.get()->getType(),
465                                              result.get()->getValueKind(),
466                                              OK_Ordinary,
467                                              opLHS.get()->getType(),
468                                              result.get()->getType(),
469                                              opcLoc, FPOptions());
470   }
471
472   // The result of the assignment, if not void, is the value set into
473   // the l-value.
474   result = buildSet(result.get(), opcLoc, captureSetValueAsResult());
475   if (result.isInvalid()) return ExprError();
476   addSemanticExpr(result.get());
477   if (!captureSetValueAsResult() && !result.get()->getType()->isVoidType() &&
478       (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
479     setResultToLastSemantic();
480
481   return complete(syntactic);
482 }
483
484 /// The basic skeleton for building an increment or decrement
485 /// operation.
486 ExprResult
487 PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
488                                       UnaryOperatorKind opcode,
489                                       Expr *op) {
490   assert(UnaryOperator::isIncrementDecrementOp(opcode));
491
492   Expr *syntacticOp = rebuildAndCaptureObject(op);
493
494   // Load the value.
495   ExprResult result = buildGet();
496   if (result.isInvalid()) return ExprError();
497
498   QualType resultType = result.get()->getType();
499
500   // That's the postfix result.
501   if (UnaryOperator::isPostfix(opcode) &&
502       (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
503     result = capture(result.get());
504     setResultToLastSemantic();
505   }
506
507   // Add or subtract a literal 1.
508   llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
509   Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
510                                      GenericLoc);
511
512   if (UnaryOperator::isIncrementOp(opcode)) {
513     result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one);
514   } else {
515     result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one);
516   }
517   if (result.isInvalid()) return ExprError();
518
519   // Store that back into the result.  The value stored is the result
520   // of a prefix operation.
521   result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode) &&
522                                               captureSetValueAsResult());
523   if (result.isInvalid()) return ExprError();
524   addSemanticExpr(result.get());
525   if (UnaryOperator::isPrefix(opcode) && !captureSetValueAsResult() &&
526       !result.get()->getType()->isVoidType() &&
527       (result.get()->isTypeDependent() || CanCaptureValue(result.get())))
528     setResultToLastSemantic();
529
530   UnaryOperator *syntactic =
531     new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
532                                   VK_LValue, OK_Ordinary, opcLoc);
533   return complete(syntactic);
534 }
535
536
537 //===----------------------------------------------------------------------===//
538 //  Objective-C @property and implicit property references
539 //===----------------------------------------------------------------------===//
540
541 /// Look up a method in the receiver type of an Objective-C property
542 /// reference.
543 static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
544                                             const ObjCPropertyRefExpr *PRE) {
545   if (PRE->isObjectReceiver()) {
546     const ObjCObjectPointerType *PT =
547       PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
548
549     // Special case for 'self' in class method implementations.
550     if (PT->isObjCClassType() &&
551         S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
552       // This cast is safe because isSelfExpr is only true within
553       // methods.
554       ObjCMethodDecl *method =
555         cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
556       return S.LookupMethodInObjectType(sel,
557                  S.Context.getObjCInterfaceType(method->getClassInterface()),
558                                         /*instance*/ false);
559     }
560
561     return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
562   }
563
564   if (PRE->isSuperReceiver()) {
565     if (const ObjCObjectPointerType *PT =
566         PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
567       return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
568
569     return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
570   }
571
572   assert(PRE->isClassReceiver() && "Invalid expression");
573   QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
574   return S.LookupMethodInObjectType(sel, IT, false);
575 }
576
577 bool ObjCPropertyOpBuilder::isWeakProperty() const {
578   QualType T;
579   if (RefExpr->isExplicitProperty()) {
580     const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
581     if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
582       return true;
583
584     T = Prop->getType();
585   } else if (Getter) {
586     T = Getter->getReturnType();
587   } else {
588     return false;
589   }
590
591   return T.getObjCLifetime() == Qualifiers::OCL_Weak;
592 }
593
594 bool ObjCPropertyOpBuilder::findGetter() {
595   if (Getter) return true;
596
597   // For implicit properties, just trust the lookup we already did.
598   if (RefExpr->isImplicitProperty()) {
599     if ((Getter = RefExpr->getImplicitPropertyGetter())) {
600       GetterSelector = Getter->getSelector();
601       return true;
602     }
603     else {
604       // Must build the getter selector the hard way.
605       ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
606       assert(setter && "both setter and getter are null - cannot happen");
607       IdentifierInfo *setterName = 
608         setter->getSelector().getIdentifierInfoForSlot(0);
609       IdentifierInfo *getterName =
610           &S.Context.Idents.get(setterName->getName().substr(3));
611       GetterSelector = 
612         S.PP.getSelectorTable().getNullarySelector(getterName);
613       return false;
614     }
615   }
616
617   ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
618   Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
619   return (Getter != nullptr);
620 }
621
622 /// Try to find the most accurate setter declaration for the property
623 /// reference.
624 ///
625 /// \return true if a setter was found, in which case Setter 
626 bool ObjCPropertyOpBuilder::findSetter(bool warn) {
627   // For implicit properties, just trust the lookup we already did.
628   if (RefExpr->isImplicitProperty()) {
629     if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
630       Setter = setter;
631       SetterSelector = setter->getSelector();
632       return true;
633     } else {
634       IdentifierInfo *getterName =
635         RefExpr->getImplicitPropertyGetter()->getSelector()
636           .getIdentifierInfoForSlot(0);
637       SetterSelector =
638         SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
639                                                S.PP.getSelectorTable(),
640                                                getterName);
641       return false;
642     }
643   }
644
645   // For explicit properties, this is more involved.
646   ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
647   SetterSelector = prop->getSetterName();
648
649   // Do a normal method lookup first.
650   if (ObjCMethodDecl *setter =
651         LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
652     if (setter->isPropertyAccessor() && warn)
653       if (const ObjCInterfaceDecl *IFace =
654           dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
655         StringRef thisPropertyName = prop->getName();
656         // Try flipping the case of the first character.
657         char front = thisPropertyName.front();
658         front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
659         SmallString<100> PropertyName = thisPropertyName;
660         PropertyName[0] = front;
661         IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
662         if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(
663                 AltMember, prop->getQueryKind()))
664           if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
665             S.Diag(RefExpr->getExprLoc(), diag::err_property_setter_ambiguous_use)
666               << prop << prop1 << setter->getSelector();
667             S.Diag(prop->getLocation(), diag::note_property_declare);
668             S.Diag(prop1->getLocation(), diag::note_property_declare);
669           }
670       }
671     Setter = setter;
672     return true;
673   }
674
675   // That can fail in the somewhat crazy situation that we're
676   // type-checking a message send within the @interface declaration
677   // that declared the @property.  But it's not clear that that's
678   // valuable to support.
679
680   return false;
681 }
682
683 void ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() {
684   if (S.getCurLexicalContext()->isObjCContainer() &&
685       S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
686       S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) {
687     if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) {
688         S.Diag(RefExpr->getLocation(),
689                diag::err_property_function_in_objc_container);
690         S.Diag(prop->getLocation(), diag::note_property_declare);
691     }
692   }
693 }
694
695 /// Capture the base object of an Objective-C property expression.
696 Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
697   assert(InstanceReceiver == nullptr);
698
699   // If we have a base, capture it in an OVE and rebuild the syntactic
700   // form to use the OVE as its base.
701   if (RefExpr->isObjectReceiver()) {
702     InstanceReceiver = capture(RefExpr->getBase());
703     syntacticBase = Rebuilder(S, [=](Expr *, unsigned) -> Expr * {
704                       return InstanceReceiver;
705                     }).rebuild(syntacticBase);
706   }
707
708   if (ObjCPropertyRefExpr *
709         refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
710     SyntacticRefExpr = refE;
711
712   return syntacticBase;
713 }
714
715 /// Load from an Objective-C property reference.
716 ExprResult ObjCPropertyOpBuilder::buildGet() {
717   findGetter();
718   if (!Getter) {
719     DiagnoseUnsupportedPropertyUse();
720     return ExprError();
721   }
722
723   if (SyntacticRefExpr)
724     SyntacticRefExpr->setIsMessagingGetter();
725
726   QualType receiverType = RefExpr->getReceiverType(S.Context);
727   if (!Getter->isImplicit())
728     S.DiagnoseUseOfDecl(Getter, GenericLoc, nullptr, true);
729   // Build a message-send.
730   ExprResult msg;
731   if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
732       RefExpr->isObjectReceiver()) {
733     assert(InstanceReceiver || RefExpr->isSuperReceiver());
734     msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
735                                          GenericLoc, Getter->getSelector(),
736                                          Getter, None);
737   } else {
738     msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
739                                       GenericLoc, Getter->getSelector(),
740                                       Getter, None);
741   }
742   return msg;
743 }
744
745 /// Store to an Objective-C property reference.
746 ///
747 /// \param captureSetValueAsResult If true, capture the actual
748 ///   value being set as the value of the property operation.
749 ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
750                                            bool captureSetValueAsResult) {
751   if (!findSetter(false)) {
752     DiagnoseUnsupportedPropertyUse();
753     return ExprError();
754   }
755
756   if (SyntacticRefExpr)
757     SyntacticRefExpr->setIsMessagingSetter();
758
759   QualType receiverType = RefExpr->getReceiverType(S.Context);
760
761   // Use assignment constraints when possible; they give us better
762   // diagnostics.  "When possible" basically means anything except a
763   // C++ class type.
764   if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
765     QualType paramType = (*Setter->param_begin())->getType()
766                            .substObjCMemberType(
767                              receiverType,
768                              Setter->getDeclContext(),
769                              ObjCSubstitutionContext::Parameter);
770     if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
771       ExprResult opResult = op;
772       Sema::AssignConvertType assignResult
773         = S.CheckSingleAssignmentConstraints(paramType, opResult);
774       if (opResult.isInvalid() ||
775           S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
776                                      op->getType(), opResult.get(),
777                                      Sema::AA_Assigning))
778         return ExprError();
779
780       op = opResult.get();
781       assert(op && "successful assignment left argument invalid?");
782     }
783   }
784
785   // Arguments.
786   Expr *args[] = { op };
787
788   // Build a message-send.
789   ExprResult msg;
790   if (!Setter->isImplicit())
791     S.DiagnoseUseOfDecl(Setter, GenericLoc, nullptr, true);
792   if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
793       RefExpr->isObjectReceiver()) {
794     msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
795                                          GenericLoc, SetterSelector, Setter,
796                                          MultiExprArg(args, 1));
797   } else {
798     msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
799                                       GenericLoc,
800                                       SetterSelector, Setter,
801                                       MultiExprArg(args, 1));
802   }
803
804   if (!msg.isInvalid() && captureSetValueAsResult) {
805     ObjCMessageExpr *msgExpr =
806       cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
807     Expr *arg = msgExpr->getArg(0);
808     if (CanCaptureValue(arg))
809       msgExpr->setArg(0, captureValueAsResult(arg));
810   }
811
812   return msg;
813 }
814
815 /// @property-specific behavior for doing lvalue-to-rvalue conversion.
816 ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
817   // Explicit properties always have getters, but implicit ones don't.
818   // Check that before proceeding.
819   if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
820     S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
821         << RefExpr->getSourceRange();
822     return ExprError();
823   }
824
825   ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
826   if (result.isInvalid()) return ExprError();
827
828   if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
829     S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
830                                        Getter, RefExpr->getLocation());
831
832   // As a special case, if the method returns 'id', try to get
833   // a better type from the property.
834   if (RefExpr->isExplicitProperty() && result.get()->isRValue()) {
835     QualType receiverType = RefExpr->getReceiverType(S.Context);
836     QualType propType = RefExpr->getExplicitProperty()
837                           ->getUsageType(receiverType);
838     if (result.get()->getType()->isObjCIdType()) {
839       if (const ObjCObjectPointerType *ptr
840             = propType->getAs<ObjCObjectPointerType>()) {
841         if (!ptr->isObjCIdType())
842           result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
843       }
844     }
845     if (propType.getObjCLifetime() == Qualifiers::OCL_Weak &&
846         !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
847                            RefExpr->getLocation()))
848       S.getCurFunction()->markSafeWeakUse(RefExpr);
849   }
850
851   return result;
852 }
853
854 /// Try to build this as a call to a getter that returns a reference.
855 ///
856 /// \return true if it was possible, whether or not it actually
857 ///   succeeded
858 bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
859                                                    ExprResult &result) {
860   if (!S.getLangOpts().CPlusPlus) return false;
861
862   findGetter();
863   if (!Getter) {
864     // The property has no setter and no getter! This can happen if the type is
865     // invalid. Error have already been reported.
866     result = ExprError();
867     return true;
868   }
869
870   // Only do this if the getter returns an l-value reference type.
871   QualType resultType = Getter->getReturnType();
872   if (!resultType->isLValueReferenceType()) return false;
873
874   result = buildRValueOperation(op);
875   return true;
876 }
877
878 /// @property-specific behavior for doing assignments.
879 ExprResult
880 ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
881                                                 SourceLocation opcLoc,
882                                                 BinaryOperatorKind opcode,
883                                                 Expr *LHS, Expr *RHS) {
884   assert(BinaryOperator::isAssignmentOp(opcode));
885
886   // If there's no setter, we have no choice but to try to assign to
887   // the result of the getter.
888   if (!findSetter()) {
889     ExprResult result;
890     if (tryBuildGetOfReference(LHS, result)) {
891       if (result.isInvalid()) return ExprError();
892       return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS);
893     }
894
895     // Otherwise, it's an error.
896     S.Diag(opcLoc, diag::err_nosetter_property_assignment)
897       << unsigned(RefExpr->isImplicitProperty())
898       << SetterSelector
899       << LHS->getSourceRange() << RHS->getSourceRange();
900     return ExprError();
901   }
902
903   // If there is a setter, we definitely want to use it.
904
905   // Verify that we can do a compound assignment.
906   if (opcode != BO_Assign && !findGetter()) {
907     S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
908       << LHS->getSourceRange() << RHS->getSourceRange();
909     return ExprError();
910   }
911
912   ExprResult result =
913     PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
914   if (result.isInvalid()) return ExprError();
915
916   // Various warnings about property assignments in ARC.
917   if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
918     S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
919     S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
920   }
921
922   return result;
923 }
924
925 /// @property-specific behavior for doing increments and decrements.
926 ExprResult
927 ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
928                                             UnaryOperatorKind opcode,
929                                             Expr *op) {
930   // If there's no setter, we have no choice but to try to assign to
931   // the result of the getter.
932   if (!findSetter()) {
933     ExprResult result;
934     if (tryBuildGetOfReference(op, result)) {
935       if (result.isInvalid()) return ExprError();
936       return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get());
937     }
938
939     // Otherwise, it's an error.
940     S.Diag(opcLoc, diag::err_nosetter_property_incdec)
941       << unsigned(RefExpr->isImplicitProperty())
942       << unsigned(UnaryOperator::isDecrementOp(opcode))
943       << SetterSelector
944       << op->getSourceRange();
945     return ExprError();
946   }
947
948   // If there is a setter, we definitely want to use it.
949
950   // We also need a getter.
951   if (!findGetter()) {
952     assert(RefExpr->isImplicitProperty());
953     S.Diag(opcLoc, diag::err_nogetter_property_incdec)
954       << unsigned(UnaryOperator::isDecrementOp(opcode))
955       << GetterSelector
956       << op->getSourceRange();
957     return ExprError();
958   }
959
960   return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
961 }
962
963 ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
964   if (isWeakProperty() &&
965       !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
966                          SyntacticForm->getLocStart()))
967     S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
968                                SyntacticRefExpr->isMessagingGetter());
969
970   return PseudoOpBuilder::complete(SyntacticForm);
971 }
972
973 // ObjCSubscript build stuff.
974 //
975
976 /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue 
977 /// conversion.
978 /// FIXME. Remove this routine if it is proven that no additional 
979 /// specifity is needed.
980 ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
981   ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
982   if (result.isInvalid()) return ExprError();
983   return result;
984 }
985
986 /// objective-c subscripting-specific  behavior for doing assignments.
987 ExprResult
988 ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
989                                                 SourceLocation opcLoc,
990                                                 BinaryOperatorKind opcode,
991                                                 Expr *LHS, Expr *RHS) {
992   assert(BinaryOperator::isAssignmentOp(opcode));
993   // There must be a method to do the Index'ed assignment.
994   if (!findAtIndexSetter())
995     return ExprError();
996   
997   // Verify that we can do a compound assignment.
998   if (opcode != BO_Assign && !findAtIndexGetter())
999     return ExprError();
1000   
1001   ExprResult result =
1002   PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
1003   if (result.isInvalid()) return ExprError();
1004   
1005   // Various warnings about objc Index'ed assignments in ARC.
1006   if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
1007     S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
1008     S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
1009   }
1010   
1011   return result;
1012 }
1013
1014 /// Capture the base object of an Objective-C Index'ed expression.
1015 Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1016   assert(InstanceBase == nullptr);
1017
1018   // Capture base expression in an OVE and rebuild the syntactic
1019   // form to use the OVE as its base expression.
1020   InstanceBase = capture(RefExpr->getBaseExpr());
1021   InstanceKey = capture(RefExpr->getKeyExpr());
1022
1023   syntacticBase =
1024       Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
1025         switch (Idx) {
1026         case 0:
1027           return InstanceBase;
1028         case 1:
1029           return InstanceKey;
1030         default:
1031           llvm_unreachable("Unexpected index for ObjCSubscriptExpr");
1032         }
1033       }).rebuild(syntacticBase);
1034
1035   return syntacticBase;
1036 }
1037
1038 /// CheckSubscriptingKind - This routine decide what type 
1039 /// of indexing represented by "FromE" is being done.
1040 Sema::ObjCSubscriptKind 
1041   Sema::CheckSubscriptingKind(Expr *FromE) {
1042   // If the expression already has integral or enumeration type, we're golden.
1043   QualType T = FromE->getType();
1044   if (T->isIntegralOrEnumerationType())
1045     return OS_Array;
1046   
1047   // If we don't have a class type in C++, there's no way we can get an
1048   // expression of integral or enumeration type.
1049   const RecordType *RecordTy = T->getAs<RecordType>();
1050   if (!RecordTy &&
1051       (T->isObjCObjectPointerType() || T->isVoidPointerType()))
1052     // All other scalar cases are assumed to be dictionary indexing which
1053     // caller handles, with diagnostics if needed.
1054     return OS_Dictionary;
1055   if (!getLangOpts().CPlusPlus || 
1056       !RecordTy || RecordTy->isIncompleteType()) {
1057     // No indexing can be done. Issue diagnostics and quit.
1058     const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1059     if (isa<StringLiteral>(IndexExpr))
1060       Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1061         << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1062     else
1063       Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1064         << T;
1065     return OS_Error;
1066   }
1067   
1068   // We must have a complete class type.
1069   if (RequireCompleteType(FromE->getExprLoc(), T, 
1070                           diag::err_objc_index_incomplete_class_type, FromE))
1071     return OS_Error;
1072   
1073   // Look for a conversion to an integral, enumeration type, or
1074   // objective-C pointer type.
1075   int NoIntegrals=0, NoObjCIdPointers=0;
1076   SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1077
1078   for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
1079                           ->getVisibleConversionFunctions()) {
1080     if (CXXConversionDecl *Conversion =
1081             dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
1082       QualType CT = Conversion->getConversionType().getNonReferenceType();
1083       if (CT->isIntegralOrEnumerationType()) {
1084         ++NoIntegrals;
1085         ConversionDecls.push_back(Conversion);
1086       }
1087       else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1088         ++NoObjCIdPointers;
1089         ConversionDecls.push_back(Conversion);
1090       }
1091     }
1092   }
1093   if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1094     return OS_Array;
1095   if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1096     return OS_Dictionary;
1097   if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1098     // No conversion function was found. Issue diagnostic and return.
1099     Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1100       << FromE->getType();
1101     return OS_Error;
1102   }
1103   Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1104       << FromE->getType();
1105   for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1106     Diag(ConversionDecls[i]->getLocation(),
1107          diag::note_conv_function_declared_at);
1108
1109   return OS_Error;
1110 }
1111
1112 /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1113 /// objects used as dictionary subscript key objects.
1114 static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, 
1115                                          Expr *Key) {
1116   if (ContainerT.isNull())
1117     return;
1118   // dictionary subscripting.
1119   // - (id)objectForKeyedSubscript:(id)key;
1120   IdentifierInfo *KeyIdents[] = {
1121     &S.Context.Idents.get("objectForKeyedSubscript")  
1122   };
1123   Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1124   ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, 
1125                                                       true /*instance*/);
1126   if (!Getter)
1127     return;
1128   QualType T = Getter->parameters()[0]->getType();
1129   S.CheckObjCConversion(Key->getSourceRange(), T, Key,
1130                         Sema::CCK_ImplicitConversion);
1131 }
1132
1133 bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1134   if (AtIndexGetter)
1135     return true;
1136   
1137   Expr *BaseExpr = RefExpr->getBaseExpr();
1138   QualType BaseT = BaseExpr->getType();
1139   
1140   QualType ResultType;
1141   if (const ObjCObjectPointerType *PTy =
1142       BaseT->getAs<ObjCObjectPointerType>()) {
1143     ResultType = PTy->getPointeeType();
1144   }
1145   Sema::ObjCSubscriptKind Res = 
1146     S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1147   if (Res == Sema::OS_Error) {
1148     if (S.getLangOpts().ObjCAutoRefCount)
1149       CheckKeyForObjCARCConversion(S, ResultType, 
1150                                    RefExpr->getKeyExpr());
1151     return false;
1152   }
1153   bool arrayRef = (Res == Sema::OS_Array);
1154   
1155   if (ResultType.isNull()) {
1156     S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1157       << BaseExpr->getType() << arrayRef;
1158     return false;
1159   }
1160   if (!arrayRef) {
1161     // dictionary subscripting.
1162     // - (id)objectForKeyedSubscript:(id)key;
1163     IdentifierInfo *KeyIdents[] = {
1164       &S.Context.Idents.get("objectForKeyedSubscript")  
1165     };
1166     AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1167   }
1168   else {
1169     // - (id)objectAtIndexedSubscript:(size_t)index;
1170     IdentifierInfo *KeyIdents[] = {
1171       &S.Context.Idents.get("objectAtIndexedSubscript")  
1172     };
1173   
1174     AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1175   }
1176   
1177   AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, 
1178                                              true /*instance*/);
1179   
1180   if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
1181     AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), 
1182                            SourceLocation(), AtIndexGetterSelector,
1183                            S.Context.getObjCIdType() /*ReturnType*/,
1184                            nullptr /*TypeSourceInfo */,
1185                            S.Context.getTranslationUnitDecl(),
1186                            true /*Instance*/, false/*isVariadic*/,
1187                            /*isPropertyAccessor=*/false,
1188                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1189                            ObjCMethodDecl::Required,
1190                            false);
1191     ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1192                                                 SourceLocation(), SourceLocation(),
1193                                                 arrayRef ? &S.Context.Idents.get("index")
1194                                                          : &S.Context.Idents.get("key"),
1195                                                 arrayRef ? S.Context.UnsignedLongTy
1196                                                          : S.Context.getObjCIdType(),
1197                                                 /*TInfo=*/nullptr,
1198                                                 SC_None,
1199                                                 nullptr);
1200     AtIndexGetter->setMethodParams(S.Context, Argument, None);
1201   }
1202
1203   if (!AtIndexGetter) {
1204     if (!BaseT->isObjCIdType()) {
1205       S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1206       << BaseExpr->getType() << 0 << arrayRef;
1207       return false;
1208     }
1209     AtIndexGetter = 
1210       S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, 
1211                                          RefExpr->getSourceRange(), 
1212                                          true);
1213   }
1214   
1215   if (AtIndexGetter) {
1216     QualType T = AtIndexGetter->parameters()[0]->getType();
1217     if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1218         (!arrayRef && !T->isObjCObjectPointerType())) {
1219       S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 
1220              arrayRef ? diag::err_objc_subscript_index_type
1221                       : diag::err_objc_subscript_key_type) << T;
1222       S.Diag(AtIndexGetter->parameters()[0]->getLocation(), 
1223              diag::note_parameter_type) << T;
1224       return false;
1225     }
1226     QualType R = AtIndexGetter->getReturnType();
1227     if (!R->isObjCObjectPointerType()) {
1228       S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1229              diag::err_objc_indexing_method_result_type) << R << arrayRef;
1230       S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1231         AtIndexGetter->getDeclName();
1232     }
1233   }
1234   return true;
1235 }
1236
1237 bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1238   if (AtIndexSetter)
1239     return true;
1240   
1241   Expr *BaseExpr = RefExpr->getBaseExpr();
1242   QualType BaseT = BaseExpr->getType();
1243   
1244   QualType ResultType;
1245   if (const ObjCObjectPointerType *PTy =
1246       BaseT->getAs<ObjCObjectPointerType>()) {
1247     ResultType = PTy->getPointeeType();
1248   }
1249   
1250   Sema::ObjCSubscriptKind Res = 
1251     S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1252   if (Res == Sema::OS_Error) {
1253     if (S.getLangOpts().ObjCAutoRefCount)
1254       CheckKeyForObjCARCConversion(S, ResultType, 
1255                                    RefExpr->getKeyExpr());
1256     return false;
1257   }
1258   bool arrayRef = (Res == Sema::OS_Array);
1259   
1260   if (ResultType.isNull()) {
1261     S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1262       << BaseExpr->getType() << arrayRef;
1263     return false;
1264   }
1265   
1266   if (!arrayRef) {
1267     // dictionary subscripting.
1268     // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1269     IdentifierInfo *KeyIdents[] = {
1270       &S.Context.Idents.get("setObject"),
1271       &S.Context.Idents.get("forKeyedSubscript")
1272     };
1273     AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1274   }
1275   else {
1276     // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1277     IdentifierInfo *KeyIdents[] = {
1278       &S.Context.Idents.get("setObject"),
1279       &S.Context.Idents.get("atIndexedSubscript")
1280     };
1281     AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1282   }
1283   AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, 
1284                                              true /*instance*/);
1285
1286   if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
1287     TypeSourceInfo *ReturnTInfo = nullptr;
1288     QualType ReturnType = S.Context.VoidTy;
1289     AtIndexSetter = ObjCMethodDecl::Create(
1290         S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1291         ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1292         true /*Instance*/, false /*isVariadic*/,
1293         /*isPropertyAccessor=*/false,
1294         /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1295         ObjCMethodDecl::Required, false);
1296     SmallVector<ParmVarDecl *, 2> Params;
1297     ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1298                                                 SourceLocation(), SourceLocation(),
1299                                                 &S.Context.Idents.get("object"),
1300                                                 S.Context.getObjCIdType(),
1301                                                 /*TInfo=*/nullptr,
1302                                                 SC_None,
1303                                                 nullptr);
1304     Params.push_back(object);
1305     ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1306                                                 SourceLocation(), SourceLocation(),
1307                                                 arrayRef ?  &S.Context.Idents.get("index")
1308                                                          :  &S.Context.Idents.get("key"),
1309                                                 arrayRef ? S.Context.UnsignedLongTy
1310                                                          : S.Context.getObjCIdType(),
1311                                                 /*TInfo=*/nullptr,
1312                                                 SC_None,
1313                                                 nullptr);
1314     Params.push_back(key);
1315     AtIndexSetter->setMethodParams(S.Context, Params, None);
1316   }
1317   
1318   if (!AtIndexSetter) {
1319     if (!BaseT->isObjCIdType()) {
1320       S.Diag(BaseExpr->getExprLoc(), 
1321              diag::err_objc_subscript_method_not_found)
1322       << BaseExpr->getType() << 1 << arrayRef;
1323       return false;
1324     }
1325     AtIndexSetter = 
1326       S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, 
1327                                          RefExpr->getSourceRange(), 
1328                                          true);
1329   }
1330   
1331   bool err = false;
1332   if (AtIndexSetter && arrayRef) {
1333     QualType T = AtIndexSetter->parameters()[1]->getType();
1334     if (!T->isIntegralOrEnumerationType()) {
1335       S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 
1336              diag::err_objc_subscript_index_type) << T;
1337       S.Diag(AtIndexSetter->parameters()[1]->getLocation(), 
1338              diag::note_parameter_type) << T;
1339       err = true;
1340     }
1341     T = AtIndexSetter->parameters()[0]->getType();
1342     if (!T->isObjCObjectPointerType()) {
1343       S.Diag(RefExpr->getBaseExpr()->getExprLoc(), 
1344              diag::err_objc_subscript_object_type) << T << arrayRef;
1345       S.Diag(AtIndexSetter->parameters()[0]->getLocation(), 
1346              diag::note_parameter_type) << T;
1347       err = true;
1348     }
1349   }
1350   else if (AtIndexSetter && !arrayRef)
1351     for (unsigned i=0; i <2; i++) {
1352       QualType T = AtIndexSetter->parameters()[i]->getType();
1353       if (!T->isObjCObjectPointerType()) {
1354         if (i == 1)
1355           S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1356                  diag::err_objc_subscript_key_type) << T;
1357         else
1358           S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1359                  diag::err_objc_subscript_dic_object_type) << T;
1360         S.Diag(AtIndexSetter->parameters()[i]->getLocation(), 
1361                diag::note_parameter_type) << T;
1362         err = true;
1363       }
1364     }
1365
1366   return !err;
1367 }
1368
1369 // Get the object at "Index" position in the container.
1370 // [BaseExpr objectAtIndexedSubscript : IndexExpr];
1371 ExprResult ObjCSubscriptOpBuilder::buildGet() {
1372   if (!findAtIndexGetter())
1373     return ExprError();
1374   
1375   QualType receiverType = InstanceBase->getType();
1376     
1377   // Build a message-send.
1378   ExprResult msg;
1379   Expr *Index = InstanceKey;
1380   
1381   // Arguments.
1382   Expr *args[] = { Index };
1383   assert(InstanceBase);
1384   if (AtIndexGetter)
1385     S.DiagnoseUseOfDecl(AtIndexGetter, GenericLoc);
1386   msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1387                                        GenericLoc,
1388                                        AtIndexGetterSelector, AtIndexGetter,
1389                                        MultiExprArg(args, 1));
1390   return msg;
1391 }
1392
1393 /// Store into the container the "op" object at "Index"'ed location
1394 /// by building this messaging expression:
1395 /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1396 /// \param captureSetValueAsResult If true, capture the actual
1397 ///   value being set as the value of the property operation.
1398 ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1399                                            bool captureSetValueAsResult) {
1400   if (!findAtIndexSetter())
1401     return ExprError();
1402   if (AtIndexSetter)
1403     S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc);
1404   QualType receiverType = InstanceBase->getType();
1405   Expr *Index = InstanceKey;
1406   
1407   // Arguments.
1408   Expr *args[] = { op, Index };
1409   
1410   // Build a message-send.
1411   ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1412                                                   GenericLoc,
1413                                                   AtIndexSetterSelector,
1414                                                   AtIndexSetter,
1415                                                   MultiExprArg(args, 2));
1416   
1417   if (!msg.isInvalid() && captureSetValueAsResult) {
1418     ObjCMessageExpr *msgExpr =
1419       cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1420     Expr *arg = msgExpr->getArg(0);
1421     if (CanCaptureValue(arg))
1422       msgExpr->setArg(0, captureValueAsResult(arg));
1423   }
1424   
1425   return msg;
1426 }
1427
1428 //===----------------------------------------------------------------------===//
1429 //  MSVC __declspec(property) references
1430 //===----------------------------------------------------------------------===//
1431
1432 MSPropertyRefExpr *
1433 MSPropertyOpBuilder::getBaseMSProperty(MSPropertySubscriptExpr *E) {
1434   CallArgs.insert(CallArgs.begin(), E->getIdx());
1435   Expr *Base = E->getBase()->IgnoreParens();
1436   while (auto *MSPropSubscript = dyn_cast<MSPropertySubscriptExpr>(Base)) {
1437     CallArgs.insert(CallArgs.begin(), MSPropSubscript->getIdx());
1438     Base = MSPropSubscript->getBase()->IgnoreParens();
1439   }
1440   return cast<MSPropertyRefExpr>(Base);
1441 }
1442
1443 Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1444   InstanceBase = capture(RefExpr->getBaseExpr());
1445   llvm::for_each(CallArgs, [this](Expr *&Arg) { Arg = capture(Arg); });
1446   syntacticBase = Rebuilder(S, [=](Expr *, unsigned Idx) -> Expr * {
1447                     switch (Idx) {
1448                     case 0:
1449                       return InstanceBase;
1450                     default:
1451                       assert(Idx <= CallArgs.size());
1452                       return CallArgs[Idx - 1];
1453                     }
1454                   }).rebuild(syntacticBase);
1455
1456   return syntacticBase;
1457 }
1458
1459 ExprResult MSPropertyOpBuilder::buildGet() {
1460   if (!RefExpr->getPropertyDecl()->hasGetter()) {
1461     S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
1462       << 0 /* getter */ << RefExpr->getPropertyDecl();
1463     return ExprError();
1464   }
1465
1466   UnqualifiedId GetterName;
1467   IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1468   GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1469   CXXScopeSpec SS;
1470   SS.Adopt(RefExpr->getQualifierLoc());
1471   ExprResult GetterExpr =
1472       S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
1473                               RefExpr->isArrow() ? tok::arrow : tok::period, SS,
1474                               SourceLocation(), GetterName, nullptr);
1475   if (GetterExpr.isInvalid()) {
1476     S.Diag(RefExpr->getMemberLoc(),
1477            diag::err_cannot_find_suitable_accessor) << 0 /* getter */
1478       << RefExpr->getPropertyDecl();
1479     return ExprError();
1480   }
1481
1482   return S.ActOnCallExpr(S.getCurScope(), GetterExpr.get(),
1483                          RefExpr->getSourceRange().getBegin(), CallArgs,
1484                          RefExpr->getSourceRange().getEnd());
1485 }
1486
1487 ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1488                                          bool captureSetValueAsResult) {
1489   if (!RefExpr->getPropertyDecl()->hasSetter()) {
1490     S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
1491       << 1 /* setter */ << RefExpr->getPropertyDecl();
1492     return ExprError();
1493   }
1494
1495   UnqualifiedId SetterName;
1496   IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1497   SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1498   CXXScopeSpec SS;
1499   SS.Adopt(RefExpr->getQualifierLoc());
1500   ExprResult SetterExpr =
1501       S.ActOnMemberAccessExpr(S.getCurScope(), InstanceBase, SourceLocation(),
1502                               RefExpr->isArrow() ? tok::arrow : tok::period, SS,
1503                               SourceLocation(), SetterName, nullptr);
1504   if (SetterExpr.isInvalid()) {
1505     S.Diag(RefExpr->getMemberLoc(),
1506            diag::err_cannot_find_suitable_accessor) << 1 /* setter */
1507       << RefExpr->getPropertyDecl();
1508     return ExprError();
1509   }
1510
1511   SmallVector<Expr*, 4> ArgExprs;
1512   ArgExprs.append(CallArgs.begin(), CallArgs.end());
1513   ArgExprs.push_back(op);
1514   return S.ActOnCallExpr(S.getCurScope(), SetterExpr.get(),
1515                          RefExpr->getSourceRange().getBegin(), ArgExprs,
1516                          op->getSourceRange().getEnd());
1517 }
1518
1519 //===----------------------------------------------------------------------===//
1520 //  General Sema routines.
1521 //===----------------------------------------------------------------------===//
1522
1523 ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1524   Expr *opaqueRef = E->IgnoreParens();
1525   if (ObjCPropertyRefExpr *refExpr
1526         = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1527     ObjCPropertyOpBuilder builder(*this, refExpr);
1528     return builder.buildRValueOperation(E);
1529   }
1530   else if (ObjCSubscriptRefExpr *refExpr
1531            = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1532     ObjCSubscriptOpBuilder builder(*this, refExpr);
1533     return builder.buildRValueOperation(E);
1534   } else if (MSPropertyRefExpr *refExpr
1535              = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1536     MSPropertyOpBuilder builder(*this, refExpr);
1537     return builder.buildRValueOperation(E);
1538   } else if (MSPropertySubscriptExpr *RefExpr =
1539                  dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1540     MSPropertyOpBuilder Builder(*this, RefExpr);
1541     return Builder.buildRValueOperation(E);
1542   } else {
1543     llvm_unreachable("unknown pseudo-object kind!");
1544   }
1545 }
1546
1547 /// Check an increment or decrement of a pseudo-object expression.
1548 ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1549                                          UnaryOperatorKind opcode, Expr *op) {
1550   // Do nothing if the operand is dependent.
1551   if (op->isTypeDependent())
1552     return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1553                                        VK_RValue, OK_Ordinary, opcLoc);
1554
1555   assert(UnaryOperator::isIncrementDecrementOp(opcode));
1556   Expr *opaqueRef = op->IgnoreParens();
1557   if (ObjCPropertyRefExpr *refExpr
1558         = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1559     ObjCPropertyOpBuilder builder(*this, refExpr);
1560     return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1561   } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1562     Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1563     return ExprError();
1564   } else if (MSPropertyRefExpr *refExpr
1565              = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1566     MSPropertyOpBuilder builder(*this, refExpr);
1567     return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1568   } else if (MSPropertySubscriptExpr *RefExpr
1569              = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1570     MSPropertyOpBuilder Builder(*this, RefExpr);
1571     return Builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1572   } else {
1573     llvm_unreachable("unknown pseudo-object kind!");
1574   }
1575 }
1576
1577 ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1578                                              BinaryOperatorKind opcode,
1579                                              Expr *LHS, Expr *RHS) {
1580   // Do nothing if either argument is dependent.
1581   if (LHS->isTypeDependent() || RHS->isTypeDependent())
1582     return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
1583                                         VK_RValue, OK_Ordinary, opcLoc,
1584                                         FPOptions());
1585
1586   // Filter out non-overload placeholder types in the RHS.
1587   if (RHS->getType()->isNonOverloadPlaceholderType()) {
1588     ExprResult result = CheckPlaceholderExpr(RHS);
1589     if (result.isInvalid()) return ExprError();
1590     RHS = result.get();
1591   }
1592
1593   Expr *opaqueRef = LHS->IgnoreParens();
1594   if (ObjCPropertyRefExpr *refExpr
1595         = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1596     ObjCPropertyOpBuilder builder(*this, refExpr);
1597     return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1598   } else if (ObjCSubscriptRefExpr *refExpr
1599              = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1600     ObjCSubscriptOpBuilder builder(*this, refExpr);
1601     return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1602   } else if (MSPropertyRefExpr *refExpr
1603              = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1604       MSPropertyOpBuilder builder(*this, refExpr);
1605       return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1606   } else if (MSPropertySubscriptExpr *RefExpr
1607              = dyn_cast<MSPropertySubscriptExpr>(opaqueRef)) {
1608       MSPropertyOpBuilder Builder(*this, RefExpr);
1609       return Builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1610   } else {
1611     llvm_unreachable("unknown pseudo-object kind!");
1612   }
1613 }
1614
1615 /// Given a pseudo-object reference, rebuild it without the opaque
1616 /// values.  Basically, undo the behavior of rebuildAndCaptureObject.
1617 /// This should never operate in-place.
1618 static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1619   return Rebuilder(S,
1620                    [=](Expr *E, unsigned) -> Expr * {
1621                      return cast<OpaqueValueExpr>(E)->getSourceExpr();
1622                    })
1623       .rebuild(E);
1624 }
1625
1626 /// Given a pseudo-object expression, recreate what it looks like
1627 /// syntactically without the attendant OpaqueValueExprs.
1628 ///
1629 /// This is a hack which should be removed when TreeTransform is
1630 /// capable of rebuilding a tree without stripping implicit
1631 /// operations.
1632 Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1633   Expr *syntax = E->getSyntacticForm();
1634   if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1635     Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1636     return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1637                                        uop->getValueKind(), uop->getObjectKind(),
1638                                        uop->getOperatorLoc());
1639   } else if (CompoundAssignOperator *cop
1640                = dyn_cast<CompoundAssignOperator>(syntax)) {
1641     Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1642     Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1643     return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1644                                                 cop->getType(),
1645                                                 cop->getValueKind(),
1646                                                 cop->getObjectKind(),
1647                                                 cop->getComputationLHSType(),
1648                                                 cop->getComputationResultType(),
1649                                                 cop->getOperatorLoc(),
1650                                                 FPOptions());
1651   } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1652     Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1653     Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1654     return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1655                                         bop->getType(), bop->getValueKind(),
1656                                         bop->getObjectKind(),
1657                                         bop->getOperatorLoc(), FPOptions());
1658   } else {
1659     assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1660     return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1661   }
1662 }