1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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 /// \file
11 /// \brief Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Sema/SemaInternal.h"
16 #include "TypeLocBuilder.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
42 using namespace sema;
43 
44 /// \brief Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49                                               SourceLocation NameLoc,
50                                               IdentifierInfo &Name) {
51   NestedNameSpecifier *NNS = SS.getScopeRep();
52 
53   // Convert the nested-name-specifier into a type.
54   QualType Type;
55   switch (NNS->getKind()) {
56   case NestedNameSpecifier::TypeSpec:
57   case NestedNameSpecifier::TypeSpecWithTemplate:
58     Type = QualType(NNS->getAsType(), 0);
59     break;
60 
61   case NestedNameSpecifier::Identifier:
62     // Strip off the last layer of the nested-name-specifier and build a
63     // typename type for it.
64     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66                                         NNS->getAsIdentifier());
67     break;
68 
69   case NestedNameSpecifier::Global:
70   case NestedNameSpecifier::Super:
71   case NestedNameSpecifier::Namespace:
72   case NestedNameSpecifier::NamespaceAlias:
73     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74   }
75 
76   // This reference to the type is located entirely at the location of the
77   // final identifier in the qualified-id.
78   return CreateParsedType(Type,
79                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
80 }
81 
82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
83                                    IdentifierInfo &II,
84                                    SourceLocation NameLoc,
85                                    Scope *S, CXXScopeSpec &SS,
86                                    ParsedType ObjectTypePtr,
87                                    bool EnteringContext) {
88   // Determine where to perform name lookup.
89 
90   // FIXME: This area of the standard is very messy, and the current
91   // wording is rather unclear about which scopes we search for the
92   // destructor name; see core issues 399 and 555. Issue 399 in
93   // particular shows where the current description of destructor name
94   // lookup is completely out of line with existing practice, e.g.,
95   // this appears to be ill-formed:
96   //
97   //   namespace N {
98   //     template <typename T> struct S {
99   //       ~S();
100   //     };
101   //   }
102   //
103   //   void f(N::S<int>* s) {
104   //     s->N::S<int>::~S();
105   //   }
106   //
107   // See also PR6358 and PR6359.
108   // For this reason, we're currently only doing the C++03 version of this
109   // code; the C++0x version has to wait until we get a proper spec.
110   QualType SearchType;
111   DeclContext *LookupCtx = nullptr;
112   bool isDependent = false;
113   bool LookInScope = false;
114 
115   // If we have an object type, it's because we are in a
116   // pseudo-destructor-expression or a member access expression, and
117   // we know what type we're looking for.
118   if (ObjectTypePtr)
119     SearchType = GetTypeFromParser(ObjectTypePtr);
120 
121   if (SS.isSet()) {
122     NestedNameSpecifier *NNS = SS.getScopeRep();
123 
124     bool AlreadySearched = false;
125     bool LookAtPrefix = true;
126     // C++11 [basic.lookup.qual]p6:
127     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
128     //   the type-names are looked up as types in the scope designated by the
129     //   nested-name-specifier. Similarly, in a qualified-id of the form:
130     //
131     //     nested-name-specifier[opt] class-name :: ~ class-name
132     //
133     //   the second class-name is looked up in the same scope as the first.
134     //
135     // Here, we determine whether the code below is permitted to look at the
136     // prefix of the nested-name-specifier.
137     DeclContext *DC = computeDeclContext(SS, EnteringContext);
138     if (DC && DC->isFileContext()) {
139       AlreadySearched = true;
140       LookupCtx = DC;
141       isDependent = false;
142     } else if (DC && isa<CXXRecordDecl>(DC)) {
143       LookAtPrefix = false;
144       LookInScope = true;
145     }
146 
147     // The second case from the C++03 rules quoted further above.
148     NestedNameSpecifier *Prefix = nullptr;
149     if (AlreadySearched) {
150       // Nothing left to do.
151     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
152       CXXScopeSpec PrefixSS;
153       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
154       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
155       isDependent = isDependentScopeSpecifier(PrefixSS);
156     } else if (ObjectTypePtr) {
157       LookupCtx = computeDeclContext(SearchType);
158       isDependent = SearchType->isDependentType();
159     } else {
160       LookupCtx = computeDeclContext(SS, EnteringContext);
161       isDependent = LookupCtx && LookupCtx->isDependentContext();
162     }
163   } else if (ObjectTypePtr) {
164     // C++ [basic.lookup.classref]p3:
165     //   If the unqualified-id is ~type-name, the type-name is looked up
166     //   in the context of the entire postfix-expression. If the type T
167     //   of the object expression is of a class type C, the type-name is
168     //   also looked up in the scope of class C. At least one of the
169     //   lookups shall find a name that refers to (possibly
170     //   cv-qualified) T.
171     LookupCtx = computeDeclContext(SearchType);
172     isDependent = SearchType->isDependentType();
173     assert((isDependent || !SearchType->isIncompleteType()) &&
174            "Caller should have completed object type");
175 
176     LookInScope = true;
177   } else {
178     // Perform lookup into the current scope (only).
179     LookInScope = true;
180   }
181 
182   TypeDecl *NonMatchingTypeDecl = nullptr;
183   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
184   for (unsigned Step = 0; Step != 2; ++Step) {
185     // Look for the name first in the computed lookup context (if we
186     // have one) and, if that fails to find a match, in the scope (if
187     // we're allowed to look there).
188     Found.clear();
189     if (Step == 0 && LookupCtx)
190       LookupQualifiedName(Found, LookupCtx);
191     else if (Step == 1 && LookInScope && S)
192       LookupName(Found, S);
193     else
194       continue;
195 
196     // FIXME: Should we be suppressing ambiguities here?
197     if (Found.isAmbiguous())
198       return ParsedType();
199 
200     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
201       QualType T = Context.getTypeDeclType(Type);
202 
203       if (SearchType.isNull() || SearchType->isDependentType() ||
204           Context.hasSameUnqualifiedType(T, SearchType)) {
205         // We found our type!
206 
207         return CreateParsedType(T,
208                                 Context.getTrivialTypeSourceInfo(T, NameLoc));
209       }
210 
211       if (!SearchType.isNull())
212         NonMatchingTypeDecl = Type;
213     }
214 
215     // If the name that we found is a class template name, and it is
216     // the same name as the template name in the last part of the
217     // nested-name-specifier (if present) or the object type, then
218     // this is the destructor for that class.
219     // FIXME: This is a workaround until we get real drafting for core
220     // issue 399, for which there isn't even an obvious direction.
221     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
222       QualType MemberOfType;
223       if (SS.isSet()) {
224         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
225           // Figure out the type of the context, if it has one.
226           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
227             MemberOfType = Context.getTypeDeclType(Record);
228         }
229       }
230       if (MemberOfType.isNull())
231         MemberOfType = SearchType;
232 
233       if (MemberOfType.isNull())
234         continue;
235 
236       // We're referring into a class template specialization. If the
237       // class template we found is the same as the template being
238       // specialized, we found what we are looking for.
239       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
240         if (ClassTemplateSpecializationDecl *Spec
241               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
242           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
243                 Template->getCanonicalDecl())
244             return CreateParsedType(
245                 MemberOfType,
246                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
247         }
248 
249         continue;
250       }
251 
252       // We're referring to an unresolved class template
253       // specialization. Determine whether we class template we found
254       // is the same as the template being specialized or, if we don't
255       // know which template is being specialized, that it at least
256       // has the same name.
257       if (const TemplateSpecializationType *SpecType
258             = MemberOfType->getAs<TemplateSpecializationType>()) {
259         TemplateName SpecName = SpecType->getTemplateName();
260 
261         // The class template we found is the same template being
262         // specialized.
263         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
264           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
265             return CreateParsedType(
266                 MemberOfType,
267                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
268 
269           continue;
270         }
271 
272         // The class template we found has the same name as the
273         // (dependent) template name being specialized.
274         if (DependentTemplateName *DepTemplate
275                                     = SpecName.getAsDependentTemplateName()) {
276           if (DepTemplate->isIdentifier() &&
277               DepTemplate->getIdentifier() == Template->getIdentifier())
278             return CreateParsedType(
279                 MemberOfType,
280                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
281 
282           continue;
283         }
284       }
285     }
286   }
287 
288   if (isDependent) {
289     // We didn't find our type, but that's okay: it's dependent
290     // anyway.
291 
292     // FIXME: What if we have no nested-name-specifier?
293     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
294                                    SS.getWithLocInContext(Context),
295                                    II, NameLoc);
296     return ParsedType::make(T);
297   }
298 
299   if (NonMatchingTypeDecl) {
300     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
301     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
302       << T << SearchType;
303     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
304       << T;
305   } else if (ObjectTypePtr)
306     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
307       << &II;
308   else {
309     SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
310                                           diag::err_destructor_class_name);
311     if (S) {
312       const DeclContext *Ctx = S->getEntity();
313       if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
314         DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
315                                                  Class->getNameAsString());
316     }
317   }
318 
319   return ParsedType();
320 }
321 
322 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
323     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
324       return ParsedType();
325     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
326            && "only get destructor types from declspecs");
327     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
328     QualType SearchType = GetTypeFromParser(ObjectType);
329     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
330       return ParsedType::make(T);
331     }
332 
333     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
334       << T << SearchType;
335     return ParsedType();
336 }
337 
338 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
339                                   const UnqualifiedId &Name) {
340   assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
341 
342   if (!SS.isValid())
343     return false;
344 
345   switch (SS.getScopeRep()->getKind()) {
346   case NestedNameSpecifier::Identifier:
347   case NestedNameSpecifier::TypeSpec:
348   case NestedNameSpecifier::TypeSpecWithTemplate:
349     // Per C++11 [over.literal]p2, literal operators can only be declared at
350     // namespace scope. Therefore, this unqualified-id cannot name anything.
351     // Reject it early, because we have no AST representation for this in the
352     // case where the scope is dependent.
353     Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
354       << SS.getScopeRep();
355     return true;
356 
357   case NestedNameSpecifier::Global:
358   case NestedNameSpecifier::Super:
359   case NestedNameSpecifier::Namespace:
360   case NestedNameSpecifier::NamespaceAlias:
361     return false;
362   }
363 
364   llvm_unreachable("unknown nested name specifier kind");
365 }
366 
367 /// \brief Build a C++ typeid expression with a type operand.
368 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
369                                 SourceLocation TypeidLoc,
370                                 TypeSourceInfo *Operand,
371                                 SourceLocation RParenLoc) {
372   // C++ [expr.typeid]p4:
373   //   The top-level cv-qualifiers of the lvalue expression or the type-id
374   //   that is the operand of typeid are always ignored.
375   //   If the type of the type-id is a class type or a reference to a class
376   //   type, the class shall be completely-defined.
377   Qualifiers Quals;
378   QualType T
379     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
380                                       Quals);
381   if (T->getAs<RecordType>() &&
382       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
383     return ExprError();
384 
385   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
386                                      SourceRange(TypeidLoc, RParenLoc));
387 }
388 
389 /// \brief Build a C++ typeid expression with an expression operand.
390 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
391                                 SourceLocation TypeidLoc,
392                                 Expr *E,
393                                 SourceLocation RParenLoc) {
394   if (E && !E->isTypeDependent()) {
395     if (E->getType()->isPlaceholderType()) {
396       ExprResult result = CheckPlaceholderExpr(E);
397       if (result.isInvalid()) return ExprError();
398       E = result.get();
399     }
400 
401     QualType T = E->getType();
402     if (const RecordType *RecordT = T->getAs<RecordType>()) {
403       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
404       // C++ [expr.typeid]p3:
405       //   [...] If the type of the expression is a class type, the class
406       //   shall be completely-defined.
407       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
408         return ExprError();
409 
410       // C++ [expr.typeid]p3:
411       //   When typeid is applied to an expression other than an glvalue of a
412       //   polymorphic class type [...] [the] expression is an unevaluated
413       //   operand. [...]
414       if (RecordD->isPolymorphic() && E->isGLValue()) {
415         // The subexpression is potentially evaluated; switch the context
416         // and recheck the subexpression.
417         ExprResult Result = TransformToPotentiallyEvaluated(E);
418         if (Result.isInvalid()) return ExprError();
419         E = Result.get();
420 
421         // We require a vtable to query the type at run time.
422         MarkVTableUsed(TypeidLoc, RecordD);
423       }
424     }
425 
426     // C++ [expr.typeid]p4:
427     //   [...] If the type of the type-id is a reference to a possibly
428     //   cv-qualified type, the result of the typeid expression refers to a
429     //   std::type_info object representing the cv-unqualified referenced
430     //   type.
431     Qualifiers Quals;
432     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
433     if (!Context.hasSameType(T, UnqualT)) {
434       T = UnqualT;
435       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
436     }
437   }
438 
439   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
440                                      SourceRange(TypeidLoc, RParenLoc));
441 }
442 
443 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
444 ExprResult
445 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
446                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
447   // Find the std::type_info type.
448   if (!getStdNamespace())
449     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
450 
451   if (!CXXTypeInfoDecl) {
452     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
453     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
454     LookupQualifiedName(R, getStdNamespace());
455     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
456     // Microsoft's typeinfo doesn't have type_info in std but in the global
457     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
458     if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
459       LookupQualifiedName(R, Context.getTranslationUnitDecl());
460       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
461     }
462     if (!CXXTypeInfoDecl)
463       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
464   }
465 
466   if (!getLangOpts().RTTI) {
467     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
468   }
469 
470   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
471 
472   if (isType) {
473     // The operand is a type; handle it as such.
474     TypeSourceInfo *TInfo = nullptr;
475     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
476                                    &TInfo);
477     if (T.isNull())
478       return ExprError();
479 
480     if (!TInfo)
481       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
482 
483     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
484   }
485 
486   // The operand is an expression.
487   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
488 }
489 
490 /// \brief Build a Microsoft __uuidof expression with a type operand.
491 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
492                                 SourceLocation TypeidLoc,
493                                 TypeSourceInfo *Operand,
494                                 SourceLocation RParenLoc) {
495   if (!Operand->getType()->isDependentType()) {
496     bool HasMultipleGUIDs = false;
497     if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
498                                           &HasMultipleGUIDs)) {
499       if (HasMultipleGUIDs)
500         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
501       else
502         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
503     }
504   }
505 
506   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
507                                      SourceRange(TypeidLoc, RParenLoc));
508 }
509 
510 /// \brief Build a Microsoft __uuidof expression with an expression operand.
511 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
512                                 SourceLocation TypeidLoc,
513                                 Expr *E,
514                                 SourceLocation RParenLoc) {
515   if (!E->getType()->isDependentType()) {
516     bool HasMultipleGUIDs = false;
517     if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
518         !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
519       if (HasMultipleGUIDs)
520         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
521       else
522         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
523     }
524   }
525 
526   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
527                                      SourceRange(TypeidLoc, RParenLoc));
528 }
529 
530 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
531 ExprResult
532 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
533                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
534   // If MSVCGuidDecl has not been cached, do the lookup.
535   if (!MSVCGuidDecl) {
536     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
537     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
538     LookupQualifiedName(R, Context.getTranslationUnitDecl());
539     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
540     if (!MSVCGuidDecl)
541       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
542   }
543 
544   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
545 
546   if (isType) {
547     // The operand is a type; handle it as such.
548     TypeSourceInfo *TInfo = nullptr;
549     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
550                                    &TInfo);
551     if (T.isNull())
552       return ExprError();
553 
554     if (!TInfo)
555       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
556 
557     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
558   }
559 
560   // The operand is an expression.
561   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
562 }
563 
564 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
565 ExprResult
566 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
567   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
568          "Unknown C++ Boolean value!");
569   return new (Context)
570       CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
571 }
572 
573 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
574 ExprResult
575 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
576   return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
577 }
578 
579 /// ActOnCXXThrow - Parse throw expressions.
580 ExprResult
581 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
582   bool IsThrownVarInScope = false;
583   if (Ex) {
584     // C++0x [class.copymove]p31:
585     //   When certain criteria are met, an implementation is allowed to omit the
586     //   copy/move construction of a class object [...]
587     //
588     //     - in a throw-expression, when the operand is the name of a
589     //       non-volatile automatic object (other than a function or catch-
590     //       clause parameter) whose scope does not extend beyond the end of the
591     //       innermost enclosing try-block (if there is one), the copy/move
592     //       operation from the operand to the exception object (15.1) can be
593     //       omitted by constructing the automatic object directly into the
594     //       exception object
595     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
596       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
597         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
598           for( ; S; S = S->getParent()) {
599             if (S->isDeclScope(Var)) {
600               IsThrownVarInScope = true;
601               break;
602             }
603 
604             if (S->getFlags() &
605                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
606                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
607                  Scope::TryScope))
608               break;
609           }
610         }
611       }
612   }
613 
614   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
615 }
616 
617 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
618                                bool IsThrownVarInScope) {
619   // Don't report an error if 'throw' is used in system headers.
620   if (!getLangOpts().CXXExceptions &&
621       !getSourceManager().isInSystemHeader(OpLoc))
622     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
623 
624   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
625     Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
626 
627   if (Ex && !Ex->isTypeDependent()) {
628     ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
629     if (ExRes.isInvalid())
630       return ExprError();
631     Ex = ExRes.get();
632   }
633 
634   return new (Context)
635       CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
636 }
637 
638 /// CheckCXXThrowOperand - Validate the operand of a throw.
639 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
640                                       bool IsThrownVarInScope) {
641   // C++ [except.throw]p3:
642   //   A throw-expression initializes a temporary object, called the exception
643   //   object, the type of which is determined by removing any top-level
644   //   cv-qualifiers from the static type of the operand of throw and adjusting
645   //   the type from "array of T" or "function returning T" to "pointer to T"
646   //   or "pointer to function returning T", [...]
647   if (E->getType().hasQualifiers())
648     E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
649                           E->getValueKind()).get();
650 
651   ExprResult Res = DefaultFunctionArrayConversion(E);
652   if (Res.isInvalid())
653     return ExprError();
654   E = Res.get();
655 
656   //   If the type of the exception would be an incomplete type or a pointer
657   //   to an incomplete type other than (cv) void the program is ill-formed.
658   QualType Ty = E->getType();
659   bool isPointer = false;
660   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
661     Ty = Ptr->getPointeeType();
662     isPointer = true;
663   }
664   if (!isPointer || !Ty->isVoidType()) {
665     if (RequireCompleteType(ThrowLoc, Ty,
666                             isPointer? diag::err_throw_incomplete_ptr
667                                      : diag::err_throw_incomplete,
668                             E->getSourceRange()))
669       return ExprError();
670 
671     if (RequireNonAbstractType(ThrowLoc, E->getType(),
672                                diag::err_throw_abstract_type, E))
673       return ExprError();
674   }
675 
676   // Initialize the exception result.  This implicitly weeds out
677   // abstract types or types with inaccessible copy constructors.
678 
679   // C++0x [class.copymove]p31:
680   //   When certain criteria are met, an implementation is allowed to omit the
681   //   copy/move construction of a class object [...]
682   //
683   //     - in a throw-expression, when the operand is the name of a
684   //       non-volatile automatic object (other than a function or catch-clause
685   //       parameter) whose scope does not extend beyond the end of the
686   //       innermost enclosing try-block (if there is one), the copy/move
687   //       operation from the operand to the exception object (15.1) can be
688   //       omitted by constructing the automatic object directly into the
689   //       exception object
690   const VarDecl *NRVOVariable = nullptr;
691   if (IsThrownVarInScope)
692     NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
693 
694   InitializedEntity Entity =
695       InitializedEntity::InitializeException(ThrowLoc, E->getType(),
696                                              /*NRVO=*/NRVOVariable != nullptr);
697   Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
698                                         QualType(), E,
699                                         IsThrownVarInScope);
700   if (Res.isInvalid())
701     return ExprError();
702   E = Res.get();
703 
704   // If the exception has class type, we need additional handling.
705   const RecordType *RecordTy = Ty->getAs<RecordType>();
706   if (!RecordTy)
707     return E;
708   CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
709 
710   // If we are throwing a polymorphic class type or pointer thereof,
711   // exception handling will make use of the vtable.
712   MarkVTableUsed(ThrowLoc, RD);
713 
714   // If a pointer is thrown, the referenced object will not be destroyed.
715   if (isPointer)
716     return E;
717 
718   // If the class has a destructor, we must be able to call it.
719   if (RD->hasIrrelevantDestructor())
720     return E;
721 
722   CXXDestructorDecl *Destructor = LookupDestructor(RD);
723   if (!Destructor)
724     return E;
725 
726   MarkFunctionReferenced(E->getExprLoc(), Destructor);
727   CheckDestructorAccess(E->getExprLoc(), Destructor,
728                         PDiag(diag::err_access_dtor_exception) << Ty);
729   if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
730     return ExprError();
731   return E;
732 }
733 
734 QualType Sema::getCurrentThisType() {
735   DeclContext *DC = getFunctionLevelDeclContext();
736   QualType ThisTy = CXXThisTypeOverride;
737   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
738     if (method && method->isInstance())
739       ThisTy = method->getThisType(Context);
740   }
741   if (ThisTy.isNull()) {
742     if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
743         CurContext->getParent()->getParent()->isRecord()) {
744       // This is a generic lambda call operator that is being instantiated
745       // within a default initializer - so use the enclosing class as 'this'.
746       // There is no enclosing member function to retrieve the 'this' pointer
747       // from.
748       QualType ClassTy = Context.getTypeDeclType(
749           cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
750       // There are no cv-qualifiers for 'this' within default initializers,
751       // per [expr.prim.general]p4.
752       return Context.getPointerType(ClassTy);
753     }
754   }
755   return ThisTy;
756 }
757 
758 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
759                                          Decl *ContextDecl,
760                                          unsigned CXXThisTypeQuals,
761                                          bool Enabled)
762   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
763 {
764   if (!Enabled || !ContextDecl)
765     return;
766 
767   CXXRecordDecl *Record = nullptr;
768   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
769     Record = Template->getTemplatedDecl();
770   else
771     Record = cast<CXXRecordDecl>(ContextDecl);
772 
773   S.CXXThisTypeOverride
774     = S.Context.getPointerType(
775         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
776 
777   this->Enabled = true;
778 }
779 
780 
781 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
782   if (Enabled) {
783     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
784   }
785 }
786 
787 static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
788                          QualType ThisTy, SourceLocation Loc) {
789   FieldDecl *Field
790     = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, ThisTy,
791                         Context.getTrivialTypeSourceInfo(ThisTy, Loc),
792                         nullptr, false, ICIS_NoInit);
793   Field->setImplicit(true);
794   Field->setAccess(AS_private);
795   RD->addDecl(Field);
796   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
797 }
798 
799 bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
800     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
801   // We don't need to capture this in an unevaluated context.
802   if (isUnevaluatedContext() && !Explicit)
803     return true;
804 
805   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
806     *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
807  // Otherwise, check that we can capture 'this'.
808   unsigned NumClosures = 0;
809   for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
810     if (CapturingScopeInfo *CSI =
811             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
812       if (CSI->CXXThisCaptureIndex != 0) {
813         // 'this' is already being captured; there isn't anything more to do.
814         break;
815       }
816       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
817       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
818         // This context can't implicitly capture 'this'; fail out.
819         if (BuildAndDiagnose)
820           Diag(Loc, diag::err_this_capture) << Explicit;
821         return true;
822       }
823       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
824           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
825           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
826           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
827           Explicit) {
828         // This closure can capture 'this'; continue looking upwards.
829         NumClosures++;
830         Explicit = false;
831         continue;
832       }
833       // This context can't implicitly capture 'this'; fail out.
834       if (BuildAndDiagnose)
835         Diag(Loc, diag::err_this_capture) << Explicit;
836       return true;
837     }
838     break;
839   }
840   if (!BuildAndDiagnose) return false;
841   // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
842   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
843   // contexts.
844   for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
845       --idx, --NumClosures) {
846     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
847     Expr *ThisExpr = nullptr;
848     QualType ThisTy = getCurrentThisType();
849     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
850       // For lambda expressions, build a field and an initializing expression.
851       ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
852     else if (CapturedRegionScopeInfo *RSI
853         = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
854       ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
855 
856     bool isNested = NumClosures > 1;
857     CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
858   }
859   return false;
860 }
861 
862 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
863   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
864   /// is a non-lvalue expression whose value is the address of the object for
865   /// which the function is called.
866 
867   QualType ThisTy = getCurrentThisType();
868   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
869 
870   CheckCXXThisCapture(Loc);
871   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
872 }
873 
874 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
875   // If we're outside the body of a member function, then we'll have a specified
876   // type for 'this'.
877   if (CXXThisTypeOverride.isNull())
878     return false;
879 
880   // Determine whether we're looking into a class that's currently being
881   // defined.
882   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
883   return Class && Class->isBeingDefined();
884 }
885 
886 ExprResult
887 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
888                                 SourceLocation LParenLoc,
889                                 MultiExprArg exprs,
890                                 SourceLocation RParenLoc) {
891   if (!TypeRep)
892     return ExprError();
893 
894   TypeSourceInfo *TInfo;
895   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
896   if (!TInfo)
897     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
898 
899   return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
900 }
901 
902 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
903 /// Can be interpreted either as function-style casting ("int(x)")
904 /// or class type construction ("ClassType(x,y,z)")
905 /// or creation of a value-initialized type ("int()").
906 ExprResult
907 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
908                                 SourceLocation LParenLoc,
909                                 MultiExprArg Exprs,
910                                 SourceLocation RParenLoc) {
911   QualType Ty = TInfo->getType();
912   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
913 
914   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
915     return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
916                                               RParenLoc);
917   }
918 
919   bool ListInitialization = LParenLoc.isInvalid();
920   assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
921          && "List initialization must have initializer list as expression.");
922   SourceRange FullRange = SourceRange(TyBeginLoc,
923       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
924 
925   // C++ [expr.type.conv]p1:
926   // If the expression list is a single expression, the type conversion
927   // expression is equivalent (in definedness, and if defined in meaning) to the
928   // corresponding cast expression.
929   if (Exprs.size() == 1 && !ListInitialization) {
930     Expr *Arg = Exprs[0];
931     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
932   }
933 
934   QualType ElemTy = Ty;
935   if (Ty->isArrayType()) {
936     if (!ListInitialization)
937       return ExprError(Diag(TyBeginLoc,
938                             diag::err_value_init_for_array_type) << FullRange);
939     ElemTy = Context.getBaseElementType(Ty);
940   }
941 
942   if (!Ty->isVoidType() &&
943       RequireCompleteType(TyBeginLoc, ElemTy,
944                           diag::err_invalid_incomplete_type_use, FullRange))
945     return ExprError();
946 
947   if (RequireNonAbstractType(TyBeginLoc, Ty,
948                              diag::err_allocation_of_abstract_type))
949     return ExprError();
950 
951   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
952   InitializationKind Kind =
953       Exprs.size() ? ListInitialization
954       ? InitializationKind::CreateDirectList(TyBeginLoc)
955       : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
956       : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
957   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
958   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
959 
960   if (Result.isInvalid() || !ListInitialization)
961     return Result;
962 
963   Expr *Inner = Result.get();
964   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
965     Inner = BTE->getSubExpr();
966   if (isa<InitListExpr>(Inner)) {
967     // If the list-initialization doesn't involve a constructor call, we'll get
968     // the initializer-list (with corrected type) back, but that's not what we
969     // want, since it will be treated as an initializer list in further
970     // processing. Explicitly insert a cast here.
971     QualType ResultType = Result.get()->getType();
972     Result = CXXFunctionalCastExpr::Create(
973         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
974         CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
975   }
976 
977   // FIXME: Improve AST representation?
978   return Result;
979 }
980 
981 /// doesUsualArrayDeleteWantSize - Answers whether the usual
982 /// operator delete[] for the given type has a size_t parameter.
983 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
984                                          QualType allocType) {
985   const RecordType *record =
986     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
987   if (!record) return false;
988 
989   // Try to find an operator delete[] in class scope.
990 
991   DeclarationName deleteName =
992     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
993   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
994   S.LookupQualifiedName(ops, record->getDecl());
995 
996   // We're just doing this for information.
997   ops.suppressDiagnostics();
998 
999   // Very likely: there's no operator delete[].
1000   if (ops.empty()) return false;
1001 
1002   // If it's ambiguous, it should be illegal to call operator delete[]
1003   // on this thing, so it doesn't matter if we allocate extra space or not.
1004   if (ops.isAmbiguous()) return false;
1005 
1006   LookupResult::Filter filter = ops.makeFilter();
1007   while (filter.hasNext()) {
1008     NamedDecl *del = filter.next()->getUnderlyingDecl();
1009 
1010     // C++0x [basic.stc.dynamic.deallocation]p2:
1011     //   A template instance is never a usual deallocation function,
1012     //   regardless of its signature.
1013     if (isa<FunctionTemplateDecl>(del)) {
1014       filter.erase();
1015       continue;
1016     }
1017 
1018     // C++0x [basic.stc.dynamic.deallocation]p2:
1019     //   If class T does not declare [an operator delete[] with one
1020     //   parameter] but does declare a member deallocation function
1021     //   named operator delete[] with exactly two parameters, the
1022     //   second of which has type std::size_t, then this function
1023     //   is a usual deallocation function.
1024     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1025       filter.erase();
1026       continue;
1027     }
1028   }
1029   filter.done();
1030 
1031   if (!ops.isSingleResult()) return false;
1032 
1033   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1034   return (del->getNumParams() == 2);
1035 }
1036 
1037 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1038 ///
1039 /// E.g.:
1040 /// @code new (memory) int[size][4] @endcode
1041 /// or
1042 /// @code ::new Foo(23, "hello") @endcode
1043 ///
1044 /// \param StartLoc The first location of the expression.
1045 /// \param UseGlobal True if 'new' was prefixed with '::'.
1046 /// \param PlacementLParen Opening paren of the placement arguments.
1047 /// \param PlacementArgs Placement new arguments.
1048 /// \param PlacementRParen Closing paren of the placement arguments.
1049 /// \param TypeIdParens If the type is in parens, the source range.
1050 /// \param D The type to be allocated, as well as array dimensions.
1051 /// \param Initializer The initializing expression or initializer-list, or null
1052 ///   if there is none.
1053 ExprResult
1054 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1055                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1056                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
1057                   Declarator &D, Expr *Initializer) {
1058   bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1059 
1060   Expr *ArraySize = nullptr;
1061   // If the specified type is an array, unwrap it and save the expression.
1062   if (D.getNumTypeObjects() > 0 &&
1063       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1064      DeclaratorChunk &Chunk = D.getTypeObject(0);
1065     if (TypeContainsAuto)
1066       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1067         << D.getSourceRange());
1068     if (Chunk.Arr.hasStatic)
1069       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1070         << D.getSourceRange());
1071     if (!Chunk.Arr.NumElts)
1072       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1073         << D.getSourceRange());
1074 
1075     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1076     D.DropFirstTypeObject();
1077   }
1078 
1079   // Every dimension shall be of constant size.
1080   if (ArraySize) {
1081     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1082       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1083         break;
1084 
1085       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1086       if (Expr *NumElts = (Expr *)Array.NumElts) {
1087         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1088           if (getLangOpts().CPlusPlus14) {
1089 	    // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1090 	    //   shall be a converted constant expression (5.19) of type std::size_t
1091 	    //   and shall evaluate to a strictly positive value.
1092             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1093             assert(IntWidth && "Builtin type of size 0?");
1094             llvm::APSInt Value(IntWidth);
1095             Array.NumElts
1096              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1097                                                 CCEK_NewExpr)
1098                  .get();
1099           } else {
1100             Array.NumElts
1101               = VerifyIntegerConstantExpression(NumElts, nullptr,
1102                                                 diag::err_new_array_nonconst)
1103                   .get();
1104           }
1105           if (!Array.NumElts)
1106             return ExprError();
1107         }
1108       }
1109     }
1110   }
1111 
1112   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1113   QualType AllocType = TInfo->getType();
1114   if (D.isInvalidType())
1115     return ExprError();
1116 
1117   SourceRange DirectInitRange;
1118   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1119     DirectInitRange = List->getSourceRange();
1120 
1121   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1122                      PlacementLParen,
1123                      PlacementArgs,
1124                      PlacementRParen,
1125                      TypeIdParens,
1126                      AllocType,
1127                      TInfo,
1128                      ArraySize,
1129                      DirectInitRange,
1130                      Initializer,
1131                      TypeContainsAuto);
1132 }
1133 
1134 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1135                                        Expr *Init) {
1136   if (!Init)
1137     return true;
1138   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1139     return PLE->getNumExprs() == 0;
1140   if (isa<ImplicitValueInitExpr>(Init))
1141     return true;
1142   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1143     return !CCE->isListInitialization() &&
1144            CCE->getConstructor()->isDefaultConstructor();
1145   else if (Style == CXXNewExpr::ListInit) {
1146     assert(isa<InitListExpr>(Init) &&
1147            "Shouldn't create list CXXConstructExprs for arrays.");
1148     return true;
1149   }
1150   return false;
1151 }
1152 
1153 ExprResult
1154 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1155                   SourceLocation PlacementLParen,
1156                   MultiExprArg PlacementArgs,
1157                   SourceLocation PlacementRParen,
1158                   SourceRange TypeIdParens,
1159                   QualType AllocType,
1160                   TypeSourceInfo *AllocTypeInfo,
1161                   Expr *ArraySize,
1162                   SourceRange DirectInitRange,
1163                   Expr *Initializer,
1164                   bool TypeMayContainAuto) {
1165   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1166   SourceLocation StartLoc = Range.getBegin();
1167 
1168   CXXNewExpr::InitializationStyle initStyle;
1169   if (DirectInitRange.isValid()) {
1170     assert(Initializer && "Have parens but no initializer.");
1171     initStyle = CXXNewExpr::CallInit;
1172   } else if (Initializer && isa<InitListExpr>(Initializer))
1173     initStyle = CXXNewExpr::ListInit;
1174   else {
1175     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1176             isa<CXXConstructExpr>(Initializer)) &&
1177            "Initializer expression that cannot have been implicitly created.");
1178     initStyle = CXXNewExpr::NoInit;
1179   }
1180 
1181   Expr **Inits = &Initializer;
1182   unsigned NumInits = Initializer ? 1 : 0;
1183   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1184     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1185     Inits = List->getExprs();
1186     NumInits = List->getNumExprs();
1187   }
1188 
1189   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1190   if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1191     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1192       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1193                        << AllocType << TypeRange);
1194     if (initStyle == CXXNewExpr::ListInit ||
1195         (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1196       return ExprError(Diag(Inits[0]->getLocStart(),
1197                             diag::err_auto_new_list_init)
1198                        << AllocType << TypeRange);
1199     if (NumInits > 1) {
1200       Expr *FirstBad = Inits[1];
1201       return ExprError(Diag(FirstBad->getLocStart(),
1202                             diag::err_auto_new_ctor_multiple_expressions)
1203                        << AllocType << TypeRange);
1204     }
1205     Expr *Deduce = Inits[0];
1206     QualType DeducedType;
1207     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1208       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1209                        << AllocType << Deduce->getType()
1210                        << TypeRange << Deduce->getSourceRange());
1211     if (DeducedType.isNull())
1212       return ExprError();
1213     AllocType = DeducedType;
1214   }
1215 
1216   // Per C++0x [expr.new]p5, the type being constructed may be a
1217   // typedef of an array type.
1218   if (!ArraySize) {
1219     if (const ConstantArrayType *Array
1220                               = Context.getAsConstantArrayType(AllocType)) {
1221       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1222                                          Context.getSizeType(),
1223                                          TypeRange.getEnd());
1224       AllocType = Array->getElementType();
1225     }
1226   }
1227 
1228   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1229     return ExprError();
1230 
1231   if (initStyle == CXXNewExpr::ListInit &&
1232       isStdInitializerList(AllocType, nullptr)) {
1233     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1234          diag::warn_dangling_std_initializer_list)
1235         << /*at end of FE*/0 << Inits[0]->getSourceRange();
1236   }
1237 
1238   // In ARC, infer 'retaining' for the allocated
1239   if (getLangOpts().ObjCAutoRefCount &&
1240       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1241       AllocType->isObjCLifetimeType()) {
1242     AllocType = Context.getLifetimeQualifiedType(AllocType,
1243                                     AllocType->getObjCARCImplicitLifetime());
1244   }
1245 
1246   QualType ResultType = Context.getPointerType(AllocType);
1247 
1248   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1249     ExprResult result = CheckPlaceholderExpr(ArraySize);
1250     if (result.isInvalid()) return ExprError();
1251     ArraySize = result.get();
1252   }
1253   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1254   //   integral or enumeration type with a non-negative value."
1255   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1256   //   enumeration type, or a class type for which a single non-explicit
1257   //   conversion function to integral or unscoped enumeration type exists.
1258   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1259   //   std::size_t.
1260   if (ArraySize && !ArraySize->isTypeDependent()) {
1261     ExprResult ConvertedSize;
1262     if (getLangOpts().CPlusPlus14) {
1263       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1264 
1265       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1266 						AA_Converting);
1267 
1268       if (!ConvertedSize.isInvalid() &&
1269           ArraySize->getType()->getAs<RecordType>())
1270         // Diagnose the compatibility of this conversion.
1271         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1272           << ArraySize->getType() << 0 << "'size_t'";
1273     } else {
1274       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1275       protected:
1276         Expr *ArraySize;
1277 
1278       public:
1279         SizeConvertDiagnoser(Expr *ArraySize)
1280             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1281               ArraySize(ArraySize) {}
1282 
1283         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1284                                              QualType T) override {
1285           return S.Diag(Loc, diag::err_array_size_not_integral)
1286                    << S.getLangOpts().CPlusPlus11 << T;
1287         }
1288 
1289         SemaDiagnosticBuilder diagnoseIncomplete(
1290             Sema &S, SourceLocation Loc, QualType T) override {
1291           return S.Diag(Loc, diag::err_array_size_incomplete_type)
1292                    << T << ArraySize->getSourceRange();
1293         }
1294 
1295         SemaDiagnosticBuilder diagnoseExplicitConv(
1296             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1297           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1298         }
1299 
1300         SemaDiagnosticBuilder noteExplicitConv(
1301             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1302           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1303                    << ConvTy->isEnumeralType() << ConvTy;
1304         }
1305 
1306         SemaDiagnosticBuilder diagnoseAmbiguous(
1307             Sema &S, SourceLocation Loc, QualType T) override {
1308           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1309         }
1310 
1311         SemaDiagnosticBuilder noteAmbiguous(
1312             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1313           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1314                    << ConvTy->isEnumeralType() << ConvTy;
1315         }
1316 
1317         virtual SemaDiagnosticBuilder diagnoseConversion(
1318             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1319           return S.Diag(Loc,
1320                         S.getLangOpts().CPlusPlus11
1321                           ? diag::warn_cxx98_compat_array_size_conversion
1322                           : diag::ext_array_size_conversion)
1323                    << T << ConvTy->isEnumeralType() << ConvTy;
1324         }
1325       } SizeDiagnoser(ArraySize);
1326 
1327       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1328                                                           SizeDiagnoser);
1329     }
1330     if (ConvertedSize.isInvalid())
1331       return ExprError();
1332 
1333     ArraySize = ConvertedSize.get();
1334     QualType SizeType = ArraySize->getType();
1335 
1336     if (!SizeType->isIntegralOrUnscopedEnumerationType())
1337       return ExprError();
1338 
1339     // C++98 [expr.new]p7:
1340     //   The expression in a direct-new-declarator shall have integral type
1341     //   with a non-negative value.
1342     //
1343     // Let's see if this is a constant < 0. If so, we reject it out of
1344     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1345     // array type.
1346     //
1347     // Note: such a construct has well-defined semantics in C++11: it throws
1348     // std::bad_array_new_length.
1349     if (!ArraySize->isValueDependent()) {
1350       llvm::APSInt Value;
1351       // We've already performed any required implicit conversion to integer or
1352       // unscoped enumeration type.
1353       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1354         if (Value < llvm::APSInt(
1355                         llvm::APInt::getNullValue(Value.getBitWidth()),
1356                                  Value.isUnsigned())) {
1357           if (getLangOpts().CPlusPlus11)
1358             Diag(ArraySize->getLocStart(),
1359                  diag::warn_typecheck_negative_array_new_size)
1360               << ArraySize->getSourceRange();
1361           else
1362             return ExprError(Diag(ArraySize->getLocStart(),
1363                                   diag::err_typecheck_negative_array_size)
1364                              << ArraySize->getSourceRange());
1365         } else if (!AllocType->isDependentType()) {
1366           unsigned ActiveSizeBits =
1367             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1368           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1369             if (getLangOpts().CPlusPlus11)
1370               Diag(ArraySize->getLocStart(),
1371                    diag::warn_array_new_too_large)
1372                 << Value.toString(10)
1373                 << ArraySize->getSourceRange();
1374             else
1375               return ExprError(Diag(ArraySize->getLocStart(),
1376                                     diag::err_array_too_large)
1377                                << Value.toString(10)
1378                                << ArraySize->getSourceRange());
1379           }
1380         }
1381       } else if (TypeIdParens.isValid()) {
1382         // Can't have dynamic array size when the type-id is in parentheses.
1383         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1384           << ArraySize->getSourceRange()
1385           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1386           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1387 
1388         TypeIdParens = SourceRange();
1389       }
1390     }
1391 
1392     // Note that we do *not* convert the argument in any way.  It can
1393     // be signed, larger than size_t, whatever.
1394   }
1395 
1396   FunctionDecl *OperatorNew = nullptr;
1397   FunctionDecl *OperatorDelete = nullptr;
1398 
1399   if (!AllocType->isDependentType() &&
1400       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1401       FindAllocationFunctions(StartLoc,
1402                               SourceRange(PlacementLParen, PlacementRParen),
1403                               UseGlobal, AllocType, ArraySize, PlacementArgs,
1404                               OperatorNew, OperatorDelete))
1405     return ExprError();
1406 
1407   // If this is an array allocation, compute whether the usual array
1408   // deallocation function for the type has a size_t parameter.
1409   bool UsualArrayDeleteWantsSize = false;
1410   if (ArraySize && !AllocType->isDependentType())
1411     UsualArrayDeleteWantsSize
1412       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1413 
1414   SmallVector<Expr *, 8> AllPlaceArgs;
1415   if (OperatorNew) {
1416     const FunctionProtoType *Proto =
1417         OperatorNew->getType()->getAs<FunctionProtoType>();
1418     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1419                                                     : VariadicDoesNotApply;
1420 
1421     // We've already converted the placement args, just fill in any default
1422     // arguments. Skip the first parameter because we don't have a corresponding
1423     // argument.
1424     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1425                                PlacementArgs, AllPlaceArgs, CallType))
1426       return ExprError();
1427 
1428     if (!AllPlaceArgs.empty())
1429       PlacementArgs = AllPlaceArgs;
1430 
1431     // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1432     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1433 
1434     // FIXME: Missing call to CheckFunctionCall or equivalent
1435   }
1436 
1437   // Warn if the type is over-aligned and is being allocated by global operator
1438   // new.
1439   if (PlacementArgs.empty() && OperatorNew &&
1440       (OperatorNew->isImplicit() ||
1441        getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1442     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1443       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1444       if (Align > SuitableAlign)
1445         Diag(StartLoc, diag::warn_overaligned_type)
1446             << AllocType
1447             << unsigned(Align / Context.getCharWidth())
1448             << unsigned(SuitableAlign / Context.getCharWidth());
1449     }
1450   }
1451 
1452   QualType InitType = AllocType;
1453   // Array 'new' can't have any initializers except empty parentheses.
1454   // Initializer lists are also allowed, in C++11. Rely on the parser for the
1455   // dialect distinction.
1456   if (ResultType->isArrayType() || ArraySize) {
1457     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1458       SourceRange InitRange(Inits[0]->getLocStart(),
1459                             Inits[NumInits - 1]->getLocEnd());
1460       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1461       return ExprError();
1462     }
1463     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1464       // We do the initialization typechecking against the array type
1465       // corresponding to the number of initializers + 1 (to also check
1466       // default-initialization).
1467       unsigned NumElements = ILE->getNumInits() + 1;
1468       InitType = Context.getConstantArrayType(AllocType,
1469           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1470                                               ArrayType::Normal, 0);
1471     }
1472   }
1473 
1474   // If we can perform the initialization, and we've not already done so,
1475   // do it now.
1476   if (!AllocType->isDependentType() &&
1477       !Expr::hasAnyTypeDependentArguments(
1478           llvm::makeArrayRef(Inits, NumInits))) {
1479     // C++11 [expr.new]p15:
1480     //   A new-expression that creates an object of type T initializes that
1481     //   object as follows:
1482     InitializationKind Kind
1483     //     - If the new-initializer is omitted, the object is default-
1484     //       initialized (8.5); if no initialization is performed,
1485     //       the object has indeterminate value
1486       = initStyle == CXXNewExpr::NoInit
1487           ? InitializationKind::CreateDefault(TypeRange.getBegin())
1488     //     - Otherwise, the new-initializer is interpreted according to the
1489     //       initialization rules of 8.5 for direct-initialization.
1490           : initStyle == CXXNewExpr::ListInit
1491               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1492               : InitializationKind::CreateDirect(TypeRange.getBegin(),
1493                                                  DirectInitRange.getBegin(),
1494                                                  DirectInitRange.getEnd());
1495 
1496     InitializedEntity Entity
1497       = InitializedEntity::InitializeNew(StartLoc, InitType);
1498     InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1499     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1500                                           MultiExprArg(Inits, NumInits));
1501     if (FullInit.isInvalid())
1502       return ExprError();
1503 
1504     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1505     // we don't want the initialized object to be destructed.
1506     if (CXXBindTemporaryExpr *Binder =
1507             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1508       FullInit = Binder->getSubExpr();
1509 
1510     Initializer = FullInit.get();
1511   }
1512 
1513   // Mark the new and delete operators as referenced.
1514   if (OperatorNew) {
1515     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1516       return ExprError();
1517     MarkFunctionReferenced(StartLoc, OperatorNew);
1518   }
1519   if (OperatorDelete) {
1520     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1521       return ExprError();
1522     MarkFunctionReferenced(StartLoc, OperatorDelete);
1523   }
1524 
1525   // C++0x [expr.new]p17:
1526   //   If the new expression creates an array of objects of class type,
1527   //   access and ambiguity control are done for the destructor.
1528   QualType BaseAllocType = Context.getBaseElementType(AllocType);
1529   if (ArraySize && !BaseAllocType->isDependentType()) {
1530     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1531       if (CXXDestructorDecl *dtor = LookupDestructor(
1532               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1533         MarkFunctionReferenced(StartLoc, dtor);
1534         CheckDestructorAccess(StartLoc, dtor,
1535                               PDiag(diag::err_access_dtor)
1536                                 << BaseAllocType);
1537         if (DiagnoseUseOfDecl(dtor, StartLoc))
1538           return ExprError();
1539       }
1540     }
1541   }
1542 
1543   return new (Context)
1544       CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1545                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1546                  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1547                  Range, DirectInitRange);
1548 }
1549 
1550 /// \brief Checks that a type is suitable as the allocated type
1551 /// in a new-expression.
1552 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1553                               SourceRange R) {
1554   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1555   //   abstract class type or array thereof.
1556   if (AllocType->isFunctionType())
1557     return Diag(Loc, diag::err_bad_new_type)
1558       << AllocType << 0 << R;
1559   else if (AllocType->isReferenceType())
1560     return Diag(Loc, diag::err_bad_new_type)
1561       << AllocType << 1 << R;
1562   else if (!AllocType->isDependentType() &&
1563            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1564     return true;
1565   else if (RequireNonAbstractType(Loc, AllocType,
1566                                   diag::err_allocation_of_abstract_type))
1567     return true;
1568   else if (AllocType->isVariablyModifiedType())
1569     return Diag(Loc, diag::err_variably_modified_new_type)
1570              << AllocType;
1571   else if (unsigned AddressSpace = AllocType.getAddressSpace())
1572     return Diag(Loc, diag::err_address_space_qualified_new)
1573       << AllocType.getUnqualifiedType() << AddressSpace;
1574   else if (getLangOpts().ObjCAutoRefCount) {
1575     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1576       QualType BaseAllocType = Context.getBaseElementType(AT);
1577       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1578           BaseAllocType->isObjCLifetimeType())
1579         return Diag(Loc, diag::err_arc_new_array_without_ownership)
1580           << BaseAllocType;
1581     }
1582   }
1583 
1584   return false;
1585 }
1586 
1587 /// \brief Determine whether the given function is a non-placement
1588 /// deallocation function.
1589 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1590   if (FD->isInvalidDecl())
1591     return false;
1592 
1593   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1594     return Method->isUsualDeallocationFunction();
1595 
1596   if (FD->getOverloadedOperator() != OO_Delete &&
1597       FD->getOverloadedOperator() != OO_Array_Delete)
1598     return false;
1599 
1600   if (FD->getNumParams() == 1)
1601     return true;
1602 
1603   return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1604          S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1605                                           S.Context.getSizeType());
1606 }
1607 
1608 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1609 /// that are appropriate for the allocation.
1610 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1611                                    bool UseGlobal, QualType AllocType,
1612                                    bool IsArray, MultiExprArg PlaceArgs,
1613                                    FunctionDecl *&OperatorNew,
1614                                    FunctionDecl *&OperatorDelete) {
1615   // --- Choosing an allocation function ---
1616   // C++ 5.3.4p8 - 14 & 18
1617   // 1) If UseGlobal is true, only look in the global scope. Else, also look
1618   //   in the scope of the allocated class.
1619   // 2) If an array size is given, look for operator new[], else look for
1620   //   operator new.
1621   // 3) The first argument is always size_t. Append the arguments from the
1622   //   placement form.
1623 
1624   SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1625   // We don't care about the actual value of this argument.
1626   // FIXME: Should the Sema create the expression and embed it in the syntax
1627   // tree? Or should the consumer just recalculate the value?
1628   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1629                       Context.getTargetInfo().getPointerWidth(0)),
1630                       Context.getSizeType(),
1631                       SourceLocation());
1632   AllocArgs[0] = &Size;
1633   std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1634 
1635   // C++ [expr.new]p8:
1636   //   If the allocated type is a non-array type, the allocation
1637   //   function's name is operator new and the deallocation function's
1638   //   name is operator delete. If the allocated type is an array
1639   //   type, the allocation function's name is operator new[] and the
1640   //   deallocation function's name is operator delete[].
1641   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1642                                         IsArray ? OO_Array_New : OO_New);
1643   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1644                                         IsArray ? OO_Array_Delete : OO_Delete);
1645 
1646   QualType AllocElemType = Context.getBaseElementType(AllocType);
1647 
1648   if (AllocElemType->isRecordType() && !UseGlobal) {
1649     CXXRecordDecl *Record
1650       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1651     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1652                                /*AllowMissing=*/true, OperatorNew))
1653       return true;
1654   }
1655 
1656   if (!OperatorNew) {
1657     // Didn't find a member overload. Look for a global one.
1658     DeclareGlobalNewDelete();
1659     DeclContext *TUDecl = Context.getTranslationUnitDecl();
1660     bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
1661     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1662                                /*AllowMissing=*/FallbackEnabled, OperatorNew,
1663                                /*Diagnose=*/!FallbackEnabled)) {
1664       if (!FallbackEnabled)
1665         return true;
1666 
1667       // MSVC will fall back on trying to find a matching global operator new
1668       // if operator new[] cannot be found.  Also, MSVC will leak by not
1669       // generating a call to operator delete or operator delete[], but we
1670       // will not replicate that bug.
1671       NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1672       DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1673       if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1674                                /*AllowMissing=*/false, OperatorNew))
1675       return true;
1676     }
1677   }
1678 
1679   // We don't need an operator delete if we're running under
1680   // -fno-exceptions.
1681   if (!getLangOpts().Exceptions) {
1682     OperatorDelete = nullptr;
1683     return false;
1684   }
1685 
1686   // C++ [expr.new]p19:
1687   //
1688   //   If the new-expression begins with a unary :: operator, the
1689   //   deallocation function's name is looked up in the global
1690   //   scope. Otherwise, if the allocated type is a class type T or an
1691   //   array thereof, the deallocation function's name is looked up in
1692   //   the scope of T. If this lookup fails to find the name, or if
1693   //   the allocated type is not a class type or array thereof, the
1694   //   deallocation function's name is looked up in the global scope.
1695   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1696   if (AllocElemType->isRecordType() && !UseGlobal) {
1697     CXXRecordDecl *RD
1698       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1699     LookupQualifiedName(FoundDelete, RD);
1700   }
1701   if (FoundDelete.isAmbiguous())
1702     return true; // FIXME: clean up expressions?
1703 
1704   if (FoundDelete.empty()) {
1705     DeclareGlobalNewDelete();
1706     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1707   }
1708 
1709   FoundDelete.suppressDiagnostics();
1710 
1711   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1712 
1713   // Whether we're looking for a placement operator delete is dictated
1714   // by whether we selected a placement operator new, not by whether
1715   // we had explicit placement arguments.  This matters for things like
1716   //   struct A { void *operator new(size_t, int = 0); ... };
1717   //   A *a = new A()
1718   bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
1719 
1720   if (isPlacementNew) {
1721     // C++ [expr.new]p20:
1722     //   A declaration of a placement deallocation function matches the
1723     //   declaration of a placement allocation function if it has the
1724     //   same number of parameters and, after parameter transformations
1725     //   (8.3.5), all parameter types except the first are
1726     //   identical. [...]
1727     //
1728     // To perform this comparison, we compute the function type that
1729     // the deallocation function should have, and use that type both
1730     // for template argument deduction and for comparison purposes.
1731     //
1732     // FIXME: this comparison should ignore CC and the like.
1733     QualType ExpectedFunctionType;
1734     {
1735       const FunctionProtoType *Proto
1736         = OperatorNew->getType()->getAs<FunctionProtoType>();
1737 
1738       SmallVector<QualType, 4> ArgTypes;
1739       ArgTypes.push_back(Context.VoidPtrTy);
1740       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
1741         ArgTypes.push_back(Proto->getParamType(I));
1742 
1743       FunctionProtoType::ExtProtoInfo EPI;
1744       EPI.Variadic = Proto->isVariadic();
1745 
1746       ExpectedFunctionType
1747         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
1748     }
1749 
1750     for (LookupResult::iterator D = FoundDelete.begin(),
1751                              DEnd = FoundDelete.end();
1752          D != DEnd; ++D) {
1753       FunctionDecl *Fn = nullptr;
1754       if (FunctionTemplateDecl *FnTmpl
1755             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1756         // Perform template argument deduction to try to match the
1757         // expected function type.
1758         TemplateDeductionInfo Info(StartLoc);
1759         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
1760                                     Info))
1761           continue;
1762       } else
1763         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1764 
1765       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1766         Matches.push_back(std::make_pair(D.getPair(), Fn));
1767     }
1768   } else {
1769     // C++ [expr.new]p20:
1770     //   [...] Any non-placement deallocation function matches a
1771     //   non-placement allocation function. [...]
1772     for (LookupResult::iterator D = FoundDelete.begin(),
1773                              DEnd = FoundDelete.end();
1774          D != DEnd; ++D) {
1775       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1776         if (isNonPlacementDeallocationFunction(*this, Fn))
1777           Matches.push_back(std::make_pair(D.getPair(), Fn));
1778     }
1779 
1780     // C++1y [expr.new]p22:
1781     //   For a non-placement allocation function, the normal deallocation
1782     //   function lookup is used
1783     // C++1y [expr.delete]p?:
1784     //   If [...] deallocation function lookup finds both a usual deallocation
1785     //   function with only a pointer parameter and a usual deallocation
1786     //   function with both a pointer parameter and a size parameter, then the
1787     //   selected deallocation function shall be the one with two parameters.
1788     //   Otherwise, the selected deallocation function shall be the function
1789     //   with one parameter.
1790     if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1791       if (Matches[0].second->getNumParams() == 1)
1792         Matches.erase(Matches.begin());
1793       else
1794         Matches.erase(Matches.begin() + 1);
1795       assert(Matches[0].second->getNumParams() == 2 &&
1796              "found an unexpected usual deallocation function");
1797     }
1798   }
1799 
1800   // C++ [expr.new]p20:
1801   //   [...] If the lookup finds a single matching deallocation
1802   //   function, that function will be called; otherwise, no
1803   //   deallocation function will be called.
1804   if (Matches.size() == 1) {
1805     OperatorDelete = Matches[0].second;
1806 
1807     // C++0x [expr.new]p20:
1808     //   If the lookup finds the two-parameter form of a usual
1809     //   deallocation function (3.7.4.2) and that function, considered
1810     //   as a placement deallocation function, would have been
1811     //   selected as a match for the allocation function, the program
1812     //   is ill-formed.
1813     if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
1814         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
1815       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1816         << SourceRange(PlaceArgs.front()->getLocStart(),
1817                        PlaceArgs.back()->getLocEnd());
1818       if (!OperatorDelete->isImplicit())
1819         Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1820           << DeleteName;
1821     } else {
1822       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1823                             Matches[0].first);
1824     }
1825   }
1826 
1827   return false;
1828 }
1829 
1830 /// \brief Find an fitting overload for the allocation function
1831 /// in the specified scope.
1832 ///
1833 /// \param StartLoc The location of the 'new' token.
1834 /// \param Range The range of the placement arguments.
1835 /// \param Name The name of the function ('operator new' or 'operator new[]').
1836 /// \param Args The placement arguments specified.
1837 /// \param Ctx The scope in which we should search; either a class scope or the
1838 ///        translation unit.
1839 /// \param AllowMissing If \c true, report an error if we can't find any
1840 ///        allocation functions. Otherwise, succeed but don't fill in \p
1841 ///        Operator.
1842 /// \param Operator Filled in with the found allocation function. Unchanged if
1843 ///        no allocation function was found.
1844 /// \param Diagnose If \c true, issue errors if the allocation function is not
1845 ///        usable.
1846 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1847                                   DeclarationName Name, MultiExprArg Args,
1848                                   DeclContext *Ctx,
1849                                   bool AllowMissing, FunctionDecl *&Operator,
1850                                   bool Diagnose) {
1851   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1852   LookupQualifiedName(R, Ctx);
1853   if (R.empty()) {
1854     if (AllowMissing || !Diagnose)
1855       return false;
1856     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1857       << Name << Range;
1858   }
1859 
1860   if (R.isAmbiguous())
1861     return true;
1862 
1863   R.suppressDiagnostics();
1864 
1865   OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
1866   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1867        Alloc != AllocEnd; ++Alloc) {
1868     // Even member operator new/delete are implicitly treated as
1869     // static, so don't use AddMemberCandidate.
1870     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1871 
1872     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1873       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1874                                    /*ExplicitTemplateArgs=*/nullptr,
1875                                    Args, Candidates,
1876                                    /*SuppressUserConversions=*/false);
1877       continue;
1878     }
1879 
1880     FunctionDecl *Fn = cast<FunctionDecl>(D);
1881     AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
1882                          /*SuppressUserConversions=*/false);
1883   }
1884 
1885   // Do the resolution.
1886   OverloadCandidateSet::iterator Best;
1887   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1888   case OR_Success: {
1889     // Got one!
1890     FunctionDecl *FnDecl = Best->Function;
1891     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1892                               Best->FoundDecl, Diagnose) == AR_inaccessible)
1893       return true;
1894 
1895     Operator = FnDecl;
1896     return false;
1897   }
1898 
1899   case OR_No_Viable_Function:
1900     if (Diagnose) {
1901       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1902         << Name << Range;
1903       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1904     }
1905     return true;
1906 
1907   case OR_Ambiguous:
1908     if (Diagnose) {
1909       Diag(StartLoc, diag::err_ovl_ambiguous_call)
1910         << Name << Range;
1911       Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
1912     }
1913     return true;
1914 
1915   case OR_Deleted: {
1916     if (Diagnose) {
1917       Diag(StartLoc, diag::err_ovl_deleted_call)
1918         << Best->Function->isDeleted()
1919         << Name
1920         << getDeletedOrUnavailableSuffix(Best->Function)
1921         << Range;
1922       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1923     }
1924     return true;
1925   }
1926   }
1927   llvm_unreachable("Unreachable, bad result from BestViableFunction");
1928 }
1929 
1930 
1931 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1932 /// delete. These are:
1933 /// @code
1934 ///   // C++03:
1935 ///   void* operator new(std::size_t) throw(std::bad_alloc);
1936 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
1937 ///   void operator delete(void *) throw();
1938 ///   void operator delete[](void *) throw();
1939 ///   // C++11:
1940 ///   void* operator new(std::size_t);
1941 ///   void* operator new[](std::size_t);
1942 ///   void operator delete(void *) noexcept;
1943 ///   void operator delete[](void *) noexcept;
1944 ///   // C++1y:
1945 ///   void* operator new(std::size_t);
1946 ///   void* operator new[](std::size_t);
1947 ///   void operator delete(void *) noexcept;
1948 ///   void operator delete[](void *) noexcept;
1949 ///   void operator delete(void *, std::size_t) noexcept;
1950 ///   void operator delete[](void *, std::size_t) noexcept;
1951 /// @endcode
1952 /// Note that the placement and nothrow forms of new are *not* implicitly
1953 /// declared. Their use requires including \<new\>.
1954 void Sema::DeclareGlobalNewDelete() {
1955   if (GlobalNewDeleteDeclared)
1956     return;
1957 
1958   // C++ [basic.std.dynamic]p2:
1959   //   [...] The following allocation and deallocation functions (18.4) are
1960   //   implicitly declared in global scope in each translation unit of a
1961   //   program
1962   //
1963   //     C++03:
1964   //     void* operator new(std::size_t) throw(std::bad_alloc);
1965   //     void* operator new[](std::size_t) throw(std::bad_alloc);
1966   //     void  operator delete(void*) throw();
1967   //     void  operator delete[](void*) throw();
1968   //     C++11:
1969   //     void* operator new(std::size_t);
1970   //     void* operator new[](std::size_t);
1971   //     void  operator delete(void*) noexcept;
1972   //     void  operator delete[](void*) noexcept;
1973   //     C++1y:
1974   //     void* operator new(std::size_t);
1975   //     void* operator new[](std::size_t);
1976   //     void  operator delete(void*) noexcept;
1977   //     void  operator delete[](void*) noexcept;
1978   //     void  operator delete(void*, std::size_t) noexcept;
1979   //     void  operator delete[](void*, std::size_t) noexcept;
1980   //
1981   //   These implicit declarations introduce only the function names operator
1982   //   new, operator new[], operator delete, operator delete[].
1983   //
1984   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1985   // "std" or "bad_alloc" as necessary to form the exception specification.
1986   // However, we do not make these implicit declarations visible to name
1987   // lookup.
1988   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
1989     // The "std::bad_alloc" class has not yet been declared, so build it
1990     // implicitly.
1991     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1992                                         getOrCreateStdNamespace(),
1993                                         SourceLocation(), SourceLocation(),
1994                                       &PP.getIdentifierTable().get("bad_alloc"),
1995                                         nullptr);
1996     getStdBadAlloc()->setImplicit(true);
1997   }
1998 
1999   GlobalNewDeleteDeclared = true;
2000 
2001   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2002   QualType SizeT = Context.getSizeType();
2003   bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
2004 
2005   DeclareGlobalAllocationFunction(
2006       Context.DeclarationNames.getCXXOperatorName(OO_New),
2007       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2008   DeclareGlobalAllocationFunction(
2009       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
2010       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2011   DeclareGlobalAllocationFunction(
2012       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2013       Context.VoidTy, VoidPtr);
2014   DeclareGlobalAllocationFunction(
2015       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2016       Context.VoidTy, VoidPtr);
2017   if (getLangOpts().SizedDeallocation) {
2018     DeclareGlobalAllocationFunction(
2019         Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2020         Context.VoidTy, VoidPtr, Context.getSizeType());
2021     DeclareGlobalAllocationFunction(
2022         Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2023         Context.VoidTy, VoidPtr, Context.getSizeType());
2024   }
2025 }
2026 
2027 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2028 /// allocation function if it doesn't already exist.
2029 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2030                                            QualType Return,
2031                                            QualType Param1, QualType Param2,
2032                                            bool AddMallocAttr) {
2033   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2034   unsigned NumParams = Param2.isNull() ? 1 : 2;
2035 
2036   // Check if this function is already declared.
2037   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2038   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2039        Alloc != AllocEnd; ++Alloc) {
2040     // Only look at non-template functions, as it is the predefined,
2041     // non-templated allocation function we are trying to declare here.
2042     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2043       if (Func->getNumParams() == NumParams) {
2044         QualType InitialParam1Type =
2045             Context.getCanonicalType(Func->getParamDecl(0)
2046                                          ->getType().getUnqualifiedType());
2047         QualType InitialParam2Type =
2048             NumParams == 2
2049                 ? Context.getCanonicalType(Func->getParamDecl(1)
2050                                                ->getType().getUnqualifiedType())
2051                 : QualType();
2052         // FIXME: Do we need to check for default arguments here?
2053         if (InitialParam1Type == Param1 &&
2054             (NumParams == 1 || InitialParam2Type == Param2)) {
2055           if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
2056             Func->addAttr(MallocAttr::CreateImplicit(Context));
2057           // Make the function visible to name lookup, even if we found it in
2058           // an unimported module. It either is an implicitly-declared global
2059           // allocation function, or is suppressing that function.
2060           Func->setHidden(false);
2061           return;
2062         }
2063       }
2064     }
2065   }
2066 
2067   FunctionProtoType::ExtProtoInfo EPI;
2068 
2069   QualType BadAllocType;
2070   bool HasBadAllocExceptionSpec
2071     = (Name.getCXXOverloadedOperator() == OO_New ||
2072        Name.getCXXOverloadedOperator() == OO_Array_New);
2073   if (HasBadAllocExceptionSpec) {
2074     if (!getLangOpts().CPlusPlus11) {
2075       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2076       assert(StdBadAlloc && "Must have std::bad_alloc declared");
2077       EPI.ExceptionSpec.Type = EST_Dynamic;
2078       EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2079     }
2080   } else {
2081     EPI.ExceptionSpec =
2082         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2083   }
2084 
2085   QualType Params[] = { Param1, Param2 };
2086 
2087   QualType FnType = Context.getFunctionType(
2088       Return, llvm::makeArrayRef(Params, NumParams), EPI);
2089   FunctionDecl *Alloc =
2090     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2091                          SourceLocation(), Name,
2092                          FnType, /*TInfo=*/nullptr, SC_None, false, true);
2093   Alloc->setImplicit();
2094 
2095   if (AddMallocAttr)
2096     Alloc->addAttr(MallocAttr::CreateImplicit(Context));
2097 
2098   ParmVarDecl *ParamDecls[2];
2099   for (unsigned I = 0; I != NumParams; ++I) {
2100     ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2101                                         SourceLocation(), nullptr,
2102                                         Params[I], /*TInfo=*/nullptr,
2103                                         SC_None, nullptr);
2104     ParamDecls[I]->setImplicit();
2105   }
2106   Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
2107 
2108   Context.getTranslationUnitDecl()->addDecl(Alloc);
2109   IdResolver.tryAddTopLevelDecl(Alloc, Name);
2110 }
2111 
2112 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2113                                                   bool CanProvideSize,
2114                                                   DeclarationName Name) {
2115   DeclareGlobalNewDelete();
2116 
2117   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2118   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2119 
2120   // C++ [expr.new]p20:
2121   //   [...] Any non-placement deallocation function matches a
2122   //   non-placement allocation function. [...]
2123   llvm::SmallVector<FunctionDecl*, 2> Matches;
2124   for (LookupResult::iterator D = FoundDelete.begin(),
2125                            DEnd = FoundDelete.end();
2126        D != DEnd; ++D) {
2127     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2128       if (isNonPlacementDeallocationFunction(*this, Fn))
2129         Matches.push_back(Fn);
2130   }
2131 
2132   // C++1y [expr.delete]p?:
2133   //   If the type is complete and deallocation function lookup finds both a
2134   //   usual deallocation function with only a pointer parameter and a usual
2135   //   deallocation function with both a pointer parameter and a size
2136   //   parameter, then the selected deallocation function shall be the one
2137   //   with two parameters.  Otherwise, the selected deallocation function
2138   //   shall be the function with one parameter.
2139   if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2140     unsigned NumArgs = CanProvideSize ? 2 : 1;
2141     if (Matches[0]->getNumParams() != NumArgs)
2142       Matches.erase(Matches.begin());
2143     else
2144       Matches.erase(Matches.begin() + 1);
2145     assert(Matches[0]->getNumParams() == NumArgs &&
2146            "found an unexpected usual deallocation function");
2147   }
2148 
2149   assert(Matches.size() == 1 &&
2150          "unexpectedly have multiple usual deallocation functions");
2151   return Matches.front();
2152 }
2153 
2154 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2155                                     DeclarationName Name,
2156                                     FunctionDecl* &Operator, bool Diagnose) {
2157   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2158   // Try to find operator delete/operator delete[] in class scope.
2159   LookupQualifiedName(Found, RD);
2160 
2161   if (Found.isAmbiguous())
2162     return true;
2163 
2164   Found.suppressDiagnostics();
2165 
2166   SmallVector<DeclAccessPair,4> Matches;
2167   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2168        F != FEnd; ++F) {
2169     NamedDecl *ND = (*F)->getUnderlyingDecl();
2170 
2171     // Ignore template operator delete members from the check for a usual
2172     // deallocation function.
2173     if (isa<FunctionTemplateDecl>(ND))
2174       continue;
2175 
2176     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2177       Matches.push_back(F.getPair());
2178   }
2179 
2180   // There's exactly one suitable operator;  pick it.
2181   if (Matches.size() == 1) {
2182     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2183 
2184     if (Operator->isDeleted()) {
2185       if (Diagnose) {
2186         Diag(StartLoc, diag::err_deleted_function_use);
2187         NoteDeletedFunction(Operator);
2188       }
2189       return true;
2190     }
2191 
2192     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2193                               Matches[0], Diagnose) == AR_inaccessible)
2194       return true;
2195 
2196     return false;
2197 
2198   // We found multiple suitable operators;  complain about the ambiguity.
2199   } else if (!Matches.empty()) {
2200     if (Diagnose) {
2201       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2202         << Name << RD;
2203 
2204       for (SmallVectorImpl<DeclAccessPair>::iterator
2205              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2206         Diag((*F)->getUnderlyingDecl()->getLocation(),
2207              diag::note_member_declared_here) << Name;
2208     }
2209     return true;
2210   }
2211 
2212   // We did find operator delete/operator delete[] declarations, but
2213   // none of them were suitable.
2214   if (!Found.empty()) {
2215     if (Diagnose) {
2216       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2217         << Name << RD;
2218 
2219       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2220            F != FEnd; ++F)
2221         Diag((*F)->getUnderlyingDecl()->getLocation(),
2222              diag::note_member_declared_here) << Name;
2223     }
2224     return true;
2225   }
2226 
2227   Operator = nullptr;
2228   return false;
2229 }
2230 
2231 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2232 /// @code ::delete ptr; @endcode
2233 /// or
2234 /// @code delete [] ptr; @endcode
2235 ExprResult
2236 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2237                      bool ArrayForm, Expr *ExE) {
2238   // C++ [expr.delete]p1:
2239   //   The operand shall have a pointer type, or a class type having a single
2240   //   non-explicit conversion function to a pointer type. The result has type
2241   //   void.
2242   //
2243   // DR599 amends "pointer type" to "pointer to object type" in both cases.
2244 
2245   ExprResult Ex = ExE;
2246   FunctionDecl *OperatorDelete = nullptr;
2247   bool ArrayFormAsWritten = ArrayForm;
2248   bool UsualArrayDeleteWantsSize = false;
2249 
2250   if (!Ex.get()->isTypeDependent()) {
2251     // Perform lvalue-to-rvalue cast, if needed.
2252     Ex = DefaultLvalueConversion(Ex.get());
2253     if (Ex.isInvalid())
2254       return ExprError();
2255 
2256     QualType Type = Ex.get()->getType();
2257 
2258     class DeleteConverter : public ContextualImplicitConverter {
2259     public:
2260       DeleteConverter() : ContextualImplicitConverter(false, true) {}
2261 
2262       bool match(QualType ConvType) override {
2263         // FIXME: If we have an operator T* and an operator void*, we must pick
2264         // the operator T*.
2265         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2266           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2267             return true;
2268         return false;
2269       }
2270 
2271       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2272                                             QualType T) override {
2273         return S.Diag(Loc, diag::err_delete_operand) << T;
2274       }
2275 
2276       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2277                                                QualType T) override {
2278         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2279       }
2280 
2281       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2282                                                  QualType T,
2283                                                  QualType ConvTy) override {
2284         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2285       }
2286 
2287       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2288                                              QualType ConvTy) override {
2289         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2290           << ConvTy;
2291       }
2292 
2293       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2294                                               QualType T) override {
2295         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2296       }
2297 
2298       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2299                                           QualType ConvTy) override {
2300         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2301           << ConvTy;
2302       }
2303 
2304       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2305                                                QualType T,
2306                                                QualType ConvTy) override {
2307         llvm_unreachable("conversion functions are permitted");
2308       }
2309     } Converter;
2310 
2311     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
2312     if (Ex.isInvalid())
2313       return ExprError();
2314     Type = Ex.get()->getType();
2315     if (!Converter.match(Type))
2316       // FIXME: PerformContextualImplicitConversion should return ExprError
2317       //        itself in this case.
2318       return ExprError();
2319 
2320     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2321     QualType PointeeElem = Context.getBaseElementType(Pointee);
2322 
2323     if (unsigned AddressSpace = Pointee.getAddressSpace())
2324       return Diag(Ex.get()->getLocStart(),
2325                   diag::err_address_space_qualified_delete)
2326                << Pointee.getUnqualifiedType() << AddressSpace;
2327 
2328     CXXRecordDecl *PointeeRD = nullptr;
2329     if (Pointee->isVoidType() && !isSFINAEContext()) {
2330       // The C++ standard bans deleting a pointer to a non-object type, which
2331       // effectively bans deletion of "void*". However, most compilers support
2332       // this, so we treat it as a warning unless we're in a SFINAE context.
2333       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2334         << Type << Ex.get()->getSourceRange();
2335     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2336       return ExprError(Diag(StartLoc, diag::err_delete_operand)
2337         << Type << Ex.get()->getSourceRange());
2338     } else if (!Pointee->isDependentType()) {
2339       if (!RequireCompleteType(StartLoc, Pointee,
2340                                diag::warn_delete_incomplete, Ex.get())) {
2341         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2342           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2343       }
2344     }
2345 
2346     // C++ [expr.delete]p2:
2347     //   [Note: a pointer to a const type can be the operand of a
2348     //   delete-expression; it is not necessary to cast away the constness
2349     //   (5.2.11) of the pointer expression before it is used as the operand
2350     //   of the delete-expression. ]
2351 
2352     if (Pointee->isArrayType() && !ArrayForm) {
2353       Diag(StartLoc, diag::warn_delete_array_type)
2354           << Type << Ex.get()->getSourceRange()
2355           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2356       ArrayForm = true;
2357     }
2358 
2359     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2360                                       ArrayForm ? OO_Array_Delete : OO_Delete);
2361 
2362     if (PointeeRD) {
2363       if (!UseGlobal &&
2364           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2365                                    OperatorDelete))
2366         return ExprError();
2367 
2368       // If we're allocating an array of records, check whether the
2369       // usual operator delete[] has a size_t parameter.
2370       if (ArrayForm) {
2371         // If the user specifically asked to use the global allocator,
2372         // we'll need to do the lookup into the class.
2373         if (UseGlobal)
2374           UsualArrayDeleteWantsSize =
2375             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2376 
2377         // Otherwise, the usual operator delete[] should be the
2378         // function we just found.
2379         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2380           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2381       }
2382 
2383       if (!PointeeRD->hasIrrelevantDestructor())
2384         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2385           MarkFunctionReferenced(StartLoc,
2386                                     const_cast<CXXDestructorDecl*>(Dtor));
2387           if (DiagnoseUseOfDecl(Dtor, StartLoc))
2388             return ExprError();
2389         }
2390 
2391       // C++ [expr.delete]p3:
2392       //   In the first alternative (delete object), if the static type of the
2393       //   object to be deleted is different from its dynamic type, the static
2394       //   type shall be a base class of the dynamic type of the object to be
2395       //   deleted and the static type shall have a virtual destructor or the
2396       //   behavior is undefined.
2397       //
2398       // Note: a final class cannot be derived from, no issue there
2399       if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2400         CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2401         if (dtor && !dtor->isVirtual()) {
2402           if (PointeeRD->isAbstract()) {
2403             // If the class is abstract, we warn by default, because we're
2404             // sure the code has undefined behavior.
2405             Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2406                 << PointeeElem;
2407           } else if (!ArrayForm) {
2408             // Otherwise, if this is not an array delete, it's a bit suspect,
2409             // but not necessarily wrong.
2410             Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2411           }
2412         }
2413       }
2414 
2415     }
2416 
2417     if (!OperatorDelete)
2418       // Look for a global declaration.
2419       OperatorDelete = FindUsualDeallocationFunction(
2420           StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2421                     (!ArrayForm || UsualArrayDeleteWantsSize ||
2422                      Pointee.isDestructedType()),
2423           DeleteName);
2424 
2425     MarkFunctionReferenced(StartLoc, OperatorDelete);
2426 
2427     // Check access and ambiguity of operator delete and destructor.
2428     if (PointeeRD) {
2429       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2430           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2431                       PDiag(diag::err_access_dtor) << PointeeElem);
2432       }
2433     }
2434   }
2435 
2436   return new (Context) CXXDeleteExpr(
2437       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
2438       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
2439 }
2440 
2441 /// \brief Check the use of the given variable as a C++ condition in an if,
2442 /// while, do-while, or switch statement.
2443 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2444                                         SourceLocation StmtLoc,
2445                                         bool ConvertToBoolean) {
2446   if (ConditionVar->isInvalidDecl())
2447     return ExprError();
2448 
2449   QualType T = ConditionVar->getType();
2450 
2451   // C++ [stmt.select]p2:
2452   //   The declarator shall not specify a function or an array.
2453   if (T->isFunctionType())
2454     return ExprError(Diag(ConditionVar->getLocation(),
2455                           diag::err_invalid_use_of_function_type)
2456                        << ConditionVar->getSourceRange());
2457   else if (T->isArrayType())
2458     return ExprError(Diag(ConditionVar->getLocation(),
2459                           diag::err_invalid_use_of_array_type)
2460                      << ConditionVar->getSourceRange());
2461 
2462   ExprResult Condition = DeclRefExpr::Create(
2463       Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
2464       /*enclosing*/ false, ConditionVar->getLocation(),
2465       ConditionVar->getType().getNonReferenceType(), VK_LValue);
2466 
2467   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2468 
2469   if (ConvertToBoolean) {
2470     Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
2471     if (Condition.isInvalid())
2472       return ExprError();
2473   }
2474 
2475   return Condition;
2476 }
2477 
2478 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2479 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2480   // C++ 6.4p4:
2481   // The value of a condition that is an initialized declaration in a statement
2482   // other than a switch statement is the value of the declared variable
2483   // implicitly converted to type bool. If that conversion is ill-formed, the
2484   // program is ill-formed.
2485   // The value of a condition that is an expression is the value of the
2486   // expression, implicitly converted to bool.
2487   //
2488   return PerformContextuallyConvertToBool(CondExpr);
2489 }
2490 
2491 /// Helper function to determine whether this is the (deprecated) C++
2492 /// conversion from a string literal to a pointer to non-const char or
2493 /// non-const wchar_t (for narrow and wide string literals,
2494 /// respectively).
2495 bool
2496 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2497   // Look inside the implicit cast, if it exists.
2498   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2499     From = Cast->getSubExpr();
2500 
2501   // A string literal (2.13.4) that is not a wide string literal can
2502   // be converted to an rvalue of type "pointer to char"; a wide
2503   // string literal can be converted to an rvalue of type "pointer
2504   // to wchar_t" (C++ 4.2p2).
2505   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2506     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2507       if (const BuiltinType *ToPointeeType
2508           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2509         // This conversion is considered only when there is an
2510         // explicit appropriate pointer target type (C++ 4.2p2).
2511         if (!ToPtrType->getPointeeType().hasQualifiers()) {
2512           switch (StrLit->getKind()) {
2513             case StringLiteral::UTF8:
2514             case StringLiteral::UTF16:
2515             case StringLiteral::UTF32:
2516               // We don't allow UTF literals to be implicitly converted
2517               break;
2518             case StringLiteral::Ascii:
2519               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2520                       ToPointeeType->getKind() == BuiltinType::Char_S);
2521             case StringLiteral::Wide:
2522               return ToPointeeType->isWideCharType();
2523           }
2524         }
2525       }
2526 
2527   return false;
2528 }
2529 
2530 static ExprResult BuildCXXCastArgument(Sema &S,
2531                                        SourceLocation CastLoc,
2532                                        QualType Ty,
2533                                        CastKind Kind,
2534                                        CXXMethodDecl *Method,
2535                                        DeclAccessPair FoundDecl,
2536                                        bool HadMultipleCandidates,
2537                                        Expr *From) {
2538   switch (Kind) {
2539   default: llvm_unreachable("Unhandled cast kind!");
2540   case CK_ConstructorConversion: {
2541     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2542     SmallVector<Expr*, 8> ConstructorArgs;
2543 
2544     if (S.RequireNonAbstractType(CastLoc, Ty,
2545                                  diag::err_allocation_of_abstract_type))
2546       return ExprError();
2547 
2548     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2549       return ExprError();
2550 
2551     S.CheckConstructorAccess(CastLoc, Constructor,
2552                              InitializedEntity::InitializeTemporary(Ty),
2553                              Constructor->getAccess());
2554 
2555     ExprResult Result = S.BuildCXXConstructExpr(
2556         CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2557         ConstructorArgs, HadMultipleCandidates,
2558         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
2559         CXXConstructExpr::CK_Complete, SourceRange());
2560     if (Result.isInvalid())
2561       return ExprError();
2562 
2563     return S.MaybeBindToTemporary(Result.getAs<Expr>());
2564   }
2565 
2566   case CK_UserDefinedConversion: {
2567     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2568 
2569     // Create an implicit call expr that calls it.
2570     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2571     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2572                                                  HadMultipleCandidates);
2573     if (Result.isInvalid())
2574       return ExprError();
2575     // Record usage of conversion in an implicit cast.
2576     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
2577                                       CK_UserDefinedConversion, Result.get(),
2578                                       nullptr, Result.get()->getValueKind());
2579 
2580     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
2581 
2582     return S.MaybeBindToTemporary(Result.get());
2583   }
2584   }
2585 }
2586 
2587 /// PerformImplicitConversion - Perform an implicit conversion of the
2588 /// expression From to the type ToType using the pre-computed implicit
2589 /// conversion sequence ICS. Returns the converted
2590 /// expression. Action is the kind of conversion we're performing,
2591 /// used in the error message.
2592 ExprResult
2593 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2594                                 const ImplicitConversionSequence &ICS,
2595                                 AssignmentAction Action,
2596                                 CheckedConversionKind CCK) {
2597   switch (ICS.getKind()) {
2598   case ImplicitConversionSequence::StandardConversion: {
2599     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2600                                                Action, CCK);
2601     if (Res.isInvalid())
2602       return ExprError();
2603     From = Res.get();
2604     break;
2605   }
2606 
2607   case ImplicitConversionSequence::UserDefinedConversion: {
2608 
2609       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2610       CastKind CastKind;
2611       QualType BeforeToType;
2612       assert(FD && "FIXME: aggregate initialization from init list");
2613       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2614         CastKind = CK_UserDefinedConversion;
2615 
2616         // If the user-defined conversion is specified by a conversion function,
2617         // the initial standard conversion sequence converts the source type to
2618         // the implicit object parameter of the conversion function.
2619         BeforeToType = Context.getTagDeclType(Conv->getParent());
2620       } else {
2621         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2622         CastKind = CK_ConstructorConversion;
2623         // Do no conversion if dealing with ... for the first conversion.
2624         if (!ICS.UserDefined.EllipsisConversion) {
2625           // If the user-defined conversion is specified by a constructor, the
2626           // initial standard conversion sequence converts the source type to the
2627           // type required by the argument of the constructor
2628           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2629         }
2630       }
2631       // Watch out for ellipsis conversion.
2632       if (!ICS.UserDefined.EllipsisConversion) {
2633         ExprResult Res =
2634           PerformImplicitConversion(From, BeforeToType,
2635                                     ICS.UserDefined.Before, AA_Converting,
2636                                     CCK);
2637         if (Res.isInvalid())
2638           return ExprError();
2639         From = Res.get();
2640       }
2641 
2642       ExprResult CastArg
2643         = BuildCXXCastArgument(*this,
2644                                From->getLocStart(),
2645                                ToType.getNonReferenceType(),
2646                                CastKind, cast<CXXMethodDecl>(FD),
2647                                ICS.UserDefined.FoundConversionFunction,
2648                                ICS.UserDefined.HadMultipleCandidates,
2649                                From);
2650 
2651       if (CastArg.isInvalid())
2652         return ExprError();
2653 
2654       From = CastArg.get();
2655 
2656       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2657                                        AA_Converting, CCK);
2658   }
2659 
2660   case ImplicitConversionSequence::AmbiguousConversion:
2661     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2662                           PDiag(diag::err_typecheck_ambiguous_condition)
2663                             << From->getSourceRange());
2664      return ExprError();
2665 
2666   case ImplicitConversionSequence::EllipsisConversion:
2667     llvm_unreachable("Cannot perform an ellipsis conversion");
2668 
2669   case ImplicitConversionSequence::BadConversion:
2670     return ExprError();
2671   }
2672 
2673   // Everything went well.
2674   return From;
2675 }
2676 
2677 /// PerformImplicitConversion - Perform an implicit conversion of the
2678 /// expression From to the type ToType by following the standard
2679 /// conversion sequence SCS. Returns the converted
2680 /// expression. Flavor is the context in which we're performing this
2681 /// conversion, for use in error messages.
2682 ExprResult
2683 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2684                                 const StandardConversionSequence& SCS,
2685                                 AssignmentAction Action,
2686                                 CheckedConversionKind CCK) {
2687   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2688 
2689   // Overall FIXME: we are recomputing too many types here and doing far too
2690   // much extra work. What this means is that we need to keep track of more
2691   // information that is computed when we try the implicit conversion initially,
2692   // so that we don't need to recompute anything here.
2693   QualType FromType = From->getType();
2694 
2695   if (SCS.CopyConstructor) {
2696     // FIXME: When can ToType be a reference type?
2697     assert(!ToType->isReferenceType());
2698     if (SCS.Second == ICK_Derived_To_Base) {
2699       SmallVector<Expr*, 8> ConstructorArgs;
2700       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2701                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
2702                                   ConstructorArgs))
2703         return ExprError();
2704       return BuildCXXConstructExpr(
2705           /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
2706           ConstructorArgs, /*HadMultipleCandidates*/ false,
2707           /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
2708           CXXConstructExpr::CK_Complete, SourceRange());
2709     }
2710     return BuildCXXConstructExpr(
2711         /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
2712         From, /*HadMultipleCandidates*/ false,
2713         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
2714         CXXConstructExpr::CK_Complete, SourceRange());
2715   }
2716 
2717   // Resolve overloaded function references.
2718   if (Context.hasSameType(FromType, Context.OverloadTy)) {
2719     DeclAccessPair Found;
2720     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2721                                                           true, Found);
2722     if (!Fn)
2723       return ExprError();
2724 
2725     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2726       return ExprError();
2727 
2728     From = FixOverloadedFunctionReference(From, Found, Fn);
2729     FromType = From->getType();
2730   }
2731 
2732   // If we're converting to an atomic type, first convert to the corresponding
2733   // non-atomic type.
2734   QualType ToAtomicType;
2735   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2736     ToAtomicType = ToType;
2737     ToType = ToAtomic->getValueType();
2738   }
2739 
2740   // Perform the first implicit conversion.
2741   switch (SCS.First) {
2742   case ICK_Identity:
2743     // Nothing to do.
2744     break;
2745 
2746   case ICK_Lvalue_To_Rvalue: {
2747     assert(From->getObjectKind() != OK_ObjCProperty);
2748     FromType = FromType.getUnqualifiedType();
2749     ExprResult FromRes = DefaultLvalueConversion(From);
2750     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2751     From = FromRes.get();
2752     break;
2753   }
2754 
2755   case ICK_Array_To_Pointer:
2756     FromType = Context.getArrayDecayedType(FromType);
2757     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2758                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2759     break;
2760 
2761   case ICK_Function_To_Pointer:
2762     FromType = Context.getPointerType(FromType);
2763     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2764                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2765     break;
2766 
2767   default:
2768     llvm_unreachable("Improper first standard conversion");
2769   }
2770 
2771   // Perform the second implicit conversion
2772   switch (SCS.Second) {
2773   case ICK_Identity:
2774     // If both sides are functions (or pointers/references to them), there could
2775     // be incompatible exception declarations.
2776     if (CheckExceptionSpecCompatibility(From, ToType))
2777       return ExprError();
2778     // Nothing else to do.
2779     break;
2780 
2781   case ICK_NoReturn_Adjustment:
2782     // If both sides are functions (or pointers/references to them), there could
2783     // be incompatible exception declarations.
2784     if (CheckExceptionSpecCompatibility(From, ToType))
2785       return ExprError();
2786 
2787     From = ImpCastExprToType(From, ToType, CK_NoOp,
2788                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2789     break;
2790 
2791   case ICK_Integral_Promotion:
2792   case ICK_Integral_Conversion:
2793     if (ToType->isBooleanType()) {
2794       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2795              SCS.Second == ICK_Integral_Promotion &&
2796              "only enums with fixed underlying type can promote to bool");
2797       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2798                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2799     } else {
2800       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2801                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2802     }
2803     break;
2804 
2805   case ICK_Floating_Promotion:
2806   case ICK_Floating_Conversion:
2807     From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2808                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2809     break;
2810 
2811   case ICK_Complex_Promotion:
2812   case ICK_Complex_Conversion: {
2813     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2814     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2815     CastKind CK;
2816     if (FromEl->isRealFloatingType()) {
2817       if (ToEl->isRealFloatingType())
2818         CK = CK_FloatingComplexCast;
2819       else
2820         CK = CK_FloatingComplexToIntegralComplex;
2821     } else if (ToEl->isRealFloatingType()) {
2822       CK = CK_IntegralComplexToFloatingComplex;
2823     } else {
2824       CK = CK_IntegralComplexCast;
2825     }
2826     From = ImpCastExprToType(From, ToType, CK,
2827                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2828     break;
2829   }
2830 
2831   case ICK_Floating_Integral:
2832     if (ToType->isRealFloatingType())
2833       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2834                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2835     else
2836       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2837                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2838     break;
2839 
2840   case ICK_Compatible_Conversion:
2841       From = ImpCastExprToType(From, ToType, CK_NoOp,
2842                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2843     break;
2844 
2845   case ICK_Writeback_Conversion:
2846   case ICK_Pointer_Conversion: {
2847     if (SCS.IncompatibleObjC && Action != AA_Casting) {
2848       // Diagnose incompatible Objective-C conversions
2849       if (Action == AA_Initializing || Action == AA_Assigning)
2850         Diag(From->getLocStart(),
2851              diag::ext_typecheck_convert_incompatible_pointer)
2852           << ToType << From->getType() << Action
2853           << From->getSourceRange() << 0;
2854       else
2855         Diag(From->getLocStart(),
2856              diag::ext_typecheck_convert_incompatible_pointer)
2857           << From->getType() << ToType << Action
2858           << From->getSourceRange() << 0;
2859 
2860       if (From->getType()->isObjCObjectPointerType() &&
2861           ToType->isObjCObjectPointerType())
2862         EmitRelatedResultTypeNote(From);
2863     }
2864     else if (getLangOpts().ObjCAutoRefCount &&
2865              !CheckObjCARCUnavailableWeakConversion(ToType,
2866                                                     From->getType())) {
2867       if (Action == AA_Initializing)
2868         Diag(From->getLocStart(),
2869              diag::err_arc_weak_unavailable_assign);
2870       else
2871         Diag(From->getLocStart(),
2872              diag::err_arc_convesion_of_weak_unavailable)
2873           << (Action == AA_Casting) << From->getType() << ToType
2874           << From->getSourceRange();
2875     }
2876 
2877     CastKind Kind = CK_Invalid;
2878     CXXCastPath BasePath;
2879     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2880       return ExprError();
2881 
2882     // Make sure we extend blocks if necessary.
2883     // FIXME: doing this here is really ugly.
2884     if (Kind == CK_BlockPointerToObjCPointerCast) {
2885       ExprResult E = From;
2886       (void) PrepareCastToObjCObjectPointer(E);
2887       From = E.get();
2888     }
2889     if (getLangOpts().ObjCAutoRefCount)
2890       CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
2891     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2892              .get();
2893     break;
2894   }
2895 
2896   case ICK_Pointer_Member: {
2897     CastKind Kind = CK_Invalid;
2898     CXXCastPath BasePath;
2899     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2900       return ExprError();
2901     if (CheckExceptionSpecCompatibility(From, ToType))
2902       return ExprError();
2903 
2904     // We may not have been able to figure out what this member pointer resolved
2905     // to up until this exact point.  Attempt to lock-in it's inheritance model.
2906     QualType FromType = From->getType();
2907     if (FromType->isMemberPointerType())
2908       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2909         RequireCompleteType(From->getExprLoc(), FromType, 0);
2910 
2911     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2912              .get();
2913     break;
2914   }
2915 
2916   case ICK_Boolean_Conversion:
2917     // Perform half-to-boolean conversion via float.
2918     if (From->getType()->isHalfType()) {
2919       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
2920       FromType = Context.FloatTy;
2921     }
2922 
2923     From = ImpCastExprToType(From, Context.BoolTy,
2924                              ScalarTypeToBooleanCastKind(FromType),
2925                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2926     break;
2927 
2928   case ICK_Derived_To_Base: {
2929     CXXCastPath BasePath;
2930     if (CheckDerivedToBaseConversion(From->getType(),
2931                                      ToType.getNonReferenceType(),
2932                                      From->getLocStart(),
2933                                      From->getSourceRange(),
2934                                      &BasePath,
2935                                      CStyle))
2936       return ExprError();
2937 
2938     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2939                       CK_DerivedToBase, From->getValueKind(),
2940                       &BasePath, CCK).get();
2941     break;
2942   }
2943 
2944   case ICK_Vector_Conversion:
2945     From = ImpCastExprToType(From, ToType, CK_BitCast,
2946                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2947     break;
2948 
2949   case ICK_Vector_Splat:
2950     From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2951                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
2952     break;
2953 
2954   case ICK_Complex_Real:
2955     // Case 1.  x -> _Complex y
2956     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2957       QualType ElType = ToComplex->getElementType();
2958       bool isFloatingComplex = ElType->isRealFloatingType();
2959 
2960       // x -> y
2961       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2962         // do nothing
2963       } else if (From->getType()->isRealFloatingType()) {
2964         From = ImpCastExprToType(From, ElType,
2965                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
2966       } else {
2967         assert(From->getType()->isIntegerType());
2968         From = ImpCastExprToType(From, ElType,
2969                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
2970       }
2971       // y -> _Complex y
2972       From = ImpCastExprToType(From, ToType,
2973                    isFloatingComplex ? CK_FloatingRealToComplex
2974                                      : CK_IntegralRealToComplex).get();
2975 
2976     // Case 2.  _Complex x -> y
2977     } else {
2978       const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2979       assert(FromComplex);
2980 
2981       QualType ElType = FromComplex->getElementType();
2982       bool isFloatingComplex = ElType->isRealFloatingType();
2983 
2984       // _Complex x -> x
2985       From = ImpCastExprToType(From, ElType,
2986                    isFloatingComplex ? CK_FloatingComplexToReal
2987                                      : CK_IntegralComplexToReal,
2988                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
2989 
2990       // x -> y
2991       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2992         // do nothing
2993       } else if (ToType->isRealFloatingType()) {
2994         From = ImpCastExprToType(From, ToType,
2995                    isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2996                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
2997       } else {
2998         assert(ToType->isIntegerType());
2999         From = ImpCastExprToType(From, ToType,
3000                    isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3001                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3002       }
3003     }
3004     break;
3005 
3006   case ICK_Block_Pointer_Conversion: {
3007     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3008                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
3009     break;
3010   }
3011 
3012   case ICK_TransparentUnionConversion: {
3013     ExprResult FromRes = From;
3014     Sema::AssignConvertType ConvTy =
3015       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3016     if (FromRes.isInvalid())
3017       return ExprError();
3018     From = FromRes.get();
3019     assert ((ConvTy == Sema::Compatible) &&
3020             "Improper transparent union conversion");
3021     (void)ConvTy;
3022     break;
3023   }
3024 
3025   case ICK_Zero_Event_Conversion:
3026     From = ImpCastExprToType(From, ToType,
3027                              CK_ZeroToOCLEvent,
3028                              From->getValueKind()).get();
3029     break;
3030 
3031   case ICK_Lvalue_To_Rvalue:
3032   case ICK_Array_To_Pointer:
3033   case ICK_Function_To_Pointer:
3034   case ICK_Qualification:
3035   case ICK_Num_Conversion_Kinds:
3036     llvm_unreachable("Improper second standard conversion");
3037   }
3038 
3039   switch (SCS.Third) {
3040   case ICK_Identity:
3041     // Nothing to do.
3042     break;
3043 
3044   case ICK_Qualification: {
3045     // The qualification keeps the category of the inner expression, unless the
3046     // target type isn't a reference.
3047     ExprValueKind VK = ToType->isReferenceType() ?
3048                                   From->getValueKind() : VK_RValue;
3049     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3050                              CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3051 
3052     if (SCS.DeprecatedStringLiteralToCharPtr &&
3053         !getLangOpts().WritableStrings) {
3054       Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3055            ? diag::ext_deprecated_string_literal_conversion
3056            : diag::warn_deprecated_string_literal_conversion)
3057         << ToType.getNonReferenceType();
3058     }
3059 
3060     break;
3061   }
3062 
3063   default:
3064     llvm_unreachable("Improper third standard conversion");
3065   }
3066 
3067   // If this conversion sequence involved a scalar -> atomic conversion, perform
3068   // that conversion now.
3069   if (!ToAtomicType.isNull()) {
3070     assert(Context.hasSameType(
3071         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3072     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3073                              VK_RValue, nullptr, CCK).get();
3074   }
3075 
3076   return From;
3077 }
3078 
3079 /// \brief Check the completeness of a type in a unary type trait.
3080 ///
3081 /// If the particular type trait requires a complete type, tries to complete
3082 /// it. If completing the type fails, a diagnostic is emitted and false
3083 /// returned. If completing the type succeeds or no completion was required,
3084 /// returns true.
3085 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
3086                                                 SourceLocation Loc,
3087                                                 QualType ArgTy) {
3088   // C++0x [meta.unary.prop]p3:
3089   //   For all of the class templates X declared in this Clause, instantiating
3090   //   that template with a template argument that is a class template
3091   //   specialization may result in the implicit instantiation of the template
3092   //   argument if and only if the semantics of X require that the argument
3093   //   must be a complete type.
3094   // We apply this rule to all the type trait expressions used to implement
3095   // these class templates. We also try to follow any GCC documented behavior
3096   // in these expressions to ensure portability of standard libraries.
3097   switch (UTT) {
3098   default: llvm_unreachable("not a UTT");
3099     // is_complete_type somewhat obviously cannot require a complete type.
3100   case UTT_IsCompleteType:
3101     // Fall-through
3102 
3103     // These traits are modeled on the type predicates in C++0x
3104     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3105     // requiring a complete type, as whether or not they return true cannot be
3106     // impacted by the completeness of the type.
3107   case UTT_IsVoid:
3108   case UTT_IsIntegral:
3109   case UTT_IsFloatingPoint:
3110   case UTT_IsArray:
3111   case UTT_IsPointer:
3112   case UTT_IsLvalueReference:
3113   case UTT_IsRvalueReference:
3114   case UTT_IsMemberFunctionPointer:
3115   case UTT_IsMemberObjectPointer:
3116   case UTT_IsEnum:
3117   case UTT_IsUnion:
3118   case UTT_IsClass:
3119   case UTT_IsFunction:
3120   case UTT_IsReference:
3121   case UTT_IsArithmetic:
3122   case UTT_IsFundamental:
3123   case UTT_IsObject:
3124   case UTT_IsScalar:
3125   case UTT_IsCompound:
3126   case UTT_IsMemberPointer:
3127     // Fall-through
3128 
3129     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3130     // which requires some of its traits to have the complete type. However,
3131     // the completeness of the type cannot impact these traits' semantics, and
3132     // so they don't require it. This matches the comments on these traits in
3133     // Table 49.
3134   case UTT_IsConst:
3135   case UTT_IsVolatile:
3136   case UTT_IsSigned:
3137   case UTT_IsUnsigned:
3138     return true;
3139 
3140     // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3141     // applied to a complete type.
3142   case UTT_IsTrivial:
3143   case UTT_IsTriviallyCopyable:
3144   case UTT_IsStandardLayout:
3145   case UTT_IsPOD:
3146   case UTT_IsLiteral:
3147   case UTT_IsEmpty:
3148   case UTT_IsPolymorphic:
3149   case UTT_IsAbstract:
3150   case UTT_IsInterfaceClass:
3151   case UTT_IsDestructible:
3152   case UTT_IsNothrowDestructible:
3153     // Fall-through
3154 
3155   // These traits require a complete type.
3156   case UTT_IsFinal:
3157   case UTT_IsSealed:
3158 
3159     // These trait expressions are designed to help implement predicates in
3160     // [meta.unary.prop] despite not being named the same. They are specified
3161     // by both GCC and the Embarcadero C++ compiler, and require the complete
3162     // type due to the overarching C++0x type predicates being implemented
3163     // requiring the complete type.
3164   case UTT_HasNothrowAssign:
3165   case UTT_HasNothrowMoveAssign:
3166   case UTT_HasNothrowConstructor:
3167   case UTT_HasNothrowCopy:
3168   case UTT_HasTrivialAssign:
3169   case UTT_HasTrivialMoveAssign:
3170   case UTT_HasTrivialDefaultConstructor:
3171   case UTT_HasTrivialMoveConstructor:
3172   case UTT_HasTrivialCopy:
3173   case UTT_HasTrivialDestructor:
3174   case UTT_HasVirtualDestructor:
3175     // Arrays of unknown bound are expressly allowed.
3176     QualType ElTy = ArgTy;
3177     if (ArgTy->isIncompleteArrayType())
3178       ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3179 
3180     // The void type is expressly allowed.
3181     if (ElTy->isVoidType())
3182       return true;
3183 
3184     return !S.RequireCompleteType(
3185       Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3186   }
3187 }
3188 
3189 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3190                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3191                                bool (CXXRecordDecl::*HasTrivial)() const,
3192                                bool (CXXRecordDecl::*HasNonTrivial)() const,
3193                                bool (CXXMethodDecl::*IsDesiredOp)() const)
3194 {
3195   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3196   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3197     return true;
3198 
3199   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3200   DeclarationNameInfo NameInfo(Name, KeyLoc);
3201   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3202   if (Self.LookupQualifiedName(Res, RD)) {
3203     bool FoundOperator = false;
3204     Res.suppressDiagnostics();
3205     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3206          Op != OpEnd; ++Op) {
3207       if (isa<FunctionTemplateDecl>(*Op))
3208         continue;
3209 
3210       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3211       if((Operator->*IsDesiredOp)()) {
3212         FoundOperator = true;
3213         const FunctionProtoType *CPT =
3214           Operator->getType()->getAs<FunctionProtoType>();
3215         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3216         if (!CPT || !CPT->isNothrow(C))
3217           return false;
3218       }
3219     }
3220     return FoundOperator;
3221   }
3222   return false;
3223 }
3224 
3225 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
3226                                    SourceLocation KeyLoc, QualType T) {
3227   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3228 
3229   ASTContext &C = Self.Context;
3230   switch(UTT) {
3231   default: llvm_unreachable("not a UTT");
3232     // Type trait expressions corresponding to the primary type category
3233     // predicates in C++0x [meta.unary.cat].
3234   case UTT_IsVoid:
3235     return T->isVoidType();
3236   case UTT_IsIntegral:
3237     return T->isIntegralType(C);
3238   case UTT_IsFloatingPoint:
3239     return T->isFloatingType();
3240   case UTT_IsArray:
3241     return T->isArrayType();
3242   case UTT_IsPointer:
3243     return T->isPointerType();
3244   case UTT_IsLvalueReference:
3245     return T->isLValueReferenceType();
3246   case UTT_IsRvalueReference:
3247     return T->isRValueReferenceType();
3248   case UTT_IsMemberFunctionPointer:
3249     return T->isMemberFunctionPointerType();
3250   case UTT_IsMemberObjectPointer:
3251     return T->isMemberDataPointerType();
3252   case UTT_IsEnum:
3253     return T->isEnumeralType();
3254   case UTT_IsUnion:
3255     return T->isUnionType();
3256   case UTT_IsClass:
3257     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3258   case UTT_IsFunction:
3259     return T->isFunctionType();
3260 
3261     // Type trait expressions which correspond to the convenient composition
3262     // predicates in C++0x [meta.unary.comp].
3263   case UTT_IsReference:
3264     return T->isReferenceType();
3265   case UTT_IsArithmetic:
3266     return T->isArithmeticType() && !T->isEnumeralType();
3267   case UTT_IsFundamental:
3268     return T->isFundamentalType();
3269   case UTT_IsObject:
3270     return T->isObjectType();
3271   case UTT_IsScalar:
3272     // Note: semantic analysis depends on Objective-C lifetime types to be
3273     // considered scalar types. However, such types do not actually behave
3274     // like scalar types at run time (since they may require retain/release
3275     // operations), so we report them as non-scalar.
3276     if (T->isObjCLifetimeType()) {
3277       switch (T.getObjCLifetime()) {
3278       case Qualifiers::OCL_None:
3279       case Qualifiers::OCL_ExplicitNone:
3280         return true;
3281 
3282       case Qualifiers::OCL_Strong:
3283       case Qualifiers::OCL_Weak:
3284       case Qualifiers::OCL_Autoreleasing:
3285         return false;
3286       }
3287     }
3288 
3289     return T->isScalarType();
3290   case UTT_IsCompound:
3291     return T->isCompoundType();
3292   case UTT_IsMemberPointer:
3293     return T->isMemberPointerType();
3294 
3295     // Type trait expressions which correspond to the type property predicates
3296     // in C++0x [meta.unary.prop].
3297   case UTT_IsConst:
3298     return T.isConstQualified();
3299   case UTT_IsVolatile:
3300     return T.isVolatileQualified();
3301   case UTT_IsTrivial:
3302     return T.isTrivialType(Self.Context);
3303   case UTT_IsTriviallyCopyable:
3304     return T.isTriviallyCopyableType(Self.Context);
3305   case UTT_IsStandardLayout:
3306     return T->isStandardLayoutType();
3307   case UTT_IsPOD:
3308     return T.isPODType(Self.Context);
3309   case UTT_IsLiteral:
3310     return T->isLiteralType(Self.Context);
3311   case UTT_IsEmpty:
3312     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3313       return !RD->isUnion() && RD->isEmpty();
3314     return false;
3315   case UTT_IsPolymorphic:
3316     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3317       return RD->isPolymorphic();
3318     return false;
3319   case UTT_IsAbstract:
3320     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3321       return RD->isAbstract();
3322     return false;
3323   case UTT_IsInterfaceClass:
3324     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3325       return RD->isInterface();
3326     return false;
3327   case UTT_IsFinal:
3328     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3329       return RD->hasAttr<FinalAttr>();
3330     return false;
3331   case UTT_IsSealed:
3332     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3333       if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3334         return FA->isSpelledAsSealed();
3335     return false;
3336   case UTT_IsSigned:
3337     return T->isSignedIntegerType();
3338   case UTT_IsUnsigned:
3339     return T->isUnsignedIntegerType();
3340 
3341     // Type trait expressions which query classes regarding their construction,
3342     // destruction, and copying. Rather than being based directly on the
3343     // related type predicates in the standard, they are specified by both
3344     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3345     // specifications.
3346     //
3347     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3348     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3349     //
3350     // Note that these builtins do not behave as documented in g++: if a class
3351     // has both a trivial and a non-trivial special member of a particular kind,
3352     // they return false! For now, we emulate this behavior.
3353     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3354     // does not correctly compute triviality in the presence of multiple special
3355     // members of the same kind. Revisit this once the g++ bug is fixed.
3356   case UTT_HasTrivialDefaultConstructor:
3357     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3358     //   If __is_pod (type) is true then the trait is true, else if type is
3359     //   a cv class or union type (or array thereof) with a trivial default
3360     //   constructor ([class.ctor]) then the trait is true, else it is false.
3361     if (T.isPODType(Self.Context))
3362       return true;
3363     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3364       return RD->hasTrivialDefaultConstructor() &&
3365              !RD->hasNonTrivialDefaultConstructor();
3366     return false;
3367   case UTT_HasTrivialMoveConstructor:
3368     //  This trait is implemented by MSVC 2012 and needed to parse the
3369     //  standard library headers. Specifically this is used as the logic
3370     //  behind std::is_trivially_move_constructible (20.9.4.3).
3371     if (T.isPODType(Self.Context))
3372       return true;
3373     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3374       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3375     return false;
3376   case UTT_HasTrivialCopy:
3377     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3378     //   If __is_pod (type) is true or type is a reference type then
3379     //   the trait is true, else if type is a cv class or union type
3380     //   with a trivial copy constructor ([class.copy]) then the trait
3381     //   is true, else it is false.
3382     if (T.isPODType(Self.Context) || T->isReferenceType())
3383       return true;
3384     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3385       return RD->hasTrivialCopyConstructor() &&
3386              !RD->hasNonTrivialCopyConstructor();
3387     return false;
3388   case UTT_HasTrivialMoveAssign:
3389     //  This trait is implemented by MSVC 2012 and needed to parse the
3390     //  standard library headers. Specifically it is used as the logic
3391     //  behind std::is_trivially_move_assignable (20.9.4.3)
3392     if (T.isPODType(Self.Context))
3393       return true;
3394     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3395       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3396     return false;
3397   case UTT_HasTrivialAssign:
3398     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3399     //   If type is const qualified or is a reference type then the
3400     //   trait is false. Otherwise if __is_pod (type) is true then the
3401     //   trait is true, else if type is a cv class or union type with
3402     //   a trivial copy assignment ([class.copy]) then the trait is
3403     //   true, else it is false.
3404     // Note: the const and reference restrictions are interesting,
3405     // given that const and reference members don't prevent a class
3406     // from having a trivial copy assignment operator (but do cause
3407     // errors if the copy assignment operator is actually used, q.v.
3408     // [class.copy]p12).
3409 
3410     if (T.isConstQualified())
3411       return false;
3412     if (T.isPODType(Self.Context))
3413       return true;
3414     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3415       return RD->hasTrivialCopyAssignment() &&
3416              !RD->hasNonTrivialCopyAssignment();
3417     return false;
3418   case UTT_IsDestructible:
3419   case UTT_IsNothrowDestructible:
3420     // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
3421     // For now, let's fall through.
3422   case UTT_HasTrivialDestructor:
3423     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
3424     //   If __is_pod (type) is true or type is a reference type
3425     //   then the trait is true, else if type is a cv class or union
3426     //   type (or array thereof) with a trivial destructor
3427     //   ([class.dtor]) then the trait is true, else it is
3428     //   false.
3429     if (T.isPODType(Self.Context) || T->isReferenceType())
3430       return true;
3431 
3432     // Objective-C++ ARC: autorelease types don't require destruction.
3433     if (T->isObjCLifetimeType() &&
3434         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3435       return true;
3436 
3437     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3438       return RD->hasTrivialDestructor();
3439     return false;
3440   // TODO: Propagate nothrowness for implicitly declared special members.
3441   case UTT_HasNothrowAssign:
3442     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3443     //   If type is const qualified or is a reference type then the
3444     //   trait is false. Otherwise if __has_trivial_assign (type)
3445     //   is true then the trait is true, else if type is a cv class
3446     //   or union type with copy assignment operators that are known
3447     //   not to throw an exception then the trait is true, else it is
3448     //   false.
3449     if (C.getBaseElementType(T).isConstQualified())
3450       return false;
3451     if (T->isReferenceType())
3452       return false;
3453     if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3454       return true;
3455 
3456     if (const RecordType *RT = T->getAs<RecordType>())
3457       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3458                                 &CXXRecordDecl::hasTrivialCopyAssignment,
3459                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3460                                 &CXXMethodDecl::isCopyAssignmentOperator);
3461     return false;
3462   case UTT_HasNothrowMoveAssign:
3463     //  This trait is implemented by MSVC 2012 and needed to parse the
3464     //  standard library headers. Specifically this is used as the logic
3465     //  behind std::is_nothrow_move_assignable (20.9.4.3).
3466     if (T.isPODType(Self.Context))
3467       return true;
3468 
3469     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3470       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3471                                 &CXXRecordDecl::hasTrivialMoveAssignment,
3472                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3473                                 &CXXMethodDecl::isMoveAssignmentOperator);
3474     return false;
3475   case UTT_HasNothrowCopy:
3476     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3477     //   If __has_trivial_copy (type) is true then the trait is true, else
3478     //   if type is a cv class or union type with copy constructors that are
3479     //   known not to throw an exception then the trait is true, else it is
3480     //   false.
3481     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3482       return true;
3483     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3484       if (RD->hasTrivialCopyConstructor() &&
3485           !RD->hasNonTrivialCopyConstructor())
3486         return true;
3487 
3488       bool FoundConstructor = false;
3489       unsigned FoundTQs;
3490       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3491       for (DeclContext::lookup_const_iterator Con = R.begin(),
3492            ConEnd = R.end(); Con != ConEnd; ++Con) {
3493         // A template constructor is never a copy constructor.
3494         // FIXME: However, it may actually be selected at the actual overload
3495         // resolution point.
3496         if (isa<FunctionTemplateDecl>(*Con))
3497           continue;
3498         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3499         if (Constructor->isCopyConstructor(FoundTQs)) {
3500           FoundConstructor = true;
3501           const FunctionProtoType *CPT
3502               = Constructor->getType()->getAs<FunctionProtoType>();
3503           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3504           if (!CPT)
3505             return false;
3506           // TODO: check whether evaluating default arguments can throw.
3507           // For now, we'll be conservative and assume that they can throw.
3508           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
3509             return false;
3510         }
3511       }
3512 
3513       return FoundConstructor;
3514     }
3515     return false;
3516   case UTT_HasNothrowConstructor:
3517     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
3518     //   If __has_trivial_constructor (type) is true then the trait is
3519     //   true, else if type is a cv class or union type (or array
3520     //   thereof) with a default constructor that is known not to
3521     //   throw an exception then the trait is true, else it is false.
3522     if (T.isPODType(C) || T->isObjCLifetimeType())
3523       return true;
3524     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3525       if (RD->hasTrivialDefaultConstructor() &&
3526           !RD->hasNonTrivialDefaultConstructor())
3527         return true;
3528 
3529       bool FoundConstructor = false;
3530       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3531       for (DeclContext::lookup_const_iterator Con = R.begin(),
3532            ConEnd = R.end(); Con != ConEnd; ++Con) {
3533         // FIXME: In C++0x, a constructor template can be a default constructor.
3534         if (isa<FunctionTemplateDecl>(*Con))
3535           continue;
3536         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3537         if (Constructor->isDefaultConstructor()) {
3538           FoundConstructor = true;
3539           const FunctionProtoType *CPT
3540               = Constructor->getType()->getAs<FunctionProtoType>();
3541           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3542           if (!CPT)
3543             return false;
3544           // FIXME: check whether evaluating default arguments can throw.
3545           // For now, we'll be conservative and assume that they can throw.
3546           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
3547             return false;
3548         }
3549       }
3550       return FoundConstructor;
3551     }
3552     return false;
3553   case UTT_HasVirtualDestructor:
3554     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3555     //   If type is a class type with a virtual destructor ([class.dtor])
3556     //   then the trait is true, else it is false.
3557     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3558       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3559         return Destructor->isVirtual();
3560     return false;
3561 
3562     // These type trait expressions are modeled on the specifications for the
3563     // Embarcadero C++0x type trait functions:
3564     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3565   case UTT_IsCompleteType:
3566     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3567     //   Returns True if and only if T is a complete type at the point of the
3568     //   function call.
3569     return !T->isIncompleteType();
3570   }
3571 }
3572 
3573 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
3574 /// ARC mode.
3575 static bool hasNontrivialObjCLifetime(QualType T) {
3576   switch (T.getObjCLifetime()) {
3577   case Qualifiers::OCL_ExplicitNone:
3578     return false;
3579 
3580   case Qualifiers::OCL_Strong:
3581   case Qualifiers::OCL_Weak:
3582   case Qualifiers::OCL_Autoreleasing:
3583     return true;
3584 
3585   case Qualifiers::OCL_None:
3586     return T->isObjCLifetimeType();
3587   }
3588 
3589   llvm_unreachable("Unknown ObjC lifetime qualifier");
3590 }
3591 
3592 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3593                                     QualType RhsT, SourceLocation KeyLoc);
3594 
3595 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3596                               ArrayRef<TypeSourceInfo *> Args,
3597                               SourceLocation RParenLoc) {
3598   if (Kind <= UTT_Last)
3599     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
3600 
3601   if (Kind <= BTT_Last)
3602     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
3603                                    Args[1]->getType(), RParenLoc);
3604 
3605   switch (Kind) {
3606   case clang::TT_IsConstructible:
3607   case clang::TT_IsNothrowConstructible:
3608   case clang::TT_IsTriviallyConstructible: {
3609     // C++11 [meta.unary.prop]:
3610     //   is_trivially_constructible is defined as:
3611     //
3612     //     is_constructible<T, Args...>::value is true and the variable
3613     //     definition for is_constructible, as defined below, is known to call
3614     //     no operation that is not trivial.
3615     //
3616     //   The predicate condition for a template specialization
3617     //   is_constructible<T, Args...> shall be satisfied if and only if the
3618     //   following variable definition would be well-formed for some invented
3619     //   variable t:
3620     //
3621     //     T t(create<Args>()...);
3622     assert(!Args.empty());
3623 
3624     // Precondition: T and all types in the parameter pack Args shall be
3625     // complete types, (possibly cv-qualified) void, or arrays of
3626     // unknown bound.
3627     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3628       QualType ArgTy = Args[I]->getType();
3629       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
3630         continue;
3631 
3632       if (S.RequireCompleteType(KWLoc, ArgTy,
3633           diag::err_incomplete_type_used_in_type_trait_expr))
3634         return false;
3635     }
3636 
3637     // Make sure the first argument is a complete type.
3638     if (Args[0]->getType()->isIncompleteType())
3639       return false;
3640 
3641     // Make sure the first argument is not an abstract type.
3642     CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
3643     if (RD && RD->isAbstract())
3644       return false;
3645 
3646     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3647     SmallVector<Expr *, 2> ArgExprs;
3648     ArgExprs.reserve(Args.size() - 1);
3649     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3650       QualType T = Args[I]->getType();
3651       if (T->isObjectType() || T->isFunctionType())
3652         T = S.Context.getRValueReferenceType(T);
3653       OpaqueArgExprs.push_back(
3654         OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3655                         T.getNonLValueExprType(S.Context),
3656                         Expr::getValueKindForType(T)));
3657     }
3658     for (Expr &E : OpaqueArgExprs)
3659       ArgExprs.push_back(&E);
3660 
3661     // Perform the initialization in an unevaluated context within a SFINAE
3662     // trap at translation unit scope.
3663     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3664     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3665     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3666     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3667     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3668                                                                  RParenLoc));
3669     InitializationSequence Init(S, To, InitKind, ArgExprs);
3670     if (Init.Failed())
3671       return false;
3672 
3673     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3674     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3675       return false;
3676 
3677     if (Kind == clang::TT_IsConstructible)
3678       return true;
3679 
3680     if (Kind == clang::TT_IsNothrowConstructible)
3681       return S.canThrow(Result.get()) == CT_Cannot;
3682 
3683     if (Kind == clang::TT_IsTriviallyConstructible) {
3684       // Under Objective-C ARC, if the destination has non-trivial Objective-C
3685       // lifetime, this is a non-trivial construction.
3686       if (S.getLangOpts().ObjCAutoRefCount &&
3687           hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3688         return false;
3689 
3690       // The initialization succeeded; now make sure there are no non-trivial
3691       // calls.
3692       return !Result.get()->hasNonTrivialCall(S.Context);
3693     }
3694 
3695     llvm_unreachable("unhandled type trait");
3696     return false;
3697   }
3698     default: llvm_unreachable("not a TT");
3699   }
3700 
3701   return false;
3702 }
3703 
3704 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3705                                 ArrayRef<TypeSourceInfo *> Args,
3706                                 SourceLocation RParenLoc) {
3707   QualType ResultType = Context.getLogicalOperationType();
3708 
3709   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
3710                                *this, Kind, KWLoc, Args[0]->getType()))
3711     return ExprError();
3712 
3713   bool Dependent = false;
3714   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3715     if (Args[I]->getType()->isDependentType()) {
3716       Dependent = true;
3717       break;
3718     }
3719   }
3720 
3721   bool Result = false;
3722   if (!Dependent)
3723     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3724 
3725   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
3726                                RParenLoc, Result);
3727 }
3728 
3729 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3730                                 ArrayRef<ParsedType> Args,
3731                                 SourceLocation RParenLoc) {
3732   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3733   ConvertedArgs.reserve(Args.size());
3734 
3735   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3736     TypeSourceInfo *TInfo;
3737     QualType T = GetTypeFromParser(Args[I], &TInfo);
3738     if (!TInfo)
3739       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3740 
3741     ConvertedArgs.push_back(TInfo);
3742   }
3743 
3744   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3745 }
3746 
3747 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
3748                                     QualType RhsT, SourceLocation KeyLoc) {
3749   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3750          "Cannot evaluate traits of dependent types");
3751 
3752   switch(BTT) {
3753   case BTT_IsBaseOf: {
3754     // C++0x [meta.rel]p2
3755     // Base is a base class of Derived without regard to cv-qualifiers or
3756     // Base and Derived are not unions and name the same class type without
3757     // regard to cv-qualifiers.
3758 
3759     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3760     if (!lhsRecord) return false;
3761 
3762     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3763     if (!rhsRecord) return false;
3764 
3765     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3766              == (lhsRecord == rhsRecord));
3767 
3768     if (lhsRecord == rhsRecord)
3769       return !lhsRecord->getDecl()->isUnion();
3770 
3771     // C++0x [meta.rel]p2:
3772     //   If Base and Derived are class types and are different types
3773     //   (ignoring possible cv-qualifiers) then Derived shall be a
3774     //   complete type.
3775     if (Self.RequireCompleteType(KeyLoc, RhsT,
3776                           diag::err_incomplete_type_used_in_type_trait_expr))
3777       return false;
3778 
3779     return cast<CXXRecordDecl>(rhsRecord->getDecl())
3780       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3781   }
3782   case BTT_IsSame:
3783     return Self.Context.hasSameType(LhsT, RhsT);
3784   case BTT_TypeCompatible:
3785     return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3786                                            RhsT.getUnqualifiedType());
3787   case BTT_IsConvertible:
3788   case BTT_IsConvertibleTo: {
3789     // C++0x [meta.rel]p4:
3790     //   Given the following function prototype:
3791     //
3792     //     template <class T>
3793     //       typename add_rvalue_reference<T>::type create();
3794     //
3795     //   the predicate condition for a template specialization
3796     //   is_convertible<From, To> shall be satisfied if and only if
3797     //   the return expression in the following code would be
3798     //   well-formed, including any implicit conversions to the return
3799     //   type of the function:
3800     //
3801     //     To test() {
3802     //       return create<From>();
3803     //     }
3804     //
3805     //   Access checking is performed as if in a context unrelated to To and
3806     //   From. Only the validity of the immediate context of the expression
3807     //   of the return-statement (including conversions to the return type)
3808     //   is considered.
3809     //
3810     // We model the initialization as a copy-initialization of a temporary
3811     // of the appropriate type, which for this expression is identical to the
3812     // return statement (since NRVO doesn't apply).
3813 
3814     // Functions aren't allowed to return function or array types.
3815     if (RhsT->isFunctionType() || RhsT->isArrayType())
3816       return false;
3817 
3818     // A return statement in a void function must have void type.
3819     if (RhsT->isVoidType())
3820       return LhsT->isVoidType();
3821 
3822     // A function definition requires a complete, non-abstract return type.
3823     if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3824         Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3825       return false;
3826 
3827     // Compute the result of add_rvalue_reference.
3828     if (LhsT->isObjectType() || LhsT->isFunctionType())
3829       LhsT = Self.Context.getRValueReferenceType(LhsT);
3830 
3831     // Build a fake source and destination for initialization.
3832     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3833     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3834                          Expr::getValueKindForType(LhsT));
3835     Expr *FromPtr = &From;
3836     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3837                                                            SourceLocation()));
3838 
3839     // Perform the initialization in an unevaluated context within a SFINAE
3840     // trap at translation unit scope.
3841     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3842     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3843     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3844     InitializationSequence Init(Self, To, Kind, FromPtr);
3845     if (Init.Failed())
3846       return false;
3847 
3848     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3849     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3850   }
3851 
3852   case BTT_IsNothrowAssignable:
3853   case BTT_IsTriviallyAssignable: {
3854     // C++11 [meta.unary.prop]p3:
3855     //   is_trivially_assignable is defined as:
3856     //     is_assignable<T, U>::value is true and the assignment, as defined by
3857     //     is_assignable, is known to call no operation that is not trivial
3858     //
3859     //   is_assignable is defined as:
3860     //     The expression declval<T>() = declval<U>() is well-formed when
3861     //     treated as an unevaluated operand (Clause 5).
3862     //
3863     //   For both, T and U shall be complete types, (possibly cv-qualified)
3864     //   void, or arrays of unknown bound.
3865     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3866         Self.RequireCompleteType(KeyLoc, LhsT,
3867           diag::err_incomplete_type_used_in_type_trait_expr))
3868       return false;
3869     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3870         Self.RequireCompleteType(KeyLoc, RhsT,
3871           diag::err_incomplete_type_used_in_type_trait_expr))
3872       return false;
3873 
3874     // cv void is never assignable.
3875     if (LhsT->isVoidType() || RhsT->isVoidType())
3876       return false;
3877 
3878     // Build expressions that emulate the effect of declval<T>() and
3879     // declval<U>().
3880     if (LhsT->isObjectType() || LhsT->isFunctionType())
3881       LhsT = Self.Context.getRValueReferenceType(LhsT);
3882     if (RhsT->isObjectType() || RhsT->isFunctionType())
3883       RhsT = Self.Context.getRValueReferenceType(RhsT);
3884     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3885                         Expr::getValueKindForType(LhsT));
3886     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3887                         Expr::getValueKindForType(RhsT));
3888 
3889     // Attempt the assignment in an unevaluated context within a SFINAE
3890     // trap at translation unit scope.
3891     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3892     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3893     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3894     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
3895                                         &Rhs);
3896     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3897       return false;
3898 
3899     if (BTT == BTT_IsNothrowAssignable)
3900       return Self.canThrow(Result.get()) == CT_Cannot;
3901 
3902     if (BTT == BTT_IsTriviallyAssignable) {
3903       // Under Objective-C ARC, if the destination has non-trivial Objective-C
3904       // lifetime, this is a non-trivial assignment.
3905       if (Self.getLangOpts().ObjCAutoRefCount &&
3906           hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3907         return false;
3908 
3909       return !Result.get()->hasNonTrivialCall(Self.Context);
3910     }
3911 
3912     llvm_unreachable("unhandled type trait");
3913     return false;
3914   }
3915     default: llvm_unreachable("not a BTT");
3916   }
3917   llvm_unreachable("Unknown type trait or not implemented");
3918 }
3919 
3920 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3921                                      SourceLocation KWLoc,
3922                                      ParsedType Ty,
3923                                      Expr* DimExpr,
3924                                      SourceLocation RParen) {
3925   TypeSourceInfo *TSInfo;
3926   QualType T = GetTypeFromParser(Ty, &TSInfo);
3927   if (!TSInfo)
3928     TSInfo = Context.getTrivialTypeSourceInfo(T);
3929 
3930   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3931 }
3932 
3933 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3934                                            QualType T, Expr *DimExpr,
3935                                            SourceLocation KeyLoc) {
3936   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3937 
3938   switch(ATT) {
3939   case ATT_ArrayRank:
3940     if (T->isArrayType()) {
3941       unsigned Dim = 0;
3942       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3943         ++Dim;
3944         T = AT->getElementType();
3945       }
3946       return Dim;
3947     }
3948     return 0;
3949 
3950   case ATT_ArrayExtent: {
3951     llvm::APSInt Value;
3952     uint64_t Dim;
3953     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3954           diag::err_dimension_expr_not_constant_integer,
3955           false).isInvalid())
3956       return 0;
3957     if (Value.isSigned() && Value.isNegative()) {
3958       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3959         << DimExpr->getSourceRange();
3960       return 0;
3961     }
3962     Dim = Value.getLimitedValue();
3963 
3964     if (T->isArrayType()) {
3965       unsigned D = 0;
3966       bool Matched = false;
3967       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3968         if (Dim == D) {
3969           Matched = true;
3970           break;
3971         }
3972         ++D;
3973         T = AT->getElementType();
3974       }
3975 
3976       if (Matched && T->isArrayType()) {
3977         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3978           return CAT->getSize().getLimitedValue();
3979       }
3980     }
3981     return 0;
3982   }
3983   }
3984   llvm_unreachable("Unknown type trait or not implemented");
3985 }
3986 
3987 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3988                                      SourceLocation KWLoc,
3989                                      TypeSourceInfo *TSInfo,
3990                                      Expr* DimExpr,
3991                                      SourceLocation RParen) {
3992   QualType T = TSInfo->getType();
3993 
3994   // FIXME: This should likely be tracked as an APInt to remove any host
3995   // assumptions about the width of size_t on the target.
3996   uint64_t Value = 0;
3997   if (!T->isDependentType())
3998     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3999 
4000   // While the specification for these traits from the Embarcadero C++
4001   // compiler's documentation says the return type is 'unsigned int', Clang
4002   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4003   // compiler, there is no difference. On several other platforms this is an
4004   // important distinction.
4005   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4006                                           RParen, Context.getSizeType());
4007 }
4008 
4009 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4010                                       SourceLocation KWLoc,
4011                                       Expr *Queried,
4012                                       SourceLocation RParen) {
4013   // If error parsing the expression, ignore.
4014   if (!Queried)
4015     return ExprError();
4016 
4017   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4018 
4019   return Result;
4020 }
4021 
4022 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4023   switch (ET) {
4024   case ET_IsLValueExpr: return E->isLValue();
4025   case ET_IsRValueExpr: return E->isRValue();
4026   }
4027   llvm_unreachable("Expression trait not covered by switch");
4028 }
4029 
4030 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4031                                       SourceLocation KWLoc,
4032                                       Expr *Queried,
4033                                       SourceLocation RParen) {
4034   if (Queried->isTypeDependent()) {
4035     // Delay type-checking for type-dependent expressions.
4036   } else if (Queried->getType()->isPlaceholderType()) {
4037     ExprResult PE = CheckPlaceholderExpr(Queried);
4038     if (PE.isInvalid()) return ExprError();
4039     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
4040   }
4041 
4042   bool Value = EvaluateExpressionTrait(ET, Queried);
4043 
4044   return new (Context)
4045       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
4046 }
4047 
4048 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4049                                             ExprValueKind &VK,
4050                                             SourceLocation Loc,
4051                                             bool isIndirect) {
4052   assert(!LHS.get()->getType()->isPlaceholderType() &&
4053          !RHS.get()->getType()->isPlaceholderType() &&
4054          "placeholders should have been weeded out by now");
4055 
4056   // The LHS undergoes lvalue conversions if this is ->*.
4057   if (isIndirect) {
4058     LHS = DefaultLvalueConversion(LHS.get());
4059     if (LHS.isInvalid()) return QualType();
4060   }
4061 
4062   // The RHS always undergoes lvalue conversions.
4063   RHS = DefaultLvalueConversion(RHS.get());
4064   if (RHS.isInvalid()) return QualType();
4065 
4066   const char *OpSpelling = isIndirect ? "->*" : ".*";
4067   // C++ 5.5p2
4068   //   The binary operator .* [p3: ->*] binds its second operand, which shall
4069   //   be of type "pointer to member of T" (where T is a completely-defined
4070   //   class type) [...]
4071   QualType RHSType = RHS.get()->getType();
4072   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4073   if (!MemPtr) {
4074     Diag(Loc, diag::err_bad_memptr_rhs)
4075       << OpSpelling << RHSType << RHS.get()->getSourceRange();
4076     return QualType();
4077   }
4078 
4079   QualType Class(MemPtr->getClass(), 0);
4080 
4081   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4082   // member pointer points must be completely-defined. However, there is no
4083   // reason for this semantic distinction, and the rule is not enforced by
4084   // other compilers. Therefore, we do not check this property, as it is
4085   // likely to be considered a defect.
4086 
4087   // C++ 5.5p2
4088   //   [...] to its first operand, which shall be of class T or of a class of
4089   //   which T is an unambiguous and accessible base class. [p3: a pointer to
4090   //   such a class]
4091   QualType LHSType = LHS.get()->getType();
4092   if (isIndirect) {
4093     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4094       LHSType = Ptr->getPointeeType();
4095     else {
4096       Diag(Loc, diag::err_bad_memptr_lhs)
4097         << OpSpelling << 1 << LHSType
4098         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4099       return QualType();
4100     }
4101   }
4102 
4103   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4104     // If we want to check the hierarchy, we need a complete type.
4105     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4106                             OpSpelling, (int)isIndirect)) {
4107       return QualType();
4108     }
4109 
4110     if (!IsDerivedFrom(LHSType, Class)) {
4111       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4112         << (int)isIndirect << LHS.get()->getType();
4113       return QualType();
4114     }
4115 
4116     CXXCastPath BasePath;
4117     if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4118                                      SourceRange(LHS.get()->getLocStart(),
4119                                                  RHS.get()->getLocEnd()),
4120                                      &BasePath))
4121       return QualType();
4122 
4123     // Cast LHS to type of use.
4124     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4125     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4126     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
4127                             &BasePath);
4128   }
4129 
4130   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4131     // Diagnose use of pointer-to-member type which when used as
4132     // the functional cast in a pointer-to-member expression.
4133     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4134      return QualType();
4135   }
4136 
4137   // C++ 5.5p2
4138   //   The result is an object or a function of the type specified by the
4139   //   second operand.
4140   // The cv qualifiers are the union of those in the pointer and the left side,
4141   // in accordance with 5.5p5 and 5.2.5.
4142   QualType Result = MemPtr->getPointeeType();
4143   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4144 
4145   // C++0x [expr.mptr.oper]p6:
4146   //   In a .* expression whose object expression is an rvalue, the program is
4147   //   ill-formed if the second operand is a pointer to member function with
4148   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
4149   //   expression is an lvalue, the program is ill-formed if the second operand
4150   //   is a pointer to member function with ref-qualifier &&.
4151   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4152     switch (Proto->getRefQualifier()) {
4153     case RQ_None:
4154       // Do nothing
4155       break;
4156 
4157     case RQ_LValue:
4158       if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4159         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4160           << RHSType << 1 << LHS.get()->getSourceRange();
4161       break;
4162 
4163     case RQ_RValue:
4164       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4165         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4166           << RHSType << 0 << LHS.get()->getSourceRange();
4167       break;
4168     }
4169   }
4170 
4171   // C++ [expr.mptr.oper]p6:
4172   //   The result of a .* expression whose second operand is a pointer
4173   //   to a data member is of the same value category as its
4174   //   first operand. The result of a .* expression whose second
4175   //   operand is a pointer to a member function is a prvalue. The
4176   //   result of an ->* expression is an lvalue if its second operand
4177   //   is a pointer to data member and a prvalue otherwise.
4178   if (Result->isFunctionType()) {
4179     VK = VK_RValue;
4180     return Context.BoundMemberTy;
4181   } else if (isIndirect) {
4182     VK = VK_LValue;
4183   } else {
4184     VK = LHS.get()->getValueKind();
4185   }
4186 
4187   return Result;
4188 }
4189 
4190 /// \brief Try to convert a type to another according to C++0x 5.16p3.
4191 ///
4192 /// This is part of the parameter validation for the ? operator. If either
4193 /// value operand is a class type, the two operands are attempted to be
4194 /// converted to each other. This function does the conversion in one direction.
4195 /// It returns true if the program is ill-formed and has already been diagnosed
4196 /// as such.
4197 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4198                                 SourceLocation QuestionLoc,
4199                                 bool &HaveConversion,
4200                                 QualType &ToType) {
4201   HaveConversion = false;
4202   ToType = To->getType();
4203 
4204   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4205                                                            SourceLocation());
4206   // C++0x 5.16p3
4207   //   The process for determining whether an operand expression E1 of type T1
4208   //   can be converted to match an operand expression E2 of type T2 is defined
4209   //   as follows:
4210   //   -- If E2 is an lvalue:
4211   bool ToIsLvalue = To->isLValue();
4212   if (ToIsLvalue) {
4213     //   E1 can be converted to match E2 if E1 can be implicitly converted to
4214     //   type "lvalue reference to T2", subject to the constraint that in the
4215     //   conversion the reference must bind directly to E1.
4216     QualType T = Self.Context.getLValueReferenceType(ToType);
4217     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4218 
4219     InitializationSequence InitSeq(Self, Entity, Kind, From);
4220     if (InitSeq.isDirectReferenceBinding()) {
4221       ToType = T;
4222       HaveConversion = true;
4223       return false;
4224     }
4225 
4226     if (InitSeq.isAmbiguous())
4227       return InitSeq.Diagnose(Self, Entity, Kind, From);
4228   }
4229 
4230   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
4231   //      -- if E1 and E2 have class type, and the underlying class types are
4232   //         the same or one is a base class of the other:
4233   QualType FTy = From->getType();
4234   QualType TTy = To->getType();
4235   const RecordType *FRec = FTy->getAs<RecordType>();
4236   const RecordType *TRec = TTy->getAs<RecordType>();
4237   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4238                        Self.IsDerivedFrom(FTy, TTy);
4239   if (FRec && TRec &&
4240       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
4241     //         E1 can be converted to match E2 if the class of T2 is the
4242     //         same type as, or a base class of, the class of T1, and
4243     //         [cv2 > cv1].
4244     if (FRec == TRec || FDerivedFromT) {
4245       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4246         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4247         InitializationSequence InitSeq(Self, Entity, Kind, From);
4248         if (InitSeq) {
4249           HaveConversion = true;
4250           return false;
4251         }
4252 
4253         if (InitSeq.isAmbiguous())
4254           return InitSeq.Diagnose(Self, Entity, Kind, From);
4255       }
4256     }
4257 
4258     return false;
4259   }
4260 
4261   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
4262   //        implicitly converted to the type that expression E2 would have
4263   //        if E2 were converted to an rvalue (or the type it has, if E2 is
4264   //        an rvalue).
4265   //
4266   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4267   // to the array-to-pointer or function-to-pointer conversions.
4268   if (!TTy->getAs<TagType>())
4269     TTy = TTy.getUnqualifiedType();
4270 
4271   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4272   InitializationSequence InitSeq(Self, Entity, Kind, From);
4273   HaveConversion = !InitSeq.Failed();
4274   ToType = TTy;
4275   if (InitSeq.isAmbiguous())
4276     return InitSeq.Diagnose(Self, Entity, Kind, From);
4277 
4278   return false;
4279 }
4280 
4281 /// \brief Try to find a common type for two according to C++0x 5.16p5.
4282 ///
4283 /// This is part of the parameter validation for the ? operator. If either
4284 /// value operand is a class type, overload resolution is used to find a
4285 /// conversion to a common type.
4286 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4287                                     SourceLocation QuestionLoc) {
4288   Expr *Args[2] = { LHS.get(), RHS.get() };
4289   OverloadCandidateSet CandidateSet(QuestionLoc,
4290                                     OverloadCandidateSet::CSK_Operator);
4291   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
4292                                     CandidateSet);
4293 
4294   OverloadCandidateSet::iterator Best;
4295   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4296     case OR_Success: {
4297       // We found a match. Perform the conversions on the arguments and move on.
4298       ExprResult LHSRes =
4299         Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4300                                        Best->Conversions[0], Sema::AA_Converting);
4301       if (LHSRes.isInvalid())
4302         break;
4303       LHS = LHSRes;
4304 
4305       ExprResult RHSRes =
4306         Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4307                                        Best->Conversions[1], Sema::AA_Converting);
4308       if (RHSRes.isInvalid())
4309         break;
4310       RHS = RHSRes;
4311       if (Best->Function)
4312         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4313       return false;
4314     }
4315 
4316     case OR_No_Viable_Function:
4317 
4318       // Emit a better diagnostic if one of the expressions is a null pointer
4319       // constant and the other is a pointer type. In this case, the user most
4320       // likely forgot to take the address of the other expression.
4321       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4322         return true;
4323 
4324       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4325         << LHS.get()->getType() << RHS.get()->getType()
4326         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4327       return true;
4328 
4329     case OR_Ambiguous:
4330       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4331         << LHS.get()->getType() << RHS.get()->getType()
4332         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4333       // FIXME: Print the possible common types by printing the return types of
4334       // the viable candidates.
4335       break;
4336 
4337     case OR_Deleted:
4338       llvm_unreachable("Conditional operator has only built-in overloads");
4339   }
4340   return true;
4341 }
4342 
4343 /// \brief Perform an "extended" implicit conversion as returned by
4344 /// TryClassUnification.
4345 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4346   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4347   InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4348                                                            SourceLocation());
4349   Expr *Arg = E.get();
4350   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
4351   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4352   if (Result.isInvalid())
4353     return true;
4354 
4355   E = Result;
4356   return false;
4357 }
4358 
4359 /// \brief Check the operands of ?: under C++ semantics.
4360 ///
4361 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4362 /// extension. In this case, LHS == Cond. (But they're not aliases.)
4363 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4364                                            ExprResult &RHS, ExprValueKind &VK,
4365                                            ExprObjectKind &OK,
4366                                            SourceLocation QuestionLoc) {
4367   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4368   // interface pointers.
4369 
4370   // C++11 [expr.cond]p1
4371   //   The first expression is contextually converted to bool.
4372   if (!Cond.get()->isTypeDependent()) {
4373     ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
4374     if (CondRes.isInvalid())
4375       return QualType();
4376     Cond = CondRes;
4377   }
4378 
4379   // Assume r-value.
4380   VK = VK_RValue;
4381   OK = OK_Ordinary;
4382 
4383   // Either of the arguments dependent?
4384   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4385     return Context.DependentTy;
4386 
4387   // C++11 [expr.cond]p2
4388   //   If either the second or the third operand has type (cv) void, ...
4389   QualType LTy = LHS.get()->getType();
4390   QualType RTy = RHS.get()->getType();
4391   bool LVoid = LTy->isVoidType();
4392   bool RVoid = RTy->isVoidType();
4393   if (LVoid || RVoid) {
4394     //   ... one of the following shall hold:
4395     //   -- The second or the third operand (but not both) is a (possibly
4396     //      parenthesized) throw-expression; the result is of the type
4397     //      and value category of the other.
4398     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
4399     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
4400     if (LThrow != RThrow) {
4401       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
4402       VK = NonThrow->getValueKind();
4403       // DR (no number yet): the result is a bit-field if the
4404       // non-throw-expression operand is a bit-field.
4405       OK = NonThrow->getObjectKind();
4406       return NonThrow->getType();
4407     }
4408 
4409     //   -- Both the second and third operands have type void; the result is of
4410     //      type void and is a prvalue.
4411     if (LVoid && RVoid)
4412       return Context.VoidTy;
4413 
4414     // Neither holds, error.
4415     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4416       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4417       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4418     return QualType();
4419   }
4420 
4421   // Neither is void.
4422 
4423   // C++11 [expr.cond]p3
4424   //   Otherwise, if the second and third operand have different types, and
4425   //   either has (cv) class type [...] an attempt is made to convert each of
4426   //   those operands to the type of the other.
4427   if (!Context.hasSameType(LTy, RTy) &&
4428       (LTy->isRecordType() || RTy->isRecordType())) {
4429     // These return true if a single direction is already ambiguous.
4430     QualType L2RType, R2LType;
4431     bool HaveL2R, HaveR2L;
4432     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4433       return QualType();
4434     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4435       return QualType();
4436 
4437     //   If both can be converted, [...] the program is ill-formed.
4438     if (HaveL2R && HaveR2L) {
4439       Diag(QuestionLoc, diag::err_conditional_ambiguous)
4440         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4441       return QualType();
4442     }
4443 
4444     //   If exactly one conversion is possible, that conversion is applied to
4445     //   the chosen operand and the converted operands are used in place of the
4446     //   original operands for the remainder of this section.
4447     if (HaveL2R) {
4448       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4449         return QualType();
4450       LTy = LHS.get()->getType();
4451     } else if (HaveR2L) {
4452       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4453         return QualType();
4454       RTy = RHS.get()->getType();
4455     }
4456   }
4457 
4458   // C++11 [expr.cond]p3
4459   //   if both are glvalues of the same value category and the same type except
4460   //   for cv-qualification, an attempt is made to convert each of those
4461   //   operands to the type of the other.
4462   ExprValueKind LVK = LHS.get()->getValueKind();
4463   ExprValueKind RVK = RHS.get()->getValueKind();
4464   if (!Context.hasSameType(LTy, RTy) &&
4465       Context.hasSameUnqualifiedType(LTy, RTy) &&
4466       LVK == RVK && LVK != VK_RValue) {
4467     // Since the unqualified types are reference-related and we require the
4468     // result to be as if a reference bound directly, the only conversion
4469     // we can perform is to add cv-qualifiers.
4470     Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4471     Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4472     if (RCVR.isStrictSupersetOf(LCVR)) {
4473       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
4474       LTy = LHS.get()->getType();
4475     }
4476     else if (LCVR.isStrictSupersetOf(RCVR)) {
4477       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
4478       RTy = RHS.get()->getType();
4479     }
4480   }
4481 
4482   // C++11 [expr.cond]p4
4483   //   If the second and third operands are glvalues of the same value
4484   //   category and have the same type, the result is of that type and
4485   //   value category and it is a bit-field if the second or the third
4486   //   operand is a bit-field, or if both are bit-fields.
4487   // We only extend this to bitfields, not to the crazy other kinds of
4488   // l-values.
4489   bool Same = Context.hasSameType(LTy, RTy);
4490   if (Same && LVK == RVK && LVK != VK_RValue &&
4491       LHS.get()->isOrdinaryOrBitFieldObject() &&
4492       RHS.get()->isOrdinaryOrBitFieldObject()) {
4493     VK = LHS.get()->getValueKind();
4494     if (LHS.get()->getObjectKind() == OK_BitField ||
4495         RHS.get()->getObjectKind() == OK_BitField)
4496       OK = OK_BitField;
4497     return LTy;
4498   }
4499 
4500   // C++11 [expr.cond]p5
4501   //   Otherwise, the result is a prvalue. If the second and third operands
4502   //   do not have the same type, and either has (cv) class type, ...
4503   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4504     //   ... overload resolution is used to determine the conversions (if any)
4505     //   to be applied to the operands. If the overload resolution fails, the
4506     //   program is ill-formed.
4507     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4508       return QualType();
4509   }
4510 
4511   // C++11 [expr.cond]p6
4512   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4513   //   conversions are performed on the second and third operands.
4514   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
4515   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
4516   if (LHS.isInvalid() || RHS.isInvalid())
4517     return QualType();
4518   LTy = LHS.get()->getType();
4519   RTy = RHS.get()->getType();
4520 
4521   //   After those conversions, one of the following shall hold:
4522   //   -- The second and third operands have the same type; the result
4523   //      is of that type. If the operands have class type, the result
4524   //      is a prvalue temporary of the result type, which is
4525   //      copy-initialized from either the second operand or the third
4526   //      operand depending on the value of the first operand.
4527   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4528     if (LTy->isRecordType()) {
4529       // The operands have class type. Make a temporary copy.
4530       if (RequireNonAbstractType(QuestionLoc, LTy,
4531                                  diag::err_allocation_of_abstract_type))
4532         return QualType();
4533       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4534 
4535       ExprResult LHSCopy = PerformCopyInitialization(Entity,
4536                                                      SourceLocation(),
4537                                                      LHS);
4538       if (LHSCopy.isInvalid())
4539         return QualType();
4540 
4541       ExprResult RHSCopy = PerformCopyInitialization(Entity,
4542                                                      SourceLocation(),
4543                                                      RHS);
4544       if (RHSCopy.isInvalid())
4545         return QualType();
4546 
4547       LHS = LHSCopy;
4548       RHS = RHSCopy;
4549     }
4550 
4551     return LTy;
4552   }
4553 
4554   // Extension: conditional operator involving vector types.
4555   if (LTy->isVectorType() || RTy->isVectorType())
4556     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4557 
4558   //   -- The second and third operands have arithmetic or enumeration type;
4559   //      the usual arithmetic conversions are performed to bring them to a
4560   //      common type, and the result is of that type.
4561   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4562     UsualArithmeticConversions(LHS, RHS);
4563     if (LHS.isInvalid() || RHS.isInvalid())
4564       return QualType();
4565     return LHS.get()->getType();
4566   }
4567 
4568   //   -- The second and third operands have pointer type, or one has pointer
4569   //      type and the other is a null pointer constant, or both are null
4570   //      pointer constants, at least one of which is non-integral; pointer
4571   //      conversions and qualification conversions are performed to bring them
4572   //      to their composite pointer type. The result is of the composite
4573   //      pointer type.
4574   //   -- The second and third operands have pointer to member type, or one has
4575   //      pointer to member type and the other is a null pointer constant;
4576   //      pointer to member conversions and qualification conversions are
4577   //      performed to bring them to a common type, whose cv-qualification
4578   //      shall match the cv-qualification of either the second or the third
4579   //      operand. The result is of the common type.
4580   bool NonStandardCompositeType = false;
4581   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4582                                  isSFINAEContext() ? nullptr
4583                                                    : &NonStandardCompositeType);
4584   if (!Composite.isNull()) {
4585     if (NonStandardCompositeType)
4586       Diag(QuestionLoc,
4587            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4588         << LTy << RTy << Composite
4589         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4590 
4591     return Composite;
4592   }
4593 
4594   // Similarly, attempt to find composite type of two objective-c pointers.
4595   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4596   if (!Composite.isNull())
4597     return Composite;
4598 
4599   // Check if we are using a null with a non-pointer type.
4600   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4601     return QualType();
4602 
4603   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4604     << LHS.get()->getType() << RHS.get()->getType()
4605     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4606   return QualType();
4607 }
4608 
4609 /// \brief Find a merged pointer type and convert the two expressions to it.
4610 ///
4611 /// This finds the composite pointer type (or member pointer type) for @p E1
4612 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4613 /// type and returns it.
4614 /// It does not emit diagnostics.
4615 ///
4616 /// \param Loc The location of the operator requiring these two expressions to
4617 /// be converted to the composite pointer type.
4618 ///
4619 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4620 /// a non-standard (but still sane) composite type to which both expressions
4621 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4622 /// will be set true.
4623 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4624                                         Expr *&E1, Expr *&E2,
4625                                         bool *NonStandardCompositeType) {
4626   if (NonStandardCompositeType)
4627     *NonStandardCompositeType = false;
4628 
4629   assert(getLangOpts().CPlusPlus && "This function assumes C++");
4630   QualType T1 = E1->getType(), T2 = E2->getType();
4631 
4632   // C++11 5.9p2
4633   //   Pointer conversions and qualification conversions are performed on
4634   //   pointer operands to bring them to their composite pointer type. If
4635   //   one operand is a null pointer constant, the composite pointer type is
4636   //   std::nullptr_t if the other operand is also a null pointer constant or,
4637   //   if the other operand is a pointer, the type of the other operand.
4638   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4639       !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4640     if (T1->isNullPtrType() &&
4641         E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4642       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
4643       return T1;
4644     }
4645     if (T2->isNullPtrType() &&
4646         E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4647       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
4648       return T2;
4649     }
4650     return QualType();
4651   }
4652 
4653   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4654     if (T2->isMemberPointerType())
4655       E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
4656     else
4657       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
4658     return T2;
4659   }
4660   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4661     if (T1->isMemberPointerType())
4662       E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
4663     else
4664       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
4665     return T1;
4666   }
4667 
4668   // Now both have to be pointers or member pointers.
4669   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4670       (!T2->isPointerType() && !T2->isMemberPointerType()))
4671     return QualType();
4672 
4673   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
4674   //   the other has type "pointer to cv2 T" and the composite pointer type is
4675   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4676   //   Otherwise, the composite pointer type is a pointer type similar to the
4677   //   type of one of the operands, with a cv-qualification signature that is
4678   //   the union of the cv-qualification signatures of the operand types.
4679   // In practice, the first part here is redundant; it's subsumed by the second.
4680   // What we do here is, we build the two possible composite types, and try the
4681   // conversions in both directions. If only one works, or if the two composite
4682   // types are the same, we have succeeded.
4683   // FIXME: extended qualifiers?
4684   typedef SmallVector<unsigned, 4> QualifierVector;
4685   QualifierVector QualifierUnion;
4686   typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4687       ContainingClassVector;
4688   ContainingClassVector MemberOfClass;
4689   QualType Composite1 = Context.getCanonicalType(T1),
4690            Composite2 = Context.getCanonicalType(T2);
4691   unsigned NeedConstBefore = 0;
4692   do {
4693     const PointerType *Ptr1, *Ptr2;
4694     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4695         (Ptr2 = Composite2->getAs<PointerType>())) {
4696       Composite1 = Ptr1->getPointeeType();
4697       Composite2 = Ptr2->getPointeeType();
4698 
4699       // If we're allowed to create a non-standard composite type, keep track
4700       // of where we need to fill in additional 'const' qualifiers.
4701       if (NonStandardCompositeType &&
4702           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4703         NeedConstBefore = QualifierUnion.size();
4704 
4705       QualifierUnion.push_back(
4706                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4707       MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
4708       continue;
4709     }
4710 
4711     const MemberPointerType *MemPtr1, *MemPtr2;
4712     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4713         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4714       Composite1 = MemPtr1->getPointeeType();
4715       Composite2 = MemPtr2->getPointeeType();
4716 
4717       // If we're allowed to create a non-standard composite type, keep track
4718       // of where we need to fill in additional 'const' qualifiers.
4719       if (NonStandardCompositeType &&
4720           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4721         NeedConstBefore = QualifierUnion.size();
4722 
4723       QualifierUnion.push_back(
4724                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4725       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4726                                              MemPtr2->getClass()));
4727       continue;
4728     }
4729 
4730     // FIXME: block pointer types?
4731 
4732     // Cannot unwrap any more types.
4733     break;
4734   } while (true);
4735 
4736   if (NeedConstBefore && NonStandardCompositeType) {
4737     // Extension: Add 'const' to qualifiers that come before the first qualifier
4738     // mismatch, so that our (non-standard!) composite type meets the
4739     // requirements of C++ [conv.qual]p4 bullet 3.
4740     for (unsigned I = 0; I != NeedConstBefore; ++I) {
4741       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4742         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4743         *NonStandardCompositeType = true;
4744       }
4745     }
4746   }
4747 
4748   // Rewrap the composites as pointers or member pointers with the union CVRs.
4749   ContainingClassVector::reverse_iterator MOC
4750     = MemberOfClass.rbegin();
4751   for (QualifierVector::reverse_iterator
4752          I = QualifierUnion.rbegin(),
4753          E = QualifierUnion.rend();
4754        I != E; (void)++I, ++MOC) {
4755     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4756     if (MOC->first && MOC->second) {
4757       // Rebuild member pointer type
4758       Composite1 = Context.getMemberPointerType(
4759                                     Context.getQualifiedType(Composite1, Quals),
4760                                     MOC->first);
4761       Composite2 = Context.getMemberPointerType(
4762                                     Context.getQualifiedType(Composite2, Quals),
4763                                     MOC->second);
4764     } else {
4765       // Rebuild pointer type
4766       Composite1
4767         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4768       Composite2
4769         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4770     }
4771   }
4772 
4773   // Try to convert to the first composite pointer type.
4774   InitializedEntity Entity1
4775     = InitializedEntity::InitializeTemporary(Composite1);
4776   InitializationKind Kind
4777     = InitializationKind::CreateCopy(Loc, SourceLocation());
4778   InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4779   InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
4780 
4781   if (E1ToC1 && E2ToC1) {
4782     // Conversion to Composite1 is viable.
4783     if (!Context.hasSameType(Composite1, Composite2)) {
4784       // Composite2 is a different type from Composite1. Check whether
4785       // Composite2 is also viable.
4786       InitializedEntity Entity2
4787         = InitializedEntity::InitializeTemporary(Composite2);
4788       InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4789       InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4790       if (E1ToC2 && E2ToC2) {
4791         // Both Composite1 and Composite2 are viable and are different;
4792         // this is an ambiguity.
4793         return QualType();
4794       }
4795     }
4796 
4797     // Convert E1 to Composite1
4798     ExprResult E1Result
4799       = E1ToC1.Perform(*this, Entity1, Kind, E1);
4800     if (E1Result.isInvalid())
4801       return QualType();
4802     E1 = E1Result.getAs<Expr>();
4803 
4804     // Convert E2 to Composite1
4805     ExprResult E2Result
4806       = E2ToC1.Perform(*this, Entity1, Kind, E2);
4807     if (E2Result.isInvalid())
4808       return QualType();
4809     E2 = E2Result.getAs<Expr>();
4810 
4811     return Composite1;
4812   }
4813 
4814   // Check whether Composite2 is viable.
4815   InitializedEntity Entity2
4816     = InitializedEntity::InitializeTemporary(Composite2);
4817   InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4818   InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4819   if (!E1ToC2 || !E2ToC2)
4820     return QualType();
4821 
4822   // Convert E1 to Composite2
4823   ExprResult E1Result
4824     = E1ToC2.Perform(*this, Entity2, Kind, E1);
4825   if (E1Result.isInvalid())
4826     return QualType();
4827   E1 = E1Result.getAs<Expr>();
4828 
4829   // Convert E2 to Composite2
4830   ExprResult E2Result
4831     = E2ToC2.Perform(*this, Entity2, Kind, E2);
4832   if (E2Result.isInvalid())
4833     return QualType();
4834   E2 = E2Result.getAs<Expr>();
4835 
4836   return Composite2;
4837 }
4838 
4839 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4840   if (!E)
4841     return ExprError();
4842 
4843   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4844 
4845   // If the result is a glvalue, we shouldn't bind it.
4846   if (!E->isRValue())
4847     return E;
4848 
4849   // In ARC, calls that return a retainable type can return retained,
4850   // in which case we have to insert a consuming cast.
4851   if (getLangOpts().ObjCAutoRefCount &&
4852       E->getType()->isObjCRetainableType()) {
4853 
4854     bool ReturnsRetained;
4855 
4856     // For actual calls, we compute this by examining the type of the
4857     // called value.
4858     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4859       Expr *Callee = Call->getCallee()->IgnoreParens();
4860       QualType T = Callee->getType();
4861 
4862       if (T == Context.BoundMemberTy) {
4863         // Handle pointer-to-members.
4864         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4865           T = BinOp->getRHS()->getType();
4866         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4867           T = Mem->getMemberDecl()->getType();
4868       }
4869 
4870       if (const PointerType *Ptr = T->getAs<PointerType>())
4871         T = Ptr->getPointeeType();
4872       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4873         T = Ptr->getPointeeType();
4874       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4875         T = MemPtr->getPointeeType();
4876 
4877       const FunctionType *FTy = T->getAs<FunctionType>();
4878       assert(FTy && "call to value not of function type?");
4879       ReturnsRetained = FTy->getExtInfo().getProducesResult();
4880 
4881     // ActOnStmtExpr arranges things so that StmtExprs of retainable
4882     // type always produce a +1 object.
4883     } else if (isa<StmtExpr>(E)) {
4884       ReturnsRetained = true;
4885 
4886     // We hit this case with the lambda conversion-to-block optimization;
4887     // we don't want any extra casts here.
4888     } else if (isa<CastExpr>(E) &&
4889                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4890       return E;
4891 
4892     // For message sends and property references, we try to find an
4893     // actual method.  FIXME: we should infer retention by selector in
4894     // cases where we don't have an actual method.
4895     } else {
4896       ObjCMethodDecl *D = nullptr;
4897       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4898         D = Send->getMethodDecl();
4899       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4900         D = BoxedExpr->getBoxingMethod();
4901       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4902         D = ArrayLit->getArrayWithObjectsMethod();
4903       } else if (ObjCDictionaryLiteral *DictLit
4904                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
4905         D = DictLit->getDictWithObjectsMethod();
4906       }
4907 
4908       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4909 
4910       // Don't do reclaims on performSelector calls; despite their
4911       // return type, the invoked method doesn't necessarily actually
4912       // return an object.
4913       if (!ReturnsRetained &&
4914           D && D->getMethodFamily() == OMF_performSelector)
4915         return E;
4916     }
4917 
4918     // Don't reclaim an object of Class type.
4919     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4920       return E;
4921 
4922     ExprNeedsCleanups = true;
4923 
4924     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4925                                    : CK_ARCReclaimReturnedObject);
4926     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
4927                                     VK_RValue);
4928   }
4929 
4930   if (!getLangOpts().CPlusPlus)
4931     return E;
4932 
4933   // Search for the base element type (cf. ASTContext::getBaseElementType) with
4934   // a fast path for the common case that the type is directly a RecordType.
4935   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4936   const RecordType *RT = nullptr;
4937   while (!RT) {
4938     switch (T->getTypeClass()) {
4939     case Type::Record:
4940       RT = cast<RecordType>(T);
4941       break;
4942     case Type::ConstantArray:
4943     case Type::IncompleteArray:
4944     case Type::VariableArray:
4945     case Type::DependentSizedArray:
4946       T = cast<ArrayType>(T)->getElementType().getTypePtr();
4947       break;
4948     default:
4949       return E;
4950     }
4951   }
4952 
4953   // That should be enough to guarantee that this type is complete, if we're
4954   // not processing a decltype expression.
4955   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4956   if (RD->isInvalidDecl() || RD->isDependentContext())
4957     return E;
4958 
4959   bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4960   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
4961 
4962   if (Destructor) {
4963     MarkFunctionReferenced(E->getExprLoc(), Destructor);
4964     CheckDestructorAccess(E->getExprLoc(), Destructor,
4965                           PDiag(diag::err_access_dtor_temp)
4966                             << E->getType());
4967     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4968       return ExprError();
4969 
4970     // If destructor is trivial, we can avoid the extra copy.
4971     if (Destructor->isTrivial())
4972       return E;
4973 
4974     // We need a cleanup, but we don't need to remember the temporary.
4975     ExprNeedsCleanups = true;
4976   }
4977 
4978   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
4979   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4980 
4981   if (IsDecltype)
4982     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4983 
4984   return Bind;
4985 }
4986 
4987 ExprResult
4988 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
4989   if (SubExpr.isInvalid())
4990     return ExprError();
4991 
4992   return MaybeCreateExprWithCleanups(SubExpr.get());
4993 }
4994 
4995 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4996   assert(SubExpr && "subexpression can't be null!");
4997 
4998   CleanupVarDeclMarking();
4999 
5000   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5001   assert(ExprCleanupObjects.size() >= FirstCleanup);
5002   assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5003   if (!ExprNeedsCleanups)
5004     return SubExpr;
5005 
5006   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5007                                      ExprCleanupObjects.size() - FirstCleanup);
5008 
5009   Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5010   DiscardCleanupsInEvaluationContext();
5011 
5012   return E;
5013 }
5014 
5015 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5016   assert(SubStmt && "sub-statement can't be null!");
5017 
5018   CleanupVarDeclMarking();
5019 
5020   if (!ExprNeedsCleanups)
5021     return SubStmt;
5022 
5023   // FIXME: In order to attach the temporaries, wrap the statement into
5024   // a StmtExpr; currently this is only used for asm statements.
5025   // This is hacky, either create a new CXXStmtWithTemporaries statement or
5026   // a new AsmStmtWithTemporaries.
5027   CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5028                                                       SourceLocation(),
5029                                                       SourceLocation());
5030   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5031                                    SourceLocation());
5032   return MaybeCreateExprWithCleanups(E);
5033 }
5034 
5035 /// Process the expression contained within a decltype. For such expressions,
5036 /// certain semantic checks on temporaries are delayed until this point, and
5037 /// are omitted for the 'topmost' call in the decltype expression. If the
5038 /// topmost call bound a temporary, strip that temporary off the expression.
5039 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5040   assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5041 
5042   // C++11 [expr.call]p11:
5043   //   If a function call is a prvalue of object type,
5044   // -- if the function call is either
5045   //   -- the operand of a decltype-specifier, or
5046   //   -- the right operand of a comma operator that is the operand of a
5047   //      decltype-specifier,
5048   //   a temporary object is not introduced for the prvalue.
5049 
5050   // Recursively rebuild ParenExprs and comma expressions to strip out the
5051   // outermost CXXBindTemporaryExpr, if any.
5052   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5053     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5054     if (SubExpr.isInvalid())
5055       return ExprError();
5056     if (SubExpr.get() == PE->getSubExpr())
5057       return E;
5058     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
5059   }
5060   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5061     if (BO->getOpcode() == BO_Comma) {
5062       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5063       if (RHS.isInvalid())
5064         return ExprError();
5065       if (RHS.get() == BO->getRHS())
5066         return E;
5067       return new (Context) BinaryOperator(
5068           BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5069           BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
5070     }
5071   }
5072 
5073   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5074   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5075                               : nullptr;
5076   if (TopCall)
5077     E = TopCall;
5078   else
5079     TopBind = nullptr;
5080 
5081   // Disable the special decltype handling now.
5082   ExprEvalContexts.back().IsDecltype = false;
5083 
5084   // In MS mode, don't perform any extra checking of call return types within a
5085   // decltype expression.
5086   if (getLangOpts().MSVCCompat)
5087     return E;
5088 
5089   // Perform the semantic checks we delayed until this point.
5090   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5091        I != N; ++I) {
5092     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5093     if (Call == TopCall)
5094       continue;
5095 
5096     if (CheckCallReturnType(Call->getCallReturnType(),
5097                             Call->getLocStart(),
5098                             Call, Call->getDirectCallee()))
5099       return ExprError();
5100   }
5101 
5102   // Now all relevant types are complete, check the destructors are accessible
5103   // and non-deleted, and annotate them on the temporaries.
5104   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5105        I != N; ++I) {
5106     CXXBindTemporaryExpr *Bind =
5107       ExprEvalContexts.back().DelayedDecltypeBinds[I];
5108     if (Bind == TopBind)
5109       continue;
5110 
5111     CXXTemporary *Temp = Bind->getTemporary();
5112 
5113     CXXRecordDecl *RD =
5114       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5115     CXXDestructorDecl *Destructor = LookupDestructor(RD);
5116     Temp->setDestructor(Destructor);
5117 
5118     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5119     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5120                           PDiag(diag::err_access_dtor_temp)
5121                             << Bind->getType());
5122     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5123       return ExprError();
5124 
5125     // We need a cleanup, but we don't need to remember the temporary.
5126     ExprNeedsCleanups = true;
5127   }
5128 
5129   // Possibly strip off the top CXXBindTemporaryExpr.
5130   return E;
5131 }
5132 
5133 /// Note a set of 'operator->' functions that were used for a member access.
5134 static void noteOperatorArrows(Sema &S,
5135                                ArrayRef<FunctionDecl *> OperatorArrows) {
5136   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5137   // FIXME: Make this configurable?
5138   unsigned Limit = 9;
5139   if (OperatorArrows.size() > Limit) {
5140     // Produce Limit-1 normal notes and one 'skipping' note.
5141     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5142     SkipCount = OperatorArrows.size() - (Limit - 1);
5143   }
5144 
5145   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5146     if (I == SkipStart) {
5147       S.Diag(OperatorArrows[I]->getLocation(),
5148              diag::note_operator_arrows_suppressed)
5149           << SkipCount;
5150       I += SkipCount;
5151     } else {
5152       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5153           << OperatorArrows[I]->getCallResultType();
5154       ++I;
5155     }
5156   }
5157 }
5158 
5159 ExprResult
5160 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
5161                                    tok::TokenKind OpKind, ParsedType &ObjectType,
5162                                    bool &MayBePseudoDestructor) {
5163   // Since this might be a postfix expression, get rid of ParenListExprs.
5164   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5165   if (Result.isInvalid()) return ExprError();
5166   Base = Result.get();
5167 
5168   Result = CheckPlaceholderExpr(Base);
5169   if (Result.isInvalid()) return ExprError();
5170   Base = Result.get();
5171 
5172   QualType BaseType = Base->getType();
5173   MayBePseudoDestructor = false;
5174   if (BaseType->isDependentType()) {
5175     // If we have a pointer to a dependent type and are using the -> operator,
5176     // the object type is the type that the pointer points to. We might still
5177     // have enough information about that type to do something useful.
5178     if (OpKind == tok::arrow)
5179       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5180         BaseType = Ptr->getPointeeType();
5181 
5182     ObjectType = ParsedType::make(BaseType);
5183     MayBePseudoDestructor = true;
5184     return Base;
5185   }
5186 
5187   // C++ [over.match.oper]p8:
5188   //   [...] When operator->returns, the operator-> is applied  to the value
5189   //   returned, with the original second operand.
5190   if (OpKind == tok::arrow) {
5191     QualType StartingType = BaseType;
5192     bool NoArrowOperatorFound = false;
5193     bool FirstIteration = true;
5194     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5195     // The set of types we've considered so far.
5196     llvm::SmallPtrSet<CanQualType,8> CTypes;
5197     SmallVector<FunctionDecl*, 8> OperatorArrows;
5198     CTypes.insert(Context.getCanonicalType(BaseType));
5199 
5200     while (BaseType->isRecordType()) {
5201       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5202         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5203           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5204         noteOperatorArrows(*this, OperatorArrows);
5205         Diag(OpLoc, diag::note_operator_arrow_depth)
5206           << getLangOpts().ArrowDepth;
5207         return ExprError();
5208       }
5209 
5210       Result = BuildOverloadedArrowExpr(
5211           S, Base, OpLoc,
5212           // When in a template specialization and on the first loop iteration,
5213           // potentially give the default diagnostic (with the fixit in a
5214           // separate note) instead of having the error reported back to here
5215           // and giving a diagnostic with a fixit attached to the error itself.
5216           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5217               ? nullptr
5218               : &NoArrowOperatorFound);
5219       if (Result.isInvalid()) {
5220         if (NoArrowOperatorFound) {
5221           if (FirstIteration) {
5222             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5223               << BaseType << 1 << Base->getSourceRange()
5224               << FixItHint::CreateReplacement(OpLoc, ".");
5225             OpKind = tok::period;
5226             break;
5227           }
5228           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5229             << BaseType << Base->getSourceRange();
5230           CallExpr *CE = dyn_cast<CallExpr>(Base);
5231           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
5232             Diag(CD->getLocStart(),
5233                  diag::note_member_reference_arrow_from_operator_arrow);
5234           }
5235         }
5236         return ExprError();
5237       }
5238       Base = Result.get();
5239       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5240         OperatorArrows.push_back(OpCall->getDirectCallee());
5241       BaseType = Base->getType();
5242       CanQualType CBaseType = Context.getCanonicalType(BaseType);
5243       if (!CTypes.insert(CBaseType)) {
5244         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5245         noteOperatorArrows(*this, OperatorArrows);
5246         return ExprError();
5247       }
5248       FirstIteration = false;
5249     }
5250 
5251     if (OpKind == tok::arrow &&
5252         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
5253       BaseType = BaseType->getPointeeType();
5254   }
5255 
5256   // Objective-C properties allow "." access on Objective-C pointer types,
5257   // so adjust the base type to the object type itself.
5258   if (BaseType->isObjCObjectPointerType())
5259     BaseType = BaseType->getPointeeType();
5260 
5261   // C++ [basic.lookup.classref]p2:
5262   //   [...] If the type of the object expression is of pointer to scalar
5263   //   type, the unqualified-id is looked up in the context of the complete
5264   //   postfix-expression.
5265   //
5266   // This also indicates that we could be parsing a pseudo-destructor-name.
5267   // Note that Objective-C class and object types can be pseudo-destructor
5268   // expressions or normal member (ivar or property) access expressions.
5269   if (BaseType->isObjCObjectOrInterfaceType()) {
5270     MayBePseudoDestructor = true;
5271   } else if (!BaseType->isRecordType()) {
5272     ObjectType = ParsedType();
5273     MayBePseudoDestructor = true;
5274     return Base;
5275   }
5276 
5277   // The object type must be complete (or dependent), or
5278   // C++11 [expr.prim.general]p3:
5279   //   Unlike the object expression in other contexts, *this is not required to
5280   //   be of complete type for purposes of class member access (5.2.5) outside
5281   //   the member function body.
5282   if (!BaseType->isDependentType() &&
5283       !isThisOutsideMemberFunctionBody(BaseType) &&
5284       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
5285     return ExprError();
5286 
5287   // C++ [basic.lookup.classref]p2:
5288   //   If the id-expression in a class member access (5.2.5) is an
5289   //   unqualified-id, and the type of the object expression is of a class
5290   //   type C (or of pointer to a class type C), the unqualified-id is looked
5291   //   up in the scope of class C. [...]
5292   ObjectType = ParsedType::make(BaseType);
5293   return Base;
5294 }
5295 
5296 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
5297                                                    Expr *MemExpr) {
5298   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
5299   Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5300     << isa<CXXPseudoDestructorExpr>(MemExpr)
5301     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
5302 
5303   return ActOnCallExpr(/*Scope*/ nullptr,
5304                        MemExpr,
5305                        /*LPLoc*/ ExpectedLParenLoc,
5306                        None,
5307                        /*RPLoc*/ ExpectedLParenLoc);
5308 }
5309 
5310 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
5311                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
5312   if (Base->hasPlaceholderType()) {
5313     ExprResult result = S.CheckPlaceholderExpr(Base);
5314     if (result.isInvalid()) return true;
5315     Base = result.get();
5316   }
5317   ObjectType = Base->getType();
5318 
5319   // C++ [expr.pseudo]p2:
5320   //   The left-hand side of the dot operator shall be of scalar type. The
5321   //   left-hand side of the arrow operator shall be of pointer to scalar type.
5322   //   This scalar type is the object type.
5323   // Note that this is rather different from the normal handling for the
5324   // arrow operator.
5325   if (OpKind == tok::arrow) {
5326     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5327       ObjectType = Ptr->getPointeeType();
5328     } else if (!Base->isTypeDependent()) {
5329       // The user wrote "p->" when she probably meant "p."; fix it.
5330       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5331         << ObjectType << true
5332         << FixItHint::CreateReplacement(OpLoc, ".");
5333       if (S.isSFINAEContext())
5334         return true;
5335 
5336       OpKind = tok::period;
5337     }
5338   }
5339 
5340   return false;
5341 }
5342 
5343 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5344                                            SourceLocation OpLoc,
5345                                            tok::TokenKind OpKind,
5346                                            const CXXScopeSpec &SS,
5347                                            TypeSourceInfo *ScopeTypeInfo,
5348                                            SourceLocation CCLoc,
5349                                            SourceLocation TildeLoc,
5350                                          PseudoDestructorTypeStorage Destructed,
5351                                            bool HasTrailingLParen) {
5352   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5353 
5354   QualType ObjectType;
5355   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5356     return ExprError();
5357 
5358   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5359       !ObjectType->isVectorType()) {
5360     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
5361       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5362     else {
5363       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5364         << ObjectType << Base->getSourceRange();
5365       return ExprError();
5366     }
5367   }
5368 
5369   // C++ [expr.pseudo]p2:
5370   //   [...] The cv-unqualified versions of the object type and of the type
5371   //   designated by the pseudo-destructor-name shall be the same type.
5372   if (DestructedTypeInfo) {
5373     QualType DestructedType = DestructedTypeInfo->getType();
5374     SourceLocation DestructedTypeStart
5375       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5376     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5377       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5378         Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5379           << ObjectType << DestructedType << Base->getSourceRange()
5380           << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5381 
5382         // Recover by setting the destructed type to the object type.
5383         DestructedType = ObjectType;
5384         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5385                                                            DestructedTypeStart);
5386         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5387       } else if (DestructedType.getObjCLifetime() !=
5388                                                 ObjectType.getObjCLifetime()) {
5389 
5390         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5391           // Okay: just pretend that the user provided the correctly-qualified
5392           // type.
5393         } else {
5394           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5395             << ObjectType << DestructedType << Base->getSourceRange()
5396             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5397         }
5398 
5399         // Recover by setting the destructed type to the object type.
5400         DestructedType = ObjectType;
5401         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5402                                                            DestructedTypeStart);
5403         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5404       }
5405     }
5406   }
5407 
5408   // C++ [expr.pseudo]p2:
5409   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5410   //   form
5411   //
5412   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5413   //
5414   //   shall designate the same scalar type.
5415   if (ScopeTypeInfo) {
5416     QualType ScopeType = ScopeTypeInfo->getType();
5417     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5418         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5419 
5420       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5421            diag::err_pseudo_dtor_type_mismatch)
5422         << ObjectType << ScopeType << Base->getSourceRange()
5423         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5424 
5425       ScopeType = QualType();
5426       ScopeTypeInfo = nullptr;
5427     }
5428   }
5429 
5430   Expr *Result
5431     = new (Context) CXXPseudoDestructorExpr(Context, Base,
5432                                             OpKind == tok::arrow, OpLoc,
5433                                             SS.getWithLocInContext(Context),
5434                                             ScopeTypeInfo,
5435                                             CCLoc,
5436                                             TildeLoc,
5437                                             Destructed);
5438 
5439   if (HasTrailingLParen)
5440     return Result;
5441 
5442   return DiagnoseDtorReference(Destructed.getLocation(), Result);
5443 }
5444 
5445 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5446                                            SourceLocation OpLoc,
5447                                            tok::TokenKind OpKind,
5448                                            CXXScopeSpec &SS,
5449                                            UnqualifiedId &FirstTypeName,
5450                                            SourceLocation CCLoc,
5451                                            SourceLocation TildeLoc,
5452                                            UnqualifiedId &SecondTypeName,
5453                                            bool HasTrailingLParen) {
5454   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5455           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5456          "Invalid first type name in pseudo-destructor");
5457   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5458           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5459          "Invalid second type name in pseudo-destructor");
5460 
5461   QualType ObjectType;
5462   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5463     return ExprError();
5464 
5465   // Compute the object type that we should use for name lookup purposes. Only
5466   // record types and dependent types matter.
5467   ParsedType ObjectTypePtrForLookup;
5468   if (!SS.isSet()) {
5469     if (ObjectType->isRecordType())
5470       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5471     else if (ObjectType->isDependentType())
5472       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5473   }
5474 
5475   // Convert the name of the type being destructed (following the ~) into a
5476   // type (with source-location information).
5477   QualType DestructedType;
5478   TypeSourceInfo *DestructedTypeInfo = nullptr;
5479   PseudoDestructorTypeStorage Destructed;
5480   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5481     ParsedType T = getTypeName(*SecondTypeName.Identifier,
5482                                SecondTypeName.StartLocation,
5483                                S, &SS, true, false, ObjectTypePtrForLookup);
5484     if (!T &&
5485         ((SS.isSet() && !computeDeclContext(SS, false)) ||
5486          (!SS.isSet() && ObjectType->isDependentType()))) {
5487       // The name of the type being destroyed is a dependent name, and we
5488       // couldn't find anything useful in scope. Just store the identifier and
5489       // it's location, and we'll perform (qualified) name lookup again at
5490       // template instantiation time.
5491       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5492                                                SecondTypeName.StartLocation);
5493     } else if (!T) {
5494       Diag(SecondTypeName.StartLocation,
5495            diag::err_pseudo_dtor_destructor_non_type)
5496         << SecondTypeName.Identifier << ObjectType;
5497       if (isSFINAEContext())
5498         return ExprError();
5499 
5500       // Recover by assuming we had the right type all along.
5501       DestructedType = ObjectType;
5502     } else
5503       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5504   } else {
5505     // Resolve the template-id to a type.
5506     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5507     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5508                                        TemplateId->NumArgs);
5509     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5510                                        TemplateId->TemplateKWLoc,
5511                                        TemplateId->Template,
5512                                        TemplateId->TemplateNameLoc,
5513                                        TemplateId->LAngleLoc,
5514                                        TemplateArgsPtr,
5515                                        TemplateId->RAngleLoc);
5516     if (T.isInvalid() || !T.get()) {
5517       // Recover by assuming we had the right type all along.
5518       DestructedType = ObjectType;
5519     } else
5520       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5521   }
5522 
5523   // If we've performed some kind of recovery, (re-)build the type source
5524   // information.
5525   if (!DestructedType.isNull()) {
5526     if (!DestructedTypeInfo)
5527       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5528                                                   SecondTypeName.StartLocation);
5529     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5530   }
5531 
5532   // Convert the name of the scope type (the type prior to '::') into a type.
5533   TypeSourceInfo *ScopeTypeInfo = nullptr;
5534   QualType ScopeType;
5535   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5536       FirstTypeName.Identifier) {
5537     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5538       ParsedType T = getTypeName(*FirstTypeName.Identifier,
5539                                  FirstTypeName.StartLocation,
5540                                  S, &SS, true, false, ObjectTypePtrForLookup);
5541       if (!T) {
5542         Diag(FirstTypeName.StartLocation,
5543              diag::err_pseudo_dtor_destructor_non_type)
5544           << FirstTypeName.Identifier << ObjectType;
5545 
5546         if (isSFINAEContext())
5547           return ExprError();
5548 
5549         // Just drop this type. It's unnecessary anyway.
5550         ScopeType = QualType();
5551       } else
5552         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5553     } else {
5554       // Resolve the template-id to a type.
5555       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5556       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5557                                          TemplateId->NumArgs);
5558       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5559                                          TemplateId->TemplateKWLoc,
5560                                          TemplateId->Template,
5561                                          TemplateId->TemplateNameLoc,
5562                                          TemplateId->LAngleLoc,
5563                                          TemplateArgsPtr,
5564                                          TemplateId->RAngleLoc);
5565       if (T.isInvalid() || !T.get()) {
5566         // Recover by dropping this type.
5567         ScopeType = QualType();
5568       } else
5569         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5570     }
5571   }
5572 
5573   if (!ScopeType.isNull() && !ScopeTypeInfo)
5574     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5575                                                   FirstTypeName.StartLocation);
5576 
5577 
5578   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5579                                    ScopeTypeInfo, CCLoc, TildeLoc,
5580                                    Destructed, HasTrailingLParen);
5581 }
5582 
5583 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5584                                            SourceLocation OpLoc,
5585                                            tok::TokenKind OpKind,
5586                                            SourceLocation TildeLoc,
5587                                            const DeclSpec& DS,
5588                                            bool HasTrailingLParen) {
5589   QualType ObjectType;
5590   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5591     return ExprError();
5592 
5593   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5594 
5595   TypeLocBuilder TLB;
5596   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5597   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5598   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5599   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5600 
5601   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5602                                    nullptr, SourceLocation(), TildeLoc,
5603                                    Destructed, HasTrailingLParen);
5604 }
5605 
5606 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5607                                         CXXConversionDecl *Method,
5608                                         bool HadMultipleCandidates) {
5609   if (Method->getParent()->isLambda() &&
5610       Method->getConversionType()->isBlockPointerType()) {
5611     // This is a lambda coversion to block pointer; check if the argument
5612     // is a LambdaExpr.
5613     Expr *SubE = E;
5614     CastExpr *CE = dyn_cast<CastExpr>(SubE);
5615     if (CE && CE->getCastKind() == CK_NoOp)
5616       SubE = CE->getSubExpr();
5617     SubE = SubE->IgnoreParens();
5618     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5619       SubE = BE->getSubExpr();
5620     if (isa<LambdaExpr>(SubE)) {
5621       // For the conversion to block pointer on a lambda expression, we
5622       // construct a special BlockLiteral instead; this doesn't really make
5623       // a difference in ARC, but outside of ARC the resulting block literal
5624       // follows the normal lifetime rules for block literals instead of being
5625       // autoreleased.
5626       DiagnosticErrorTrap Trap(Diags);
5627       ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5628                                                      E->getExprLoc(),
5629                                                      Method, E);
5630       if (Exp.isInvalid())
5631         Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5632       return Exp;
5633     }
5634   }
5635 
5636   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
5637                                           FoundDecl, Method);
5638   if (Exp.isInvalid())
5639     return true;
5640 
5641   MemberExpr *ME =
5642       new (Context) MemberExpr(Exp.get(), /*IsArrow=*/false, Method,
5643                                SourceLocation(), Context.BoundMemberTy,
5644                                VK_RValue, OK_Ordinary);
5645   if (HadMultipleCandidates)
5646     ME->setHadMultipleCandidates(true);
5647   MarkMemberReferenced(ME);
5648 
5649   QualType ResultType = Method->getReturnType();
5650   ExprValueKind VK = Expr::getValueKindForType(ResultType);
5651   ResultType = ResultType.getNonLValueExprType(Context);
5652 
5653   CXXMemberCallExpr *CE =
5654     new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
5655                                     Exp.get()->getLocEnd());
5656   return CE;
5657 }
5658 
5659 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5660                                       SourceLocation RParen) {
5661   CanThrowResult CanThrow = canThrow(Operand);
5662   return new (Context)
5663       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
5664 }
5665 
5666 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5667                                    Expr *Operand, SourceLocation RParen) {
5668   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5669 }
5670 
5671 static bool IsSpecialDiscardedValue(Expr *E) {
5672   // In C++11, discarded-value expressions of a certain form are special,
5673   // according to [expr]p10:
5674   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
5675   //   expression is an lvalue of volatile-qualified type and it has
5676   //   one of the following forms:
5677   E = E->IgnoreParens();
5678 
5679   //   - id-expression (5.1.1),
5680   if (isa<DeclRefExpr>(E))
5681     return true;
5682 
5683   //   - subscripting (5.2.1),
5684   if (isa<ArraySubscriptExpr>(E))
5685     return true;
5686 
5687   //   - class member access (5.2.5),
5688   if (isa<MemberExpr>(E))
5689     return true;
5690 
5691   //   - indirection (5.3.1),
5692   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5693     if (UO->getOpcode() == UO_Deref)
5694       return true;
5695 
5696   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5697     //   - pointer-to-member operation (5.5),
5698     if (BO->isPtrMemOp())
5699       return true;
5700 
5701     //   - comma expression (5.18) where the right operand is one of the above.
5702     if (BO->getOpcode() == BO_Comma)
5703       return IsSpecialDiscardedValue(BO->getRHS());
5704   }
5705 
5706   //   - conditional expression (5.16) where both the second and the third
5707   //     operands are one of the above, or
5708   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5709     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5710            IsSpecialDiscardedValue(CO->getFalseExpr());
5711   // The related edge case of "*x ?: *x".
5712   if (BinaryConditionalOperator *BCO =
5713           dyn_cast<BinaryConditionalOperator>(E)) {
5714     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5715       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5716              IsSpecialDiscardedValue(BCO->getFalseExpr());
5717   }
5718 
5719   // Objective-C++ extensions to the rule.
5720   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5721     return true;
5722 
5723   return false;
5724 }
5725 
5726 /// Perform the conversions required for an expression used in a
5727 /// context that ignores the result.
5728 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5729   if (E->hasPlaceholderType()) {
5730     ExprResult result = CheckPlaceholderExpr(E);
5731     if (result.isInvalid()) return E;
5732     E = result.get();
5733   }
5734 
5735   // C99 6.3.2.1:
5736   //   [Except in specific positions,] an lvalue that does not have
5737   //   array type is converted to the value stored in the
5738   //   designated object (and is no longer an lvalue).
5739   if (E->isRValue()) {
5740     // In C, function designators (i.e. expressions of function type)
5741     // are r-values, but we still want to do function-to-pointer decay
5742     // on them.  This is both technically correct and convenient for
5743     // some clients.
5744     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5745       return DefaultFunctionArrayConversion(E);
5746 
5747     return E;
5748   }
5749 
5750   if (getLangOpts().CPlusPlus)  {
5751     // The C++11 standard defines the notion of a discarded-value expression;
5752     // normally, we don't need to do anything to handle it, but if it is a
5753     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5754     // conversion.
5755     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
5756         E->getType().isVolatileQualified() &&
5757         IsSpecialDiscardedValue(E)) {
5758       ExprResult Res = DefaultLvalueConversion(E);
5759       if (Res.isInvalid())
5760         return E;
5761       E = Res.get();
5762     }
5763     return E;
5764   }
5765 
5766   // GCC seems to also exclude expressions of incomplete enum type.
5767   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5768     if (!T->getDecl()->isComplete()) {
5769       // FIXME: stupid workaround for a codegen bug!
5770       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
5771       return E;
5772     }
5773   }
5774 
5775   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5776   if (Res.isInvalid())
5777     return E;
5778   E = Res.get();
5779 
5780   if (!E->getType()->isVoidType())
5781     RequireCompleteType(E->getExprLoc(), E->getType(),
5782                         diag::err_incomplete_type);
5783   return E;
5784 }
5785 
5786 // If we can unambiguously determine whether Var can never be used
5787 // in a constant expression, return true.
5788 //  - if the variable and its initializer are non-dependent, then
5789 //    we can unambiguously check if the variable is a constant expression.
5790 //  - if the initializer is not value dependent - we can determine whether
5791 //    it can be used to initialize a constant expression.  If Init can not
5792 //    be used to initialize a constant expression we conclude that Var can
5793 //    never be a constant expression.
5794 //  - FXIME: if the initializer is dependent, we can still do some analysis and
5795 //    identify certain cases unambiguously as non-const by using a Visitor:
5796 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
5797 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5798 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5799     ASTContext &Context) {
5800   if (isa<ParmVarDecl>(Var)) return true;
5801   const VarDecl *DefVD = nullptr;
5802 
5803   // If there is no initializer - this can not be a constant expression.
5804   if (!Var->getAnyInitializer(DefVD)) return true;
5805   assert(DefVD);
5806   if (DefVD->isWeak()) return false;
5807   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5808 
5809   Expr *Init = cast<Expr>(Eval->Value);
5810 
5811   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5812     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
5813     // of value-dependent expressions, and use it here to determine whether the
5814     // initializer is a potential constant expression.
5815     return false;
5816   }
5817 
5818   return !IsVariableAConstantExpression(Var, Context);
5819 }
5820 
5821 /// \brief Check if the current lambda has any potential captures
5822 /// that must be captured by any of its enclosing lambdas that are ready to
5823 /// capture. If there is a lambda that can capture a nested
5824 /// potential-capture, go ahead and do so.  Also, check to see if any
5825 /// variables are uncaptureable or do not involve an odr-use so do not
5826 /// need to be captured.
5827 
5828 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
5829     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
5830 
5831   assert(!S.isUnevaluatedContext());
5832   assert(S.CurContext->isDependentContext());
5833   assert(CurrentLSI->CallOperator == S.CurContext &&
5834       "The current call operator must be synchronized with Sema's CurContext");
5835 
5836   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
5837 
5838   ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
5839       S.FunctionScopes.data(), S.FunctionScopes.size());
5840 
5841   // All the potentially captureable variables in the current nested
5842   // lambda (within a generic outer lambda), must be captured by an
5843   // outer lambda that is enclosed within a non-dependent context.
5844   const unsigned NumPotentialCaptures =
5845       CurrentLSI->getNumPotentialVariableCaptures();
5846   for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
5847     Expr *VarExpr = nullptr;
5848     VarDecl *Var = nullptr;
5849     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5850     // If the variable is clearly identified as non-odr-used and the full
5851     // expression is not instantiation dependent, only then do we not
5852     // need to check enclosing lambda's for speculative captures.
5853     // For e.g.:
5854     // Even though 'x' is not odr-used, it should be captured.
5855     // int test() {
5856     //   const int x = 10;
5857     //   auto L = [=](auto a) {
5858     //     (void) +x + a;
5859     //   };
5860     // }
5861     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5862         !IsFullExprInstantiationDependent)
5863       continue;
5864 
5865     // If we have a capture-capable lambda for the variable, go ahead and
5866     // capture the variable in that lambda (and all its enclosing lambdas).
5867     if (const Optional<unsigned> Index =
5868             getStackIndexOfNearestEnclosingCaptureCapableLambda(
5869                 FunctionScopesArrayRef, Var, S)) {
5870       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5871       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
5872                          &FunctionScopeIndexOfCapturableLambda);
5873     }
5874     const bool IsVarNeverAConstantExpression =
5875         VariableCanNeverBeAConstantExpression(Var, S.Context);
5876     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5877       // This full expression is not instantiation dependent or the variable
5878       // can not be used in a constant expression - which means
5879       // this variable must be odr-used here, so diagnose a
5880       // capture violation early, if the variable is un-captureable.
5881       // This is purely for diagnosing errors early.  Otherwise, this
5882       // error would get diagnosed when the lambda becomes capture ready.
5883       QualType CaptureType, DeclRefType;
5884       SourceLocation ExprLoc = VarExpr->getExprLoc();
5885       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5886                           /*EllipsisLoc*/ SourceLocation(),
5887                           /*BuildAndDiagnose*/false, CaptureType,
5888                           DeclRefType, nullptr)) {
5889         // We will never be able to capture this variable, and we need
5890         // to be able to in any and all instantiations, so diagnose it.
5891         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5892                           /*EllipsisLoc*/ SourceLocation(),
5893                           /*BuildAndDiagnose*/true, CaptureType,
5894                           DeclRefType, nullptr);
5895       }
5896     }
5897   }
5898 
5899   // Check if 'this' needs to be captured.
5900   if (CurrentLSI->hasPotentialThisCapture()) {
5901     // If we have a capture-capable lambda for 'this', go ahead and capture
5902     // 'this' in that lambda (and all its enclosing lambdas).
5903     if (const Optional<unsigned> Index =
5904             getStackIndexOfNearestEnclosingCaptureCapableLambda(
5905                 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
5906       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
5907       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5908                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
5909                             &FunctionScopeIndexOfCapturableLambda);
5910     }
5911   }
5912 
5913   // Reset all the potential captures at the end of each full-expression.
5914   CurrentLSI->clearPotentialCaptures();
5915 }
5916 
5917 
5918 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
5919                                      bool DiscardedValue,
5920                                      bool IsConstexpr,
5921                                      bool IsLambdaInitCaptureInitializer) {
5922   ExprResult FullExpr = FE;
5923 
5924   if (!FullExpr.get())
5925     return ExprError();
5926 
5927   // If we are an init-expression in a lambdas init-capture, we should not
5928   // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5929   // containing full-expression is done).
5930   // template<class ... Ts> void test(Ts ... t) {
5931   //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5932   //     return a;
5933   //   }() ...);
5934   // }
5935   // FIXME: This is a hack. It would be better if we pushed the lambda scope
5936   // when we parse the lambda introducer, and teach capturing (but not
5937   // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5938   // corresponding class yet (that is, have LambdaScopeInfo either represent a
5939   // lambda where we've entered the introducer but not the body, or represent a
5940   // lambda where we've entered the body, depending on where the
5941   // parser/instantiation has got to).
5942   if (!IsLambdaInitCaptureInitializer &&
5943       DiagnoseUnexpandedParameterPack(FullExpr.get()))
5944     return ExprError();
5945 
5946   // Top-level expressions default to 'id' when we're in a debugger.
5947   if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
5948       FullExpr.get()->getType() == Context.UnknownAnyTy) {
5949     FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
5950     if (FullExpr.isInvalid())
5951       return ExprError();
5952   }
5953 
5954   if (DiscardedValue) {
5955     FullExpr = CheckPlaceholderExpr(FullExpr.get());
5956     if (FullExpr.isInvalid())
5957       return ExprError();
5958 
5959     FullExpr = IgnoredValueConversions(FullExpr.get());
5960     if (FullExpr.isInvalid())
5961       return ExprError();
5962   }
5963 
5964   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
5965 
5966   // At the end of this full expression (which could be a deeply nested
5967   // lambda), if there is a potential capture within the nested lambda,
5968   // have the outer capture-able lambda try and capture it.
5969   // Consider the following code:
5970   // void f(int, int);
5971   // void f(const int&, double);
5972   // void foo() {
5973   //  const int x = 10, y = 20;
5974   //  auto L = [=](auto a) {
5975   //      auto M = [=](auto b) {
5976   //         f(x, b); <-- requires x to be captured by L and M
5977   //         f(y, a); <-- requires y to be captured by L, but not all Ms
5978   //      };
5979   //   };
5980   // }
5981 
5982   // FIXME: Also consider what happens for something like this that involves
5983   // the gnu-extension statement-expressions or even lambda-init-captures:
5984   //   void f() {
5985   //     const int n = 0;
5986   //     auto L =  [&](auto a) {
5987   //       +n + ({ 0; a; });
5988   //     };
5989   //   }
5990   //
5991   // Here, we see +n, and then the full-expression 0; ends, so we don't
5992   // capture n (and instead remove it from our list of potential captures),
5993   // and then the full-expression +n + ({ 0; }); ends, but it's too late
5994   // for us to see that we need to capture n after all.
5995 
5996   LambdaScopeInfo *const CurrentLSI = getCurLambda();
5997   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
5998   // even if CurContext is not a lambda call operator. Refer to that Bug Report
5999   // for an example of the code that might cause this asynchrony.
6000   // By ensuring we are in the context of a lambda's call operator
6001   // we can fix the bug (we only need to check whether we need to capture
6002   // if we are within a lambda's body); but per the comments in that
6003   // PR, a proper fix would entail :
6004   //   "Alternative suggestion:
6005   //   - Add to Sema an integer holding the smallest (outermost) scope
6006   //     index that we are *lexically* within, and save/restore/set to
6007   //     FunctionScopes.size() in InstantiatingTemplate's
6008   //     constructor/destructor.
6009   //  - Teach the handful of places that iterate over FunctionScopes to
6010   //    stop at the outermost enclosing lexical scope."
6011   const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6012   if (IsInLambdaDeclContext && CurrentLSI &&
6013       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
6014     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
6015                                                               *this);
6016   return MaybeCreateExprWithCleanups(FullExpr);
6017 }
6018 
6019 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6020   if (!FullStmt) return StmtError();
6021 
6022   return MaybeCreateStmtWithCleanups(FullStmt);
6023 }
6024 
6025 Sema::IfExistsResult
6026 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6027                                    CXXScopeSpec &SS,
6028                                    const DeclarationNameInfo &TargetNameInfo) {
6029   DeclarationName TargetName = TargetNameInfo.getName();
6030   if (!TargetName)
6031     return IER_DoesNotExist;
6032 
6033   // If the name itself is dependent, then the result is dependent.
6034   if (TargetName.isDependentName())
6035     return IER_Dependent;
6036 
6037   // Do the redeclaration lookup in the current scope.
6038   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6039                  Sema::NotForRedeclaration);
6040   LookupParsedName(R, S, &SS);
6041   R.suppressDiagnostics();
6042 
6043   switch (R.getResultKind()) {
6044   case LookupResult::Found:
6045   case LookupResult::FoundOverloaded:
6046   case LookupResult::FoundUnresolvedValue:
6047   case LookupResult::Ambiguous:
6048     return IER_Exists;
6049 
6050   case LookupResult::NotFound:
6051     return IER_DoesNotExist;
6052 
6053   case LookupResult::NotFoundInCurrentInstantiation:
6054     return IER_Dependent;
6055   }
6056 
6057   llvm_unreachable("Invalid LookupResult Kind!");
6058 }
6059 
6060 Sema::IfExistsResult
6061 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6062                                    bool IsIfExists, CXXScopeSpec &SS,
6063                                    UnqualifiedId &Name) {
6064   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6065 
6066   // Check for unexpanded parameter packs.
6067   SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6068   collectUnexpandedParameterPacks(SS, Unexpanded);
6069   collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6070   if (!Unexpanded.empty()) {
6071     DiagnoseUnexpandedParameterPacks(KeywordLoc,
6072                                      IsIfExists? UPPC_IfExists
6073                                                : UPPC_IfNotExists,
6074                                      Unexpanded);
6075     return IER_Error;
6076   }
6077 
6078   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6079 }
6080