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