clang API Documentation

SemaExprCXX.cpp
Go to the documentation of this file.
00001 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 ///
00010 /// \file
00011 /// \brief Implements semantic analysis for C++ expressions.
00012 ///
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "TreeTransform.h"
00017 #include "TypeLocBuilder.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/ASTLambda.h"
00020 #include "clang/AST/CXXInheritance.h"
00021 #include "clang/AST/CharUnits.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/EvaluatedExprVisitor.h"
00024 #include "clang/AST/ExprCXX.h"
00025 #include "clang/AST/ExprObjC.h"
00026 #include "clang/AST/RecursiveASTVisitor.h"
00027 #include "clang/AST/TypeLoc.h"
00028 #include "clang/Basic/PartialDiagnostic.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "clang/Lex/Preprocessor.h"
00031 #include "clang/Sema/DeclSpec.h"
00032 #include "clang/Sema/Initialization.h"
00033 #include "clang/Sema/Lookup.h"
00034 #include "clang/Sema/ParsedTemplate.h"
00035 #include "clang/Sema/Scope.h"
00036 #include "clang/Sema/ScopeInfo.h"
00037 #include "clang/Sema/SemaLambda.h"
00038 #include "clang/Sema/TemplateDeduction.h"
00039 #include "llvm/ADT/APInt.h"
00040 #include "llvm/ADT/STLExtras.h"
00041 #include "llvm/Support/ErrorHandling.h"
00042 using namespace clang;
00043 using namespace sema;
00044 
00045 /// \brief Handle the result of the special case name lookup for inheriting
00046 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
00047 /// constructor names in member using declarations, even if 'X' is not the
00048 /// name of the corresponding type.
00049 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
00050                                               SourceLocation NameLoc,
00051                                               IdentifierInfo &Name) {
00052   NestedNameSpecifier *NNS = SS.getScopeRep();
00053 
00054   // Convert the nested-name-specifier into a type.
00055   QualType Type;
00056   switch (NNS->getKind()) {
00057   case NestedNameSpecifier::TypeSpec:
00058   case NestedNameSpecifier::TypeSpecWithTemplate:
00059     Type = QualType(NNS->getAsType(), 0);
00060     break;
00061 
00062   case NestedNameSpecifier::Identifier:
00063     // Strip off the last layer of the nested-name-specifier and build a
00064     // typename type for it.
00065     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
00066     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
00067                                         NNS->getAsIdentifier());
00068     break;
00069 
00070   case NestedNameSpecifier::Global:
00071   case NestedNameSpecifier::Super:
00072   case NestedNameSpecifier::Namespace:
00073   case NestedNameSpecifier::NamespaceAlias:
00074     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
00075   }
00076 
00077   // This reference to the type is located entirely at the location of the
00078   // final identifier in the qualified-id.
00079   return CreateParsedType(Type,
00080                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
00081 }
00082 
00083 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
00084                                    IdentifierInfo &II,
00085                                    SourceLocation NameLoc,
00086                                    Scope *S, CXXScopeSpec &SS,
00087                                    ParsedType ObjectTypePtr,
00088                                    bool EnteringContext) {
00089   // Determine where to perform name lookup.
00090 
00091   // FIXME: This area of the standard is very messy, and the current
00092   // wording is rather unclear about which scopes we search for the
00093   // destructor name; see core issues 399 and 555. Issue 399 in
00094   // particular shows where the current description of destructor name
00095   // lookup is completely out of line with existing practice, e.g.,
00096   // this appears to be ill-formed:
00097   //
00098   //   namespace N {
00099   //     template <typename T> struct S {
00100   //       ~S();
00101   //     };
00102   //   }
00103   //
00104   //   void f(N::S<int>* s) {
00105   //     s->N::S<int>::~S();
00106   //   }
00107   //
00108   // See also PR6358 and PR6359.
00109   // For this reason, we're currently only doing the C++03 version of this
00110   // code; the C++0x version has to wait until we get a proper spec.
00111   QualType SearchType;
00112   DeclContext *LookupCtx = nullptr;
00113   bool isDependent = false;
00114   bool LookInScope = false;
00115 
00116   // If we have an object type, it's because we are in a
00117   // pseudo-destructor-expression or a member access expression, and
00118   // we know what type we're looking for.
00119   if (ObjectTypePtr)
00120     SearchType = GetTypeFromParser(ObjectTypePtr);
00121 
00122   if (SS.isSet()) {
00123     NestedNameSpecifier *NNS = SS.getScopeRep();
00124 
00125     bool AlreadySearched = false;
00126     bool LookAtPrefix = true;
00127     // C++11 [basic.lookup.qual]p6:
00128     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
00129     //   the type-names are looked up as types in the scope designated by the
00130     //   nested-name-specifier. Similarly, in a qualified-id of the form:
00131     //
00132     //     nested-name-specifier[opt] class-name :: ~ class-name
00133     //
00134     //   the second class-name is looked up in the same scope as the first.
00135     //
00136     // Here, we determine whether the code below is permitted to look at the
00137     // prefix of the nested-name-specifier.
00138     DeclContext *DC = computeDeclContext(SS, EnteringContext);
00139     if (DC && DC->isFileContext()) {
00140       AlreadySearched = true;
00141       LookupCtx = DC;
00142       isDependent = false;
00143     } else if (DC && isa<CXXRecordDecl>(DC)) {
00144       LookAtPrefix = false;
00145       LookInScope = true;
00146     }
00147 
00148     // The second case from the C++03 rules quoted further above.
00149     NestedNameSpecifier *Prefix = nullptr;
00150     if (AlreadySearched) {
00151       // Nothing left to do.
00152     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
00153       CXXScopeSpec PrefixSS;
00154       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
00155       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
00156       isDependent = isDependentScopeSpecifier(PrefixSS);
00157     } else if (ObjectTypePtr) {
00158       LookupCtx = computeDeclContext(SearchType);
00159       isDependent = SearchType->isDependentType();
00160     } else {
00161       LookupCtx = computeDeclContext(SS, EnteringContext);
00162       isDependent = LookupCtx && LookupCtx->isDependentContext();
00163     }
00164   } else if (ObjectTypePtr) {
00165     // C++ [basic.lookup.classref]p3:
00166     //   If the unqualified-id is ~type-name, the type-name is looked up
00167     //   in the context of the entire postfix-expression. If the type T
00168     //   of the object expression is of a class type C, the type-name is
00169     //   also looked up in the scope of class C. At least one of the
00170     //   lookups shall find a name that refers to (possibly
00171     //   cv-qualified) T.
00172     LookupCtx = computeDeclContext(SearchType);
00173     isDependent = SearchType->isDependentType();
00174     assert((isDependent || !SearchType->isIncompleteType()) &&
00175            "Caller should have completed object type");
00176 
00177     LookInScope = true;
00178   } else {
00179     // Perform lookup into the current scope (only).
00180     LookInScope = true;
00181   }
00182 
00183   TypeDecl *NonMatchingTypeDecl = nullptr;
00184   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
00185   for (unsigned Step = 0; Step != 2; ++Step) {
00186     // Look for the name first in the computed lookup context (if we
00187     // have one) and, if that fails to find a match, in the scope (if
00188     // we're allowed to look there).
00189     Found.clear();
00190     if (Step == 0 && LookupCtx)
00191       LookupQualifiedName(Found, LookupCtx);
00192     else if (Step == 1 && LookInScope && S)
00193       LookupName(Found, S);
00194     else
00195       continue;
00196 
00197     // FIXME: Should we be suppressing ambiguities here?
00198     if (Found.isAmbiguous())
00199       return ParsedType();
00200 
00201     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
00202       QualType T = Context.getTypeDeclType(Type);
00203       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
00204 
00205       if (SearchType.isNull() || SearchType->isDependentType() ||
00206           Context.hasSameUnqualifiedType(T, SearchType)) {
00207         // We found our type!
00208 
00209         return CreateParsedType(T,
00210                                 Context.getTrivialTypeSourceInfo(T, NameLoc));
00211       }
00212 
00213       if (!SearchType.isNull())
00214         NonMatchingTypeDecl = Type;
00215     }
00216 
00217     // If the name that we found is a class template name, and it is
00218     // the same name as the template name in the last part of the
00219     // nested-name-specifier (if present) or the object type, then
00220     // this is the destructor for that class.
00221     // FIXME: This is a workaround until we get real drafting for core
00222     // issue 399, for which there isn't even an obvious direction.
00223     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
00224       QualType MemberOfType;
00225       if (SS.isSet()) {
00226         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
00227           // Figure out the type of the context, if it has one.
00228           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
00229             MemberOfType = Context.getTypeDeclType(Record);
00230         }
00231       }
00232       if (MemberOfType.isNull())
00233         MemberOfType = SearchType;
00234 
00235       if (MemberOfType.isNull())
00236         continue;
00237 
00238       // We're referring into a class template specialization. If the
00239       // class template we found is the same as the template being
00240       // specialized, we found what we are looking for.
00241       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
00242         if (ClassTemplateSpecializationDecl *Spec
00243               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
00244           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
00245                 Template->getCanonicalDecl())
00246             return CreateParsedType(
00247                 MemberOfType,
00248                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
00249         }
00250 
00251         continue;
00252       }
00253 
00254       // We're referring to an unresolved class template
00255       // specialization. Determine whether we class template we found
00256       // is the same as the template being specialized or, if we don't
00257       // know which template is being specialized, that it at least
00258       // has the same name.
00259       if (const TemplateSpecializationType *SpecType
00260             = MemberOfType->getAs<TemplateSpecializationType>()) {
00261         TemplateName SpecName = SpecType->getTemplateName();
00262 
00263         // The class template we found is the same template being
00264         // specialized.
00265         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
00266           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
00267             return CreateParsedType(
00268                 MemberOfType,
00269                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
00270 
00271           continue;
00272         }
00273 
00274         // The class template we found has the same name as the
00275         // (dependent) template name being specialized.
00276         if (DependentTemplateName *DepTemplate
00277                                     = SpecName.getAsDependentTemplateName()) {
00278           if (DepTemplate->isIdentifier() &&
00279               DepTemplate->getIdentifier() == Template->getIdentifier())
00280             return CreateParsedType(
00281                 MemberOfType,
00282                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
00283 
00284           continue;
00285         }
00286       }
00287     }
00288   }
00289 
00290   if (isDependent) {
00291     // We didn't find our type, but that's okay: it's dependent
00292     // anyway.
00293     
00294     // FIXME: What if we have no nested-name-specifier?
00295     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
00296                                    SS.getWithLocInContext(Context),
00297                                    II, NameLoc);
00298     return ParsedType::make(T);
00299   }
00300 
00301   if (NonMatchingTypeDecl) {
00302     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
00303     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
00304       << T << SearchType;
00305     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
00306       << T;
00307   } else if (ObjectTypePtr)
00308     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
00309       << &II;
00310   else {
00311     SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
00312                                           diag::err_destructor_class_name);
00313     if (S) {
00314       const DeclContext *Ctx = S->getEntity();
00315       if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
00316         DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
00317                                                  Class->getNameAsString());
00318     }
00319   }
00320 
00321   return ParsedType();
00322 }
00323 
00324 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
00325     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
00326       return ParsedType();
00327     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype 
00328            && "only get destructor types from declspecs");
00329     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
00330     QualType SearchType = GetTypeFromParser(ObjectType);
00331     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
00332       return ParsedType::make(T);
00333     }
00334       
00335     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
00336       << T << SearchType;
00337     return ParsedType();
00338 }
00339 
00340 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
00341                                   const UnqualifiedId &Name) {
00342   assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
00343 
00344   if (!SS.isValid())
00345     return false;
00346 
00347   switch (SS.getScopeRep()->getKind()) {
00348   case NestedNameSpecifier::Identifier:
00349   case NestedNameSpecifier::TypeSpec:
00350   case NestedNameSpecifier::TypeSpecWithTemplate:
00351     // Per C++11 [over.literal]p2, literal operators can only be declared at
00352     // namespace scope. Therefore, this unqualified-id cannot name anything.
00353     // Reject it early, because we have no AST representation for this in the
00354     // case where the scope is dependent.
00355     Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
00356       << SS.getScopeRep();
00357     return true;
00358 
00359   case NestedNameSpecifier::Global:
00360   case NestedNameSpecifier::Super:
00361   case NestedNameSpecifier::Namespace:
00362   case NestedNameSpecifier::NamespaceAlias:
00363     return false;
00364   }
00365 
00366   llvm_unreachable("unknown nested name specifier kind");
00367 }
00368 
00369 /// \brief Build a C++ typeid expression with a type operand.
00370 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
00371                                 SourceLocation TypeidLoc,
00372                                 TypeSourceInfo *Operand,
00373                                 SourceLocation RParenLoc) {
00374   // C++ [expr.typeid]p4:
00375   //   The top-level cv-qualifiers of the lvalue expression or the type-id
00376   //   that is the operand of typeid are always ignored.
00377   //   If the type of the type-id is a class type or a reference to a class
00378   //   type, the class shall be completely-defined.
00379   Qualifiers Quals;
00380   QualType T
00381     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
00382                                       Quals);
00383   if (T->getAs<RecordType>() &&
00384       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
00385     return ExprError();
00386 
00387   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
00388                                      SourceRange(TypeidLoc, RParenLoc));
00389 }
00390 
00391 /// \brief Build a C++ typeid expression with an expression operand.
00392 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
00393                                 SourceLocation TypeidLoc,
00394                                 Expr *E,
00395                                 SourceLocation RParenLoc) {
00396   if (E && !E->isTypeDependent()) {
00397     if (E->getType()->isPlaceholderType()) {
00398       ExprResult result = CheckPlaceholderExpr(E);
00399       if (result.isInvalid()) return ExprError();
00400       E = result.get();
00401     }
00402 
00403     QualType T = E->getType();
00404     if (const RecordType *RecordT = T->getAs<RecordType>()) {
00405       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
00406       // C++ [expr.typeid]p3:
00407       //   [...] If the type of the expression is a class type, the class
00408       //   shall be completely-defined.
00409       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
00410         return ExprError();
00411 
00412       // C++ [expr.typeid]p3:
00413       //   When typeid is applied to an expression other than an glvalue of a
00414       //   polymorphic class type [...] [the] expression is an unevaluated
00415       //   operand. [...]
00416       if (RecordD->isPolymorphic() && E->isGLValue()) {
00417         // The subexpression is potentially evaluated; switch the context
00418         // and recheck the subexpression.
00419         ExprResult Result = TransformToPotentiallyEvaluated(E);
00420         if (Result.isInvalid()) return ExprError();
00421         E = Result.get();
00422 
00423         // We require a vtable to query the type at run time.
00424         MarkVTableUsed(TypeidLoc, RecordD);
00425       }
00426     }
00427 
00428     // C++ [expr.typeid]p4:
00429     //   [...] If the type of the type-id is a reference to a possibly
00430     //   cv-qualified type, the result of the typeid expression refers to a
00431     //   std::type_info object representing the cv-unqualified referenced
00432     //   type.
00433     Qualifiers Quals;
00434     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
00435     if (!Context.hasSameType(T, UnqualT)) {
00436       T = UnqualT;
00437       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
00438     }
00439   }
00440 
00441   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
00442                                      SourceRange(TypeidLoc, RParenLoc));
00443 }
00444 
00445 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
00446 ExprResult
00447 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
00448                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
00449   // Find the std::type_info type.
00450   if (!getStdNamespace())
00451     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00452 
00453   if (!CXXTypeInfoDecl) {
00454     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
00455     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
00456     LookupQualifiedName(R, getStdNamespace());
00457     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
00458     // Microsoft's typeinfo doesn't have type_info in std but in the global
00459     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
00460     if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
00461       LookupQualifiedName(R, Context.getTranslationUnitDecl());
00462       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
00463     }
00464     if (!CXXTypeInfoDecl)
00465       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
00466   }
00467 
00468   if (!getLangOpts().RTTI) {
00469     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
00470   }
00471 
00472   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
00473 
00474   if (isType) {
00475     // The operand is a type; handle it as such.
00476     TypeSourceInfo *TInfo = nullptr;
00477     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
00478                                    &TInfo);
00479     if (T.isNull())
00480       return ExprError();
00481 
00482     if (!TInfo)
00483       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
00484 
00485     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
00486   }
00487 
00488   // The operand is an expression.
00489   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
00490 }
00491 
00492 /// \brief Build a Microsoft __uuidof expression with a type operand.
00493 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
00494                                 SourceLocation TypeidLoc,
00495                                 TypeSourceInfo *Operand,
00496                                 SourceLocation RParenLoc) {
00497   if (!Operand->getType()->isDependentType()) {
00498     bool HasMultipleGUIDs = false;
00499     if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
00500                                           &HasMultipleGUIDs)) {
00501       if (HasMultipleGUIDs)
00502         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
00503       else
00504         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
00505     }
00506   }
00507 
00508   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
00509                                      SourceRange(TypeidLoc, RParenLoc));
00510 }
00511 
00512 /// \brief Build a Microsoft __uuidof expression with an expression operand.
00513 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
00514                                 SourceLocation TypeidLoc,
00515                                 Expr *E,
00516                                 SourceLocation RParenLoc) {
00517   if (!E->getType()->isDependentType()) {
00518     bool HasMultipleGUIDs = false;
00519     if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
00520         !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
00521       if (HasMultipleGUIDs)
00522         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
00523       else
00524         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
00525     }
00526   }
00527 
00528   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
00529                                      SourceRange(TypeidLoc, RParenLoc));
00530 }
00531 
00532 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
00533 ExprResult
00534 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
00535                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
00536   // If MSVCGuidDecl has not been cached, do the lookup.
00537   if (!MSVCGuidDecl) {
00538     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
00539     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
00540     LookupQualifiedName(R, Context.getTranslationUnitDecl());
00541     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
00542     if (!MSVCGuidDecl)
00543       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
00544   }
00545 
00546   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
00547 
00548   if (isType) {
00549     // The operand is a type; handle it as such.
00550     TypeSourceInfo *TInfo = nullptr;
00551     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
00552                                    &TInfo);
00553     if (T.isNull())
00554       return ExprError();
00555 
00556     if (!TInfo)
00557       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
00558 
00559     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
00560   }
00561 
00562   // The operand is an expression.
00563   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
00564 }
00565 
00566 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
00567 ExprResult
00568 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
00569   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
00570          "Unknown C++ Boolean value!");
00571   return new (Context)
00572       CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
00573 }
00574 
00575 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
00576 ExprResult
00577 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
00578   return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
00579 }
00580 
00581 /// ActOnCXXThrow - Parse throw expressions.
00582 ExprResult
00583 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
00584   bool IsThrownVarInScope = false;
00585   if (Ex) {
00586     // C++0x [class.copymove]p31:
00587     //   When certain criteria are met, an implementation is allowed to omit the 
00588     //   copy/move construction of a class object [...]
00589     //
00590     //     - in a throw-expression, when the operand is the name of a 
00591     //       non-volatile automatic object (other than a function or catch-
00592     //       clause parameter) whose scope does not extend beyond the end of the 
00593     //       innermost enclosing try-block (if there is one), the copy/move 
00594     //       operation from the operand to the exception object (15.1) can be 
00595     //       omitted by constructing the automatic object directly into the 
00596     //       exception object
00597     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
00598       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
00599         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
00600           for( ; S; S = S->getParent()) {
00601             if (S->isDeclScope(Var)) {
00602               IsThrownVarInScope = true;
00603               break;
00604             }
00605             
00606             if (S->getFlags() &
00607                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
00608                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
00609                  Scope::TryScope))
00610               break;
00611           }
00612         }
00613       }
00614   }
00615   
00616   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
00617 }
00618 
00619 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 
00620                                bool IsThrownVarInScope) {
00621   // Don't report an error if 'throw' is used in system headers.
00622   if (!getLangOpts().CXXExceptions &&
00623       !getSourceManager().isInSystemHeader(OpLoc))
00624     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
00625 
00626   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
00627     Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
00628 
00629   if (Ex && !Ex->isTypeDependent()) {
00630     ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
00631     if (ExRes.isInvalid())
00632       return ExprError();
00633     Ex = ExRes.get();
00634   }
00635   
00636   return new (Context)
00637       CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
00638 }
00639 
00640 /// CheckCXXThrowOperand - Validate the operand of a throw.
00641 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
00642                                       bool IsThrownVarInScope) {
00643   // C++ [except.throw]p3:
00644   //   A throw-expression initializes a temporary object, called the exception
00645   //   object, the type of which is determined by removing any top-level
00646   //   cv-qualifiers from the static type of the operand of throw and adjusting
00647   //   the type from "array of T" or "function returning T" to "pointer to T"
00648   //   or "pointer to function returning T", [...]
00649   if (E->getType().hasQualifiers())
00650     E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
00651                           E->getValueKind()).get();
00652 
00653   ExprResult Res = DefaultFunctionArrayConversion(E);
00654   if (Res.isInvalid())
00655     return ExprError();
00656   E = Res.get();
00657 
00658   //   If the type of the exception would be an incomplete type or a pointer
00659   //   to an incomplete type other than (cv) void the program is ill-formed.
00660   QualType Ty = E->getType();
00661   bool isPointer = false;
00662   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
00663     Ty = Ptr->getPointeeType();
00664     isPointer = true;
00665   }
00666   if (!isPointer || !Ty->isVoidType()) {
00667     if (RequireCompleteType(ThrowLoc, Ty,
00668                             isPointer? diag::err_throw_incomplete_ptr
00669                                      : diag::err_throw_incomplete,
00670                             E->getSourceRange()))
00671       return ExprError();
00672 
00673     if (RequireNonAbstractType(ThrowLoc, E->getType(),
00674                                diag::err_throw_abstract_type, E))
00675       return ExprError();
00676   }
00677 
00678   // Initialize the exception result.  This implicitly weeds out
00679   // abstract types or types with inaccessible copy constructors.
00680   
00681   // C++0x [class.copymove]p31:
00682   //   When certain criteria are met, an implementation is allowed to omit the 
00683   //   copy/move construction of a class object [...]
00684   //
00685   //     - in a throw-expression, when the operand is the name of a 
00686   //       non-volatile automatic object (other than a function or catch-clause 
00687   //       parameter) whose scope does not extend beyond the end of the 
00688   //       innermost enclosing try-block (if there is one), the copy/move 
00689   //       operation from the operand to the exception object (15.1) can be 
00690   //       omitted by constructing the automatic object directly into the 
00691   //       exception object
00692   const VarDecl *NRVOVariable = nullptr;
00693   if (IsThrownVarInScope)
00694     NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
00695 
00696   InitializedEntity Entity =
00697       InitializedEntity::InitializeException(ThrowLoc, E->getType(),
00698                                              /*NRVO=*/NRVOVariable != nullptr);
00699   Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
00700                                         QualType(), E,
00701                                         IsThrownVarInScope);
00702   if (Res.isInvalid())
00703     return ExprError();
00704   E = Res.get();
00705 
00706   // If the exception has class type, we need additional handling.
00707   const RecordType *RecordTy = Ty->getAs<RecordType>();
00708   if (!RecordTy)
00709     return E;
00710   CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
00711 
00712   // If we are throwing a polymorphic class type or pointer thereof,
00713   // exception handling will make use of the vtable.
00714   MarkVTableUsed(ThrowLoc, RD);
00715 
00716   // If a pointer is thrown, the referenced object will not be destroyed.
00717   if (isPointer)
00718     return E;
00719 
00720   // If the class has a destructor, we must be able to call it.
00721   if (RD->hasIrrelevantDestructor())
00722     return E;
00723 
00724   CXXDestructorDecl *Destructor = LookupDestructor(RD);
00725   if (!Destructor)
00726     return E;
00727 
00728   MarkFunctionReferenced(E->getExprLoc(), Destructor);
00729   CheckDestructorAccess(E->getExprLoc(), Destructor,
00730                         PDiag(diag::err_access_dtor_exception) << Ty);
00731   if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
00732     return ExprError();
00733   return E;
00734 }
00735 
00736 QualType Sema::getCurrentThisType() {
00737   DeclContext *DC = getFunctionLevelDeclContext();
00738   QualType ThisTy = CXXThisTypeOverride;
00739   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
00740     if (method && method->isInstance())
00741       ThisTy = method->getThisType(Context);
00742   }
00743   if (ThisTy.isNull()) {
00744     if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
00745         CurContext->getParent()->getParent()->isRecord()) {
00746       // This is a generic lambda call operator that is being instantiated
00747       // within a default initializer - so use the enclosing class as 'this'.
00748       // There is no enclosing member function to retrieve the 'this' pointer
00749       // from.
00750       QualType ClassTy = Context.getTypeDeclType(
00751           cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
00752       // There are no cv-qualifiers for 'this' within default initializers, 
00753       // per [expr.prim.general]p4.
00754       return Context.getPointerType(ClassTy);
00755     }
00756   }
00757   return ThisTy;
00758 }
00759 
00760 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 
00761                                          Decl *ContextDecl,
00762                                          unsigned CXXThisTypeQuals,
00763                                          bool Enabled) 
00764   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
00765 {
00766   if (!Enabled || !ContextDecl)
00767     return;
00768 
00769   CXXRecordDecl *Record = nullptr;
00770   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
00771     Record = Template->getTemplatedDecl();
00772   else
00773     Record = cast<CXXRecordDecl>(ContextDecl);
00774     
00775   S.CXXThisTypeOverride
00776     = S.Context.getPointerType(
00777         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
00778   
00779   this->Enabled = true;
00780 }
00781 
00782 
00783 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
00784   if (Enabled) {
00785     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
00786   }
00787 }
00788 
00789 static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
00790                          QualType ThisTy, SourceLocation Loc) {
00791   FieldDecl *Field
00792     = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, ThisTy,
00793                         Context.getTrivialTypeSourceInfo(ThisTy, Loc),
00794                         nullptr, false, ICIS_NoInit);
00795   Field->setImplicit(true);
00796   Field->setAccess(AS_private);
00797   RD->addDecl(Field);
00798   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
00799 }
00800 
00801 bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit, 
00802     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
00803   // We don't need to capture this in an unevaluated context.
00804   if (isUnevaluatedContext() && !Explicit)
00805     return true;
00806 
00807   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
00808     *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
00809  // Otherwise, check that we can capture 'this'.
00810   unsigned NumClosures = 0;
00811   for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
00812     if (CapturingScopeInfo *CSI =
00813             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
00814       if (CSI->CXXThisCaptureIndex != 0) {
00815         // 'this' is already being captured; there isn't anything more to do.
00816         break;
00817       }
00818       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
00819       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
00820         // This context can't implicitly capture 'this'; fail out.
00821         if (BuildAndDiagnose)
00822           Diag(Loc, diag::err_this_capture) << Explicit;
00823         return true;
00824       }
00825       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
00826           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
00827           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
00828           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
00829           Explicit) {
00830         // This closure can capture 'this'; continue looking upwards.
00831         NumClosures++;
00832         Explicit = false;
00833         continue;
00834       }
00835       // This context can't implicitly capture 'this'; fail out.
00836       if (BuildAndDiagnose)
00837         Diag(Loc, diag::err_this_capture) << Explicit;
00838       return true;
00839     }
00840     break;
00841   }
00842   if (!BuildAndDiagnose) return false;
00843   // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
00844   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
00845   // contexts.
00846   for (unsigned idx = MaxFunctionScopesIndex; NumClosures; 
00847       --idx, --NumClosures) {
00848     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
00849     Expr *ThisExpr = nullptr;
00850     QualType ThisTy = getCurrentThisType();
00851     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
00852       // For lambda expressions, build a field and an initializing expression.
00853       ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
00854     else if (CapturedRegionScopeInfo *RSI
00855         = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
00856       ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
00857 
00858     bool isNested = NumClosures > 1;
00859     CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
00860   }
00861   return false;
00862 }
00863 
00864 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
00865   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
00866   /// is a non-lvalue expression whose value is the address of the object for
00867   /// which the function is called.
00868 
00869   QualType ThisTy = getCurrentThisType();
00870   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
00871 
00872   CheckCXXThisCapture(Loc);
00873   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
00874 }
00875 
00876 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
00877   // If we're outside the body of a member function, then we'll have a specified
00878   // type for 'this'.
00879   if (CXXThisTypeOverride.isNull())
00880     return false;
00881   
00882   // Determine whether we're looking into a class that's currently being
00883   // defined.
00884   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
00885   return Class && Class->isBeingDefined();
00886 }
00887 
00888 ExprResult
00889 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
00890                                 SourceLocation LParenLoc,
00891                                 MultiExprArg exprs,
00892                                 SourceLocation RParenLoc) {
00893   if (!TypeRep)
00894     return ExprError();
00895 
00896   TypeSourceInfo *TInfo;
00897   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
00898   if (!TInfo)
00899     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
00900 
00901   return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
00902 }
00903 
00904 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
00905 /// Can be interpreted either as function-style casting ("int(x)")
00906 /// or class type construction ("ClassType(x,y,z)")
00907 /// or creation of a value-initialized type ("int()").
00908 ExprResult
00909 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
00910                                 SourceLocation LParenLoc,
00911                                 MultiExprArg Exprs,
00912                                 SourceLocation RParenLoc) {
00913   QualType Ty = TInfo->getType();
00914   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
00915 
00916   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
00917     return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
00918                                               RParenLoc);
00919   }
00920 
00921   bool ListInitialization = LParenLoc.isInvalid();
00922   assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
00923          && "List initialization must have initializer list as expression.");
00924   SourceRange FullRange = SourceRange(TyBeginLoc,
00925       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
00926 
00927   // C++ [expr.type.conv]p1:
00928   // If the expression list is a single expression, the type conversion
00929   // expression is equivalent (in definedness, and if defined in meaning) to the
00930   // corresponding cast expression.
00931   if (Exprs.size() == 1 && !ListInitialization) {
00932     Expr *Arg = Exprs[0];
00933     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
00934   }
00935 
00936   QualType ElemTy = Ty;
00937   if (Ty->isArrayType()) {
00938     if (!ListInitialization)
00939       return ExprError(Diag(TyBeginLoc,
00940                             diag::err_value_init_for_array_type) << FullRange);
00941     ElemTy = Context.getBaseElementType(Ty);
00942   }
00943 
00944   if (!Ty->isVoidType() &&
00945       RequireCompleteType(TyBeginLoc, ElemTy,
00946                           diag::err_invalid_incomplete_type_use, FullRange))
00947     return ExprError();
00948 
00949   if (RequireNonAbstractType(TyBeginLoc, Ty,
00950                              diag::err_allocation_of_abstract_type))
00951     return ExprError();
00952 
00953   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
00954   InitializationKind Kind =
00955       Exprs.size() ? ListInitialization
00956       ? InitializationKind::CreateDirectList(TyBeginLoc)
00957       : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
00958       : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
00959   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
00960   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
00961 
00962   if (Result.isInvalid() || !ListInitialization)
00963     return Result;
00964 
00965   Expr *Inner = Result.get();
00966   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
00967     Inner = BTE->getSubExpr();
00968   if (isa<InitListExpr>(Inner)) {
00969     // If the list-initialization doesn't involve a constructor call, we'll get
00970     // the initializer-list (with corrected type) back, but that's not what we
00971     // want, since it will be treated as an initializer list in further
00972     // processing. Explicitly insert a cast here.
00973     QualType ResultType = Result.get()->getType();
00974     Result = CXXFunctionalCastExpr::Create(
00975         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
00976         CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
00977   }
00978 
00979   // FIXME: Improve AST representation?
00980   return Result;
00981 }
00982 
00983 /// doesUsualArrayDeleteWantSize - Answers whether the usual
00984 /// operator delete[] for the given type has a size_t parameter.
00985 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
00986                                          QualType allocType) {
00987   const RecordType *record =
00988     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
00989   if (!record) return false;
00990 
00991   // Try to find an operator delete[] in class scope.
00992 
00993   DeclarationName deleteName =
00994     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
00995   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
00996   S.LookupQualifiedName(ops, record->getDecl());
00997 
00998   // We're just doing this for information.
00999   ops.suppressDiagnostics();
01000 
01001   // Very likely: there's no operator delete[].
01002   if (ops.empty()) return false;
01003 
01004   // If it's ambiguous, it should be illegal to call operator delete[]
01005   // on this thing, so it doesn't matter if we allocate extra space or not.
01006   if (ops.isAmbiguous()) return false;
01007 
01008   LookupResult::Filter filter = ops.makeFilter();
01009   while (filter.hasNext()) {
01010     NamedDecl *del = filter.next()->getUnderlyingDecl();
01011 
01012     // C++0x [basic.stc.dynamic.deallocation]p2:
01013     //   A template instance is never a usual deallocation function,
01014     //   regardless of its signature.
01015     if (isa<FunctionTemplateDecl>(del)) {
01016       filter.erase();
01017       continue;
01018     }
01019 
01020     // C++0x [basic.stc.dynamic.deallocation]p2:
01021     //   If class T does not declare [an operator delete[] with one
01022     //   parameter] but does declare a member deallocation function
01023     //   named operator delete[] with exactly two parameters, the
01024     //   second of which has type std::size_t, then this function
01025     //   is a usual deallocation function.
01026     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
01027       filter.erase();
01028       continue;
01029     }
01030   }
01031   filter.done();
01032 
01033   if (!ops.isSingleResult()) return false;
01034 
01035   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
01036   return (del->getNumParams() == 2);
01037 }
01038 
01039 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
01040 ///
01041 /// E.g.:
01042 /// @code new (memory) int[size][4] @endcode
01043 /// or
01044 /// @code ::new Foo(23, "hello") @endcode
01045 ///
01046 /// \param StartLoc The first location of the expression.
01047 /// \param UseGlobal True if 'new' was prefixed with '::'.
01048 /// \param PlacementLParen Opening paren of the placement arguments.
01049 /// \param PlacementArgs Placement new arguments.
01050 /// \param PlacementRParen Closing paren of the placement arguments.
01051 /// \param TypeIdParens If the type is in parens, the source range.
01052 /// \param D The type to be allocated, as well as array dimensions.
01053 /// \param Initializer The initializing expression or initializer-list, or null
01054 ///   if there is none.
01055 ExprResult
01056 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
01057                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
01058                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
01059                   Declarator &D, Expr *Initializer) {
01060   bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
01061 
01062   Expr *ArraySize = nullptr;
01063   // If the specified type is an array, unwrap it and save the expression.
01064   if (D.getNumTypeObjects() > 0 &&
01065       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
01066      DeclaratorChunk &Chunk = D.getTypeObject(0);
01067     if (TypeContainsAuto)
01068       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
01069         << D.getSourceRange());
01070     if (Chunk.Arr.hasStatic)
01071       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
01072         << D.getSourceRange());
01073     if (!Chunk.Arr.NumElts)
01074       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
01075         << D.getSourceRange());
01076 
01077     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
01078     D.DropFirstTypeObject();
01079   }
01080 
01081   // Every dimension shall be of constant size.
01082   if (ArraySize) {
01083     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
01084       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
01085         break;
01086 
01087       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
01088       if (Expr *NumElts = (Expr *)Array.NumElts) {
01089         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
01090           if (getLangOpts().CPlusPlus14) {
01091       // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
01092       //   shall be a converted constant expression (5.19) of type std::size_t
01093       //   and shall evaluate to a strictly positive value.
01094             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
01095             assert(IntWidth && "Builtin type of size 0?");
01096             llvm::APSInt Value(IntWidth);
01097             Array.NumElts
01098              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
01099                                                 CCEK_NewExpr)
01100                  .get();
01101           } else {
01102             Array.NumElts
01103               = VerifyIntegerConstantExpression(NumElts, nullptr,
01104                                                 diag::err_new_array_nonconst)
01105                   .get();
01106           }
01107           if (!Array.NumElts)
01108             return ExprError();
01109         }
01110       }
01111     }
01112   }
01113 
01114   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
01115   QualType AllocType = TInfo->getType();
01116   if (D.isInvalidType())
01117     return ExprError();
01118 
01119   SourceRange DirectInitRange;
01120   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
01121     DirectInitRange = List->getSourceRange();
01122 
01123   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
01124                      PlacementLParen,
01125                      PlacementArgs,
01126                      PlacementRParen,
01127                      TypeIdParens,
01128                      AllocType,
01129                      TInfo,
01130                      ArraySize,
01131                      DirectInitRange,
01132                      Initializer,
01133                      TypeContainsAuto);
01134 }
01135 
01136 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
01137                                        Expr *Init) {
01138   if (!Init)
01139     return true;
01140   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
01141     return PLE->getNumExprs() == 0;
01142   if (isa<ImplicitValueInitExpr>(Init))
01143     return true;
01144   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
01145     return !CCE->isListInitialization() &&
01146            CCE->getConstructor()->isDefaultConstructor();
01147   else if (Style == CXXNewExpr::ListInit) {
01148     assert(isa<InitListExpr>(Init) &&
01149            "Shouldn't create list CXXConstructExprs for arrays.");
01150     return true;
01151   }
01152   return false;
01153 }
01154 
01155 ExprResult
01156 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
01157                   SourceLocation PlacementLParen,
01158                   MultiExprArg PlacementArgs,
01159                   SourceLocation PlacementRParen,
01160                   SourceRange TypeIdParens,
01161                   QualType AllocType,
01162                   TypeSourceInfo *AllocTypeInfo,
01163                   Expr *ArraySize,
01164                   SourceRange DirectInitRange,
01165                   Expr *Initializer,
01166                   bool TypeMayContainAuto) {
01167   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
01168   SourceLocation StartLoc = Range.getBegin();
01169 
01170   CXXNewExpr::InitializationStyle initStyle;
01171   if (DirectInitRange.isValid()) {
01172     assert(Initializer && "Have parens but no initializer.");
01173     initStyle = CXXNewExpr::CallInit;
01174   } else if (Initializer && isa<InitListExpr>(Initializer))
01175     initStyle = CXXNewExpr::ListInit;
01176   else {
01177     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
01178             isa<CXXConstructExpr>(Initializer)) &&
01179            "Initializer expression that cannot have been implicitly created.");
01180     initStyle = CXXNewExpr::NoInit;
01181   }
01182 
01183   Expr **Inits = &Initializer;
01184   unsigned NumInits = Initializer ? 1 : 0;
01185   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
01186     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
01187     Inits = List->getExprs();
01188     NumInits = List->getNumExprs();
01189   }
01190 
01191   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
01192   if (TypeMayContainAuto && AllocType->isUndeducedType()) {
01193     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
01194       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
01195                        << AllocType << TypeRange);
01196     if (initStyle == CXXNewExpr::ListInit ||
01197         (NumInits == 1 && isa<InitListExpr>(Inits[0])))
01198       return ExprError(Diag(Inits[0]->getLocStart(),
01199                             diag::err_auto_new_list_init)
01200                        << AllocType << TypeRange);
01201     if (NumInits > 1) {
01202       Expr *FirstBad = Inits[1];
01203       return ExprError(Diag(FirstBad->getLocStart(),
01204                             diag::err_auto_new_ctor_multiple_expressions)
01205                        << AllocType << TypeRange);
01206     }
01207     Expr *Deduce = Inits[0];
01208     QualType DeducedType;
01209     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
01210       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
01211                        << AllocType << Deduce->getType()
01212                        << TypeRange << Deduce->getSourceRange());
01213     if (DeducedType.isNull())
01214       return ExprError();
01215     AllocType = DeducedType;
01216   }
01217 
01218   // Per C++0x [expr.new]p5, the type being constructed may be a
01219   // typedef of an array type.
01220   if (!ArraySize) {
01221     if (const ConstantArrayType *Array
01222                               = Context.getAsConstantArrayType(AllocType)) {
01223       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
01224                                          Context.getSizeType(),
01225                                          TypeRange.getEnd());
01226       AllocType = Array->getElementType();
01227     }
01228   }
01229 
01230   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
01231     return ExprError();
01232 
01233   if (initStyle == CXXNewExpr::ListInit &&
01234       isStdInitializerList(AllocType, nullptr)) {
01235     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
01236          diag::warn_dangling_std_initializer_list)
01237         << /*at end of FE*/0 << Inits[0]->getSourceRange();
01238   }
01239 
01240   // In ARC, infer 'retaining' for the allocated 
01241   if (getLangOpts().ObjCAutoRefCount &&
01242       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
01243       AllocType->isObjCLifetimeType()) {
01244     AllocType = Context.getLifetimeQualifiedType(AllocType,
01245                                     AllocType->getObjCARCImplicitLifetime());
01246   }
01247 
01248   QualType ResultType = Context.getPointerType(AllocType);
01249     
01250   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
01251     ExprResult result = CheckPlaceholderExpr(ArraySize);
01252     if (result.isInvalid()) return ExprError();
01253     ArraySize = result.get();
01254   }
01255   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
01256   //   integral or enumeration type with a non-negative value."
01257   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
01258   //   enumeration type, or a class type for which a single non-explicit
01259   //   conversion function to integral or unscoped enumeration type exists.
01260   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
01261   //   std::size_t.
01262   if (ArraySize && !ArraySize->isTypeDependent()) {
01263     ExprResult ConvertedSize;
01264     if (getLangOpts().CPlusPlus14) {
01265       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
01266 
01267       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
01268             AA_Converting);
01269 
01270       if (!ConvertedSize.isInvalid() && 
01271           ArraySize->getType()->getAs<RecordType>())
01272         // Diagnose the compatibility of this conversion.
01273         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
01274           << ArraySize->getType() << 0 << "'size_t'";
01275     } else {
01276       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
01277       protected:
01278         Expr *ArraySize;
01279   
01280       public:
01281         SizeConvertDiagnoser(Expr *ArraySize)
01282             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
01283               ArraySize(ArraySize) {}
01284 
01285         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
01286                                              QualType T) override {
01287           return S.Diag(Loc, diag::err_array_size_not_integral)
01288                    << S.getLangOpts().CPlusPlus11 << T;
01289         }
01290 
01291         SemaDiagnosticBuilder diagnoseIncomplete(
01292             Sema &S, SourceLocation Loc, QualType T) override {
01293           return S.Diag(Loc, diag::err_array_size_incomplete_type)
01294                    << T << ArraySize->getSourceRange();
01295         }
01296 
01297         SemaDiagnosticBuilder diagnoseExplicitConv(
01298             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
01299           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
01300         }
01301 
01302         SemaDiagnosticBuilder noteExplicitConv(
01303             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
01304           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
01305                    << ConvTy->isEnumeralType() << ConvTy;
01306         }
01307 
01308         SemaDiagnosticBuilder diagnoseAmbiguous(
01309             Sema &S, SourceLocation Loc, QualType T) override {
01310           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
01311         }
01312 
01313         SemaDiagnosticBuilder noteAmbiguous(
01314             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
01315           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
01316                    << ConvTy->isEnumeralType() << ConvTy;
01317         }
01318 
01319         virtual SemaDiagnosticBuilder diagnoseConversion(
01320             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
01321           return S.Diag(Loc,
01322                         S.getLangOpts().CPlusPlus11
01323                           ? diag::warn_cxx98_compat_array_size_conversion
01324                           : diag::ext_array_size_conversion)
01325                    << T << ConvTy->isEnumeralType() << ConvTy;
01326         }
01327       } SizeDiagnoser(ArraySize);
01328 
01329       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
01330                                                           SizeDiagnoser);
01331     }
01332     if (ConvertedSize.isInvalid())
01333       return ExprError();
01334 
01335     ArraySize = ConvertedSize.get();
01336     QualType SizeType = ArraySize->getType();
01337 
01338     if (!SizeType->isIntegralOrUnscopedEnumerationType())
01339       return ExprError();
01340 
01341     // C++98 [expr.new]p7:
01342     //   The expression in a direct-new-declarator shall have integral type
01343     //   with a non-negative value.
01344     //
01345     // Let's see if this is a constant < 0. If so, we reject it out of
01346     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
01347     // array type.
01348     //
01349     // Note: such a construct has well-defined semantics in C++11: it throws
01350     // std::bad_array_new_length.
01351     if (!ArraySize->isValueDependent()) {
01352       llvm::APSInt Value;
01353       // We've already performed any required implicit conversion to integer or
01354       // unscoped enumeration type.
01355       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
01356         if (Value < llvm::APSInt(
01357                         llvm::APInt::getNullValue(Value.getBitWidth()),
01358                                  Value.isUnsigned())) {
01359           if (getLangOpts().CPlusPlus11)
01360             Diag(ArraySize->getLocStart(),
01361                  diag::warn_typecheck_negative_array_new_size)
01362               << ArraySize->getSourceRange();
01363           else
01364             return ExprError(Diag(ArraySize->getLocStart(),
01365                                   diag::err_typecheck_negative_array_size)
01366                              << ArraySize->getSourceRange());
01367         } else if (!AllocType->isDependentType()) {
01368           unsigned ActiveSizeBits =
01369             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
01370           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
01371             if (getLangOpts().CPlusPlus11)
01372               Diag(ArraySize->getLocStart(),
01373                    diag::warn_array_new_too_large)
01374                 << Value.toString(10)
01375                 << ArraySize->getSourceRange();
01376             else
01377               return ExprError(Diag(ArraySize->getLocStart(),
01378                                     diag::err_array_too_large)
01379                                << Value.toString(10)
01380                                << ArraySize->getSourceRange());
01381           }
01382         }
01383       } else if (TypeIdParens.isValid()) {
01384         // Can't have dynamic array size when the type-id is in parentheses.
01385         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
01386           << ArraySize->getSourceRange()
01387           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
01388           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
01389 
01390         TypeIdParens = SourceRange();
01391       }
01392     }
01393 
01394     // Note that we do *not* convert the argument in any way.  It can
01395     // be signed, larger than size_t, whatever.
01396   }
01397 
01398   FunctionDecl *OperatorNew = nullptr;
01399   FunctionDecl *OperatorDelete = nullptr;
01400 
01401   if (!AllocType->isDependentType() &&
01402       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
01403       FindAllocationFunctions(StartLoc,
01404                               SourceRange(PlacementLParen, PlacementRParen),
01405                               UseGlobal, AllocType, ArraySize, PlacementArgs,
01406                               OperatorNew, OperatorDelete))
01407     return ExprError();
01408 
01409   // If this is an array allocation, compute whether the usual array
01410   // deallocation function for the type has a size_t parameter.
01411   bool UsualArrayDeleteWantsSize = false;
01412   if (ArraySize && !AllocType->isDependentType())
01413     UsualArrayDeleteWantsSize
01414       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
01415 
01416   SmallVector<Expr *, 8> AllPlaceArgs;
01417   if (OperatorNew) {
01418     const FunctionProtoType *Proto =
01419         OperatorNew->getType()->getAs<FunctionProtoType>();
01420     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
01421                                                     : VariadicDoesNotApply;
01422 
01423     // We've already converted the placement args, just fill in any default
01424     // arguments. Skip the first parameter because we don't have a corresponding
01425     // argument.
01426     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
01427                                PlacementArgs, AllPlaceArgs, CallType))
01428       return ExprError();
01429 
01430     if (!AllPlaceArgs.empty())
01431       PlacementArgs = AllPlaceArgs;
01432 
01433     // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
01434     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
01435 
01436     // FIXME: Missing call to CheckFunctionCall or equivalent
01437   }
01438 
01439   // Warn if the type is over-aligned and is being allocated by global operator
01440   // new.
01441   if (PlacementArgs.empty() && OperatorNew &&
01442       (OperatorNew->isImplicit() ||
01443        getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
01444     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
01445       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
01446       if (Align > SuitableAlign)
01447         Diag(StartLoc, diag::warn_overaligned_type)
01448             << AllocType
01449             << unsigned(Align / Context.getCharWidth())
01450             << unsigned(SuitableAlign / Context.getCharWidth());
01451     }
01452   }
01453 
01454   QualType InitType = AllocType;
01455   // Array 'new' can't have any initializers except empty parentheses.
01456   // Initializer lists are also allowed, in C++11. Rely on the parser for the
01457   // dialect distinction.
01458   if (ResultType->isArrayType() || ArraySize) {
01459     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
01460       SourceRange InitRange(Inits[0]->getLocStart(),
01461                             Inits[NumInits - 1]->getLocEnd());
01462       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
01463       return ExprError();
01464     }
01465     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
01466       // We do the initialization typechecking against the array type
01467       // corresponding to the number of initializers + 1 (to also check
01468       // default-initialization).
01469       unsigned NumElements = ILE->getNumInits() + 1;
01470       InitType = Context.getConstantArrayType(AllocType,
01471           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
01472                                               ArrayType::Normal, 0);
01473     }
01474   }
01475 
01476   // If we can perform the initialization, and we've not already done so,
01477   // do it now.
01478   if (!AllocType->isDependentType() &&
01479       !Expr::hasAnyTypeDependentArguments(
01480           llvm::makeArrayRef(Inits, NumInits))) {
01481     // C++11 [expr.new]p15:
01482     //   A new-expression that creates an object of type T initializes that
01483     //   object as follows:
01484     InitializationKind Kind
01485     //     - If the new-initializer is omitted, the object is default-
01486     //       initialized (8.5); if no initialization is performed,
01487     //       the object has indeterminate value
01488       = initStyle == CXXNewExpr::NoInit
01489           ? InitializationKind::CreateDefault(TypeRange.getBegin())
01490     //     - Otherwise, the new-initializer is interpreted according to the
01491     //       initialization rules of 8.5 for direct-initialization.
01492           : initStyle == CXXNewExpr::ListInit
01493               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
01494               : InitializationKind::CreateDirect(TypeRange.getBegin(),
01495                                                  DirectInitRange.getBegin(),
01496                                                  DirectInitRange.getEnd());
01497 
01498     InitializedEntity Entity
01499       = InitializedEntity::InitializeNew(StartLoc, InitType);
01500     InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
01501     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
01502                                           MultiExprArg(Inits, NumInits));
01503     if (FullInit.isInvalid())
01504       return ExprError();
01505 
01506     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
01507     // we don't want the initialized object to be destructed.
01508     if (CXXBindTemporaryExpr *Binder =
01509             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
01510       FullInit = Binder->getSubExpr();
01511 
01512     Initializer = FullInit.get();
01513   }
01514 
01515   // Mark the new and delete operators as referenced.
01516   if (OperatorNew) {
01517     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
01518       return ExprError();
01519     MarkFunctionReferenced(StartLoc, OperatorNew);
01520   }
01521   if (OperatorDelete) {
01522     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
01523       return ExprError();
01524     MarkFunctionReferenced(StartLoc, OperatorDelete);
01525   }
01526 
01527   // C++0x [expr.new]p17:
01528   //   If the new expression creates an array of objects of class type,
01529   //   access and ambiguity control are done for the destructor.
01530   QualType BaseAllocType = Context.getBaseElementType(AllocType);
01531   if (ArraySize && !BaseAllocType->isDependentType()) {
01532     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
01533       if (CXXDestructorDecl *dtor = LookupDestructor(
01534               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
01535         MarkFunctionReferenced(StartLoc, dtor);
01536         CheckDestructorAccess(StartLoc, dtor, 
01537                               PDiag(diag::err_access_dtor)
01538                                 << BaseAllocType);
01539         if (DiagnoseUseOfDecl(dtor, StartLoc))
01540           return ExprError();
01541       }
01542     }
01543   }
01544 
01545   return new (Context)
01546       CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
01547                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
01548                  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
01549                  Range, DirectInitRange);
01550 }
01551 
01552 /// \brief Checks that a type is suitable as the allocated type
01553 /// in a new-expression.
01554 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
01555                               SourceRange R) {
01556   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
01557   //   abstract class type or array thereof.
01558   if (AllocType->isFunctionType())
01559     return Diag(Loc, diag::err_bad_new_type)
01560       << AllocType << 0 << R;
01561   else if (AllocType->isReferenceType())
01562     return Diag(Loc, diag::err_bad_new_type)
01563       << AllocType << 1 << R;
01564   else if (!AllocType->isDependentType() &&
01565            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
01566     return true;
01567   else if (RequireNonAbstractType(Loc, AllocType,
01568                                   diag::err_allocation_of_abstract_type))
01569     return true;
01570   else if (AllocType->isVariablyModifiedType())
01571     return Diag(Loc, diag::err_variably_modified_new_type)
01572              << AllocType;
01573   else if (unsigned AddressSpace = AllocType.getAddressSpace())
01574     return Diag(Loc, diag::err_address_space_qualified_new)
01575       << AllocType.getUnqualifiedType() << AddressSpace;
01576   else if (getLangOpts().ObjCAutoRefCount) {
01577     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
01578       QualType BaseAllocType = Context.getBaseElementType(AT);
01579       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
01580           BaseAllocType->isObjCLifetimeType())
01581         return Diag(Loc, diag::err_arc_new_array_without_ownership)
01582           << BaseAllocType;
01583     }
01584   }
01585            
01586   return false;
01587 }
01588 
01589 /// \brief Determine whether the given function is a non-placement
01590 /// deallocation function.
01591 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
01592   if (FD->isInvalidDecl())
01593     return false;
01594 
01595   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
01596     return Method->isUsualDeallocationFunction();
01597 
01598   if (FD->getOverloadedOperator() != OO_Delete &&
01599       FD->getOverloadedOperator() != OO_Array_Delete)
01600     return false;
01601 
01602   if (FD->getNumParams() == 1)
01603     return true;
01604 
01605   return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
01606          S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
01607                                           S.Context.getSizeType());
01608 }
01609 
01610 /// FindAllocationFunctions - Finds the overloads of operator new and delete
01611 /// that are appropriate for the allocation.
01612 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
01613                                    bool UseGlobal, QualType AllocType,
01614                                    bool IsArray, MultiExprArg PlaceArgs,
01615                                    FunctionDecl *&OperatorNew,
01616                                    FunctionDecl *&OperatorDelete) {
01617   // --- Choosing an allocation function ---
01618   // C++ 5.3.4p8 - 14 & 18
01619   // 1) If UseGlobal is true, only look in the global scope. Else, also look
01620   //   in the scope of the allocated class.
01621   // 2) If an array size is given, look for operator new[], else look for
01622   //   operator new.
01623   // 3) The first argument is always size_t. Append the arguments from the
01624   //   placement form.
01625 
01626   SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
01627   // We don't care about the actual value of this argument.
01628   // FIXME: Should the Sema create the expression and embed it in the syntax
01629   // tree? Or should the consumer just recalculate the value?
01630   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
01631                       Context.getTargetInfo().getPointerWidth(0)),
01632                       Context.getSizeType(),
01633                       SourceLocation());
01634   AllocArgs[0] = &Size;
01635   std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
01636 
01637   // C++ [expr.new]p8:
01638   //   If the allocated type is a non-array type, the allocation
01639   //   function's name is operator new and the deallocation function's
01640   //   name is operator delete. If the allocated type is an array
01641   //   type, the allocation function's name is operator new[] and the
01642   //   deallocation function's name is operator delete[].
01643   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
01644                                         IsArray ? OO_Array_New : OO_New);
01645   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
01646                                         IsArray ? OO_Array_Delete : OO_Delete);
01647 
01648   QualType AllocElemType = Context.getBaseElementType(AllocType);
01649 
01650   if (AllocElemType->isRecordType() && !UseGlobal) {
01651     CXXRecordDecl *Record
01652       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
01653     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
01654                                /*AllowMissing=*/true, OperatorNew))
01655       return true;
01656   }
01657 
01658   if (!OperatorNew) {
01659     // Didn't find a member overload. Look for a global one.
01660     DeclareGlobalNewDelete();
01661     DeclContext *TUDecl = Context.getTranslationUnitDecl();
01662     bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
01663     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
01664                                /*AllowMissing=*/FallbackEnabled, OperatorNew,
01665                                /*Diagnose=*/!FallbackEnabled)) {
01666       if (!FallbackEnabled)
01667         return true;
01668 
01669       // MSVC will fall back on trying to find a matching global operator new
01670       // if operator new[] cannot be found.  Also, MSVC will leak by not
01671       // generating a call to operator delete or operator delete[], but we
01672       // will not replicate that bug.
01673       NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
01674       DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
01675       if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
01676                                /*AllowMissing=*/false, OperatorNew))
01677       return true;
01678     }
01679   }
01680 
01681   // We don't need an operator delete if we're running under
01682   // -fno-exceptions.
01683   if (!getLangOpts().Exceptions) {
01684     OperatorDelete = nullptr;
01685     return false;
01686   }
01687 
01688   // C++ [expr.new]p19:
01689   //
01690   //   If the new-expression begins with a unary :: operator, the
01691   //   deallocation function's name is looked up in the global
01692   //   scope. Otherwise, if the allocated type is a class type T or an
01693   //   array thereof, the deallocation function's name is looked up in
01694   //   the scope of T. If this lookup fails to find the name, or if
01695   //   the allocated type is not a class type or array thereof, the
01696   //   deallocation function's name is looked up in the global scope.
01697   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
01698   if (AllocElemType->isRecordType() && !UseGlobal) {
01699     CXXRecordDecl *RD
01700       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
01701     LookupQualifiedName(FoundDelete, RD);
01702   }
01703   if (FoundDelete.isAmbiguous())
01704     return true; // FIXME: clean up expressions?
01705 
01706   if (FoundDelete.empty()) {
01707     DeclareGlobalNewDelete();
01708     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
01709   }
01710 
01711   FoundDelete.suppressDiagnostics();
01712 
01713   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
01714 
01715   // Whether we're looking for a placement operator delete is dictated
01716   // by whether we selected a placement operator new, not by whether
01717   // we had explicit placement arguments.  This matters for things like
01718   //   struct A { void *operator new(size_t, int = 0); ... };
01719   //   A *a = new A()
01720   bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
01721 
01722   if (isPlacementNew) {
01723     // C++ [expr.new]p20:
01724     //   A declaration of a placement deallocation function matches the
01725     //   declaration of a placement allocation function if it has the
01726     //   same number of parameters and, after parameter transformations
01727     //   (8.3.5), all parameter types except the first are
01728     //   identical. [...]
01729     //
01730     // To perform this comparison, we compute the function type that
01731     // the deallocation function should have, and use that type both
01732     // for template argument deduction and for comparison purposes.
01733     //
01734     // FIXME: this comparison should ignore CC and the like.
01735     QualType ExpectedFunctionType;
01736     {
01737       const FunctionProtoType *Proto
01738         = OperatorNew->getType()->getAs<FunctionProtoType>();
01739 
01740       SmallVector<QualType, 4> ArgTypes;
01741       ArgTypes.push_back(Context.VoidPtrTy);
01742       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
01743         ArgTypes.push_back(Proto->getParamType(I));
01744 
01745       FunctionProtoType::ExtProtoInfo EPI;
01746       EPI.Variadic = Proto->isVariadic();
01747 
01748       ExpectedFunctionType
01749         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
01750     }
01751 
01752     for (LookupResult::iterator D = FoundDelete.begin(),
01753                              DEnd = FoundDelete.end();
01754          D != DEnd; ++D) {
01755       FunctionDecl *Fn = nullptr;
01756       if (FunctionTemplateDecl *FnTmpl
01757             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
01758         // Perform template argument deduction to try to match the
01759         // expected function type.
01760         TemplateDeductionInfo Info(StartLoc);
01761         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
01762                                     Info))
01763           continue;
01764       } else
01765         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
01766 
01767       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
01768         Matches.push_back(std::make_pair(D.getPair(), Fn));
01769     }
01770   } else {
01771     // C++ [expr.new]p20:
01772     //   [...] Any non-placement deallocation function matches a
01773     //   non-placement allocation function. [...]
01774     for (LookupResult::iterator D = FoundDelete.begin(),
01775                              DEnd = FoundDelete.end();
01776          D != DEnd; ++D) {
01777       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
01778         if (isNonPlacementDeallocationFunction(*this, Fn))
01779           Matches.push_back(std::make_pair(D.getPair(), Fn));
01780     }
01781 
01782     // C++1y [expr.new]p22:
01783     //   For a non-placement allocation function, the normal deallocation
01784     //   function lookup is used
01785     // C++1y [expr.delete]p?:
01786     //   If [...] deallocation function lookup finds both a usual deallocation
01787     //   function with only a pointer parameter and a usual deallocation
01788     //   function with both a pointer parameter and a size parameter, then the
01789     //   selected deallocation function shall be the one with two parameters.
01790     //   Otherwise, the selected deallocation function shall be the function
01791     //   with one parameter.
01792     if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
01793       if (Matches[0].second->getNumParams() == 1)
01794         Matches.erase(Matches.begin());
01795       else
01796         Matches.erase(Matches.begin() + 1);
01797       assert(Matches[0].second->getNumParams() == 2 &&
01798              "found an unexpected usual deallocation function");
01799     }
01800   }
01801 
01802   // C++ [expr.new]p20:
01803   //   [...] If the lookup finds a single matching deallocation
01804   //   function, that function will be called; otherwise, no
01805   //   deallocation function will be called.
01806   if (Matches.size() == 1) {
01807     OperatorDelete = Matches[0].second;
01808 
01809     // C++0x [expr.new]p20:
01810     //   If the lookup finds the two-parameter form of a usual
01811     //   deallocation function (3.7.4.2) and that function, considered
01812     //   as a placement deallocation function, would have been
01813     //   selected as a match for the allocation function, the program
01814     //   is ill-formed.
01815     if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
01816         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
01817       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
01818         << SourceRange(PlaceArgs.front()->getLocStart(),
01819                        PlaceArgs.back()->getLocEnd());
01820       if (!OperatorDelete->isImplicit())
01821         Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
01822           << DeleteName;
01823     } else {
01824       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
01825                             Matches[0].first);
01826     }
01827   }
01828 
01829   return false;
01830 }
01831 
01832 /// \brief Find an fitting overload for the allocation function
01833 /// in the specified scope.
01834 ///
01835 /// \param StartLoc The location of the 'new' token.
01836 /// \param Range The range of the placement arguments.
01837 /// \param Name The name of the function ('operator new' or 'operator new[]').
01838 /// \param Args The placement arguments specified.
01839 /// \param Ctx The scope in which we should search; either a class scope or the
01840 ///        translation unit.
01841 /// \param AllowMissing If \c true, report an error if we can't find any
01842 ///        allocation functions. Otherwise, succeed but don't fill in \p
01843 ///        Operator.
01844 /// \param Operator Filled in with the found allocation function. Unchanged if
01845 ///        no allocation function was found.
01846 /// \param Diagnose If \c true, issue errors if the allocation function is not
01847 ///        usable.
01848 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
01849                                   DeclarationName Name, MultiExprArg Args,
01850                                   DeclContext *Ctx,
01851                                   bool AllowMissing, FunctionDecl *&Operator,
01852                                   bool Diagnose) {
01853   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
01854   LookupQualifiedName(R, Ctx);
01855   if (R.empty()) {
01856     if (AllowMissing || !Diagnose)
01857       return false;
01858     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01859       << Name << Range;
01860   }
01861 
01862   if (R.isAmbiguous())
01863     return true;
01864 
01865   R.suppressDiagnostics();
01866 
01867   OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
01868   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
01869        Alloc != AllocEnd; ++Alloc) {
01870     // Even member operator new/delete are implicitly treated as
01871     // static, so don't use AddMemberCandidate.
01872     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
01873 
01874     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
01875       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
01876                                    /*ExplicitTemplateArgs=*/nullptr,
01877                                    Args, Candidates,
01878                                    /*SuppressUserConversions=*/false);
01879       continue;
01880     }
01881 
01882     FunctionDecl *Fn = cast<FunctionDecl>(D);
01883     AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
01884                          /*SuppressUserConversions=*/false);
01885   }
01886 
01887   // Do the resolution.
01888   OverloadCandidateSet::iterator Best;
01889   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
01890   case OR_Success: {
01891     // Got one!
01892     FunctionDecl *FnDecl = Best->Function;
01893     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
01894                               Best->FoundDecl, Diagnose) == AR_inaccessible)
01895       return true;
01896 
01897     Operator = FnDecl;
01898     return false;
01899   }
01900 
01901   case OR_No_Viable_Function:
01902     if (Diagnose) {
01903       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
01904         << Name << Range;
01905       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
01906     }
01907     return true;
01908 
01909   case OR_Ambiguous:
01910     if (Diagnose) {
01911       Diag(StartLoc, diag::err_ovl_ambiguous_call)
01912         << Name << Range;
01913       Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
01914     }
01915     return true;
01916 
01917   case OR_Deleted: {
01918     if (Diagnose) {
01919       Diag(StartLoc, diag::err_ovl_deleted_call)
01920         << Best->Function->isDeleted()
01921         << Name 
01922         << getDeletedOrUnavailableSuffix(Best->Function)
01923         << Range;
01924       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
01925     }
01926     return true;
01927   }
01928   }
01929   llvm_unreachable("Unreachable, bad result from BestViableFunction");
01930 }
01931 
01932 
01933 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
01934 /// delete. These are:
01935 /// @code
01936 ///   // C++03:
01937 ///   void* operator new(std::size_t) throw(std::bad_alloc);
01938 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
01939 ///   void operator delete(void *) throw();
01940 ///   void operator delete[](void *) throw();
01941 ///   // C++11:
01942 ///   void* operator new(std::size_t);
01943 ///   void* operator new[](std::size_t);
01944 ///   void operator delete(void *) noexcept;
01945 ///   void operator delete[](void *) noexcept;
01946 ///   // C++1y:
01947 ///   void* operator new(std::size_t);
01948 ///   void* operator new[](std::size_t);
01949 ///   void operator delete(void *) noexcept;
01950 ///   void operator delete[](void *) noexcept;
01951 ///   void operator delete(void *, std::size_t) noexcept;
01952 ///   void operator delete[](void *, std::size_t) noexcept;
01953 /// @endcode
01954 /// Note that the placement and nothrow forms of new are *not* implicitly
01955 /// declared. Their use requires including <new>.
01956 void Sema::DeclareGlobalNewDelete() {
01957   if (GlobalNewDeleteDeclared)
01958     return;
01959 
01960   // C++ [basic.std.dynamic]p2:
01961   //   [...] The following allocation and deallocation functions (18.4) are
01962   //   implicitly declared in global scope in each translation unit of a
01963   //   program
01964   //
01965   //     C++03:
01966   //     void* operator new(std::size_t) throw(std::bad_alloc);
01967   //     void* operator new[](std::size_t) throw(std::bad_alloc);
01968   //     void  operator delete(void*) throw();
01969   //     void  operator delete[](void*) throw();
01970   //     C++11:
01971   //     void* operator new(std::size_t);
01972   //     void* operator new[](std::size_t);
01973   //     void  operator delete(void*) noexcept;
01974   //     void  operator delete[](void*) noexcept;
01975   //     C++1y:
01976   //     void* operator new(std::size_t);
01977   //     void* operator new[](std::size_t);
01978   //     void  operator delete(void*) noexcept;
01979   //     void  operator delete[](void*) noexcept;
01980   //     void  operator delete(void*, std::size_t) noexcept;
01981   //     void  operator delete[](void*, std::size_t) noexcept;
01982   //
01983   //   These implicit declarations introduce only the function names operator
01984   //   new, operator new[], operator delete, operator delete[].
01985   //
01986   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
01987   // "std" or "bad_alloc" as necessary to form the exception specification.
01988   // However, we do not make these implicit declarations visible to name
01989   // lookup.
01990   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
01991     // The "std::bad_alloc" class has not yet been declared, so build it
01992     // implicitly.
01993     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
01994                                         getOrCreateStdNamespace(),
01995                                         SourceLocation(), SourceLocation(),
01996                                       &PP.getIdentifierTable().get("bad_alloc"),
01997                                         nullptr);
01998     getStdBadAlloc()->setImplicit(true);
01999   }
02000 
02001   GlobalNewDeleteDeclared = true;
02002 
02003   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
02004   QualType SizeT = Context.getSizeType();
02005   bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
02006 
02007   DeclareGlobalAllocationFunction(
02008       Context.DeclarationNames.getCXXOperatorName(OO_New),
02009       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
02010   DeclareGlobalAllocationFunction(
02011       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
02012       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
02013   DeclareGlobalAllocationFunction(
02014       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
02015       Context.VoidTy, VoidPtr);
02016   DeclareGlobalAllocationFunction(
02017       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
02018       Context.VoidTy, VoidPtr);
02019   if (getLangOpts().SizedDeallocation) {
02020     DeclareGlobalAllocationFunction(
02021         Context.DeclarationNames.getCXXOperatorName(OO_Delete),
02022         Context.VoidTy, VoidPtr, Context.getSizeType());
02023     DeclareGlobalAllocationFunction(
02024         Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
02025         Context.VoidTy, VoidPtr, Context.getSizeType());
02026   }
02027 }
02028 
02029 /// DeclareGlobalAllocationFunction - Declares a single implicit global
02030 /// allocation function if it doesn't already exist.
02031 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
02032                                            QualType Return,
02033                                            QualType Param1, QualType Param2,
02034                                            bool AddMallocAttr) {
02035   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
02036   unsigned NumParams = Param2.isNull() ? 1 : 2;
02037 
02038   // Check if this function is already declared.
02039   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
02040   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
02041        Alloc != AllocEnd; ++Alloc) {
02042     // Only look at non-template functions, as it is the predefined,
02043     // non-templated allocation function we are trying to declare here.
02044     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
02045       if (Func->getNumParams() == NumParams) {
02046         QualType InitialParam1Type =
02047             Context.getCanonicalType(Func->getParamDecl(0)
02048                                          ->getType().getUnqualifiedType());
02049         QualType InitialParam2Type =
02050             NumParams == 2
02051                 ? Context.getCanonicalType(Func->getParamDecl(1)
02052                                                ->getType().getUnqualifiedType())
02053                 : QualType();
02054         // FIXME: Do we need to check for default arguments here?
02055         if (InitialParam1Type == Param1 &&
02056             (NumParams == 1 || InitialParam2Type == Param2)) {
02057           if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
02058             Func->addAttr(MallocAttr::CreateImplicit(Context));
02059           // Make the function visible to name lookup, even if we found it in
02060           // an unimported module. It either is an implicitly-declared global
02061           // allocation function, or is suppressing that function.
02062           Func->setHidden(false);
02063           return;
02064         }
02065       }
02066     }
02067   }
02068 
02069   FunctionProtoType::ExtProtoInfo EPI;
02070 
02071   QualType BadAllocType;
02072   bool HasBadAllocExceptionSpec
02073     = (Name.getCXXOverloadedOperator() == OO_New ||
02074        Name.getCXXOverloadedOperator() == OO_Array_New);
02075   if (HasBadAllocExceptionSpec) {
02076     if (!getLangOpts().CPlusPlus11) {
02077       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
02078       assert(StdBadAlloc && "Must have std::bad_alloc declared");
02079       EPI.ExceptionSpec.Type = EST_Dynamic;
02080       EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
02081     }
02082   } else {
02083     EPI.ExceptionSpec =
02084         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
02085   }
02086 
02087   QualType Params[] = { Param1, Param2 };
02088 
02089   QualType FnType = Context.getFunctionType(
02090       Return, llvm::makeArrayRef(Params, NumParams), EPI);
02091   FunctionDecl *Alloc =
02092     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
02093                          SourceLocation(), Name,
02094                          FnType, /*TInfo=*/nullptr, SC_None, false, true);
02095   Alloc->setImplicit();
02096 
02097   if (AddMallocAttr)
02098     Alloc->addAttr(MallocAttr::CreateImplicit(Context));
02099 
02100   ParmVarDecl *ParamDecls[2];
02101   for (unsigned I = 0; I != NumParams; ++I) {
02102     ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
02103                                         SourceLocation(), nullptr,
02104                                         Params[I], /*TInfo=*/nullptr,
02105                                         SC_None, nullptr);
02106     ParamDecls[I]->setImplicit();
02107   }
02108   Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
02109 
02110   Context.getTranslationUnitDecl()->addDecl(Alloc);
02111   IdResolver.tryAddTopLevelDecl(Alloc, Name);
02112 }
02113 
02114 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
02115                                                   bool CanProvideSize,
02116                                                   DeclarationName Name) {
02117   DeclareGlobalNewDelete();
02118 
02119   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
02120   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
02121 
02122   // C++ [expr.new]p20:
02123   //   [...] Any non-placement deallocation function matches a
02124   //   non-placement allocation function. [...]
02125   llvm::SmallVector<FunctionDecl*, 2> Matches;
02126   for (LookupResult::iterator D = FoundDelete.begin(),
02127                            DEnd = FoundDelete.end();
02128        D != DEnd; ++D) {
02129     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
02130       if (isNonPlacementDeallocationFunction(*this, Fn))
02131         Matches.push_back(Fn);
02132   }
02133 
02134   // C++1y [expr.delete]p?:
02135   //   If the type is complete and deallocation function lookup finds both a
02136   //   usual deallocation function with only a pointer parameter and a usual
02137   //   deallocation function with both a pointer parameter and a size
02138   //   parameter, then the selected deallocation function shall be the one
02139   //   with two parameters.  Otherwise, the selected deallocation function
02140   //   shall be the function with one parameter.
02141   if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
02142     unsigned NumArgs = CanProvideSize ? 2 : 1;
02143     if (Matches[0]->getNumParams() != NumArgs)
02144       Matches.erase(Matches.begin());
02145     else
02146       Matches.erase(Matches.begin() + 1);
02147     assert(Matches[0]->getNumParams() == NumArgs &&
02148            "found an unexpected usual deallocation function");
02149   }
02150 
02151   assert(Matches.size() == 1 &&
02152          "unexpectedly have multiple usual deallocation functions");
02153   return Matches.front();
02154 }
02155 
02156 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
02157                                     DeclarationName Name,
02158                                     FunctionDecl* &Operator, bool Diagnose) {
02159   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
02160   // Try to find operator delete/operator delete[] in class scope.
02161   LookupQualifiedName(Found, RD);
02162 
02163   if (Found.isAmbiguous())
02164     return true;
02165 
02166   Found.suppressDiagnostics();
02167 
02168   SmallVector<DeclAccessPair,4> Matches;
02169   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
02170        F != FEnd; ++F) {
02171     NamedDecl *ND = (*F)->getUnderlyingDecl();
02172 
02173     // Ignore template operator delete members from the check for a usual
02174     // deallocation function.
02175     if (isa<FunctionTemplateDecl>(ND))
02176       continue;
02177 
02178     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
02179       Matches.push_back(F.getPair());
02180   }
02181 
02182   // There's exactly one suitable operator;  pick it.
02183   if (Matches.size() == 1) {
02184     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
02185 
02186     if (Operator->isDeleted()) {
02187       if (Diagnose) {
02188         Diag(StartLoc, diag::err_deleted_function_use);
02189         NoteDeletedFunction(Operator);
02190       }
02191       return true;
02192     }
02193 
02194     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
02195                               Matches[0], Diagnose) == AR_inaccessible)
02196       return true;
02197 
02198     return false;
02199 
02200   // We found multiple suitable operators;  complain about the ambiguity.
02201   } else if (!Matches.empty()) {
02202     if (Diagnose) {
02203       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
02204         << Name << RD;
02205 
02206       for (SmallVectorImpl<DeclAccessPair>::iterator
02207              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
02208         Diag((*F)->getUnderlyingDecl()->getLocation(),
02209              diag::note_member_declared_here) << Name;
02210     }
02211     return true;
02212   }
02213 
02214   // We did find operator delete/operator delete[] declarations, but
02215   // none of them were suitable.
02216   if (!Found.empty()) {
02217     if (Diagnose) {
02218       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
02219         << Name << RD;
02220 
02221       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
02222            F != FEnd; ++F)
02223         Diag((*F)->getUnderlyingDecl()->getLocation(),
02224              diag::note_member_declared_here) << Name;
02225     }
02226     return true;
02227   }
02228 
02229   Operator = nullptr;
02230   return false;
02231 }
02232 
02233 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
02234 /// @code ::delete ptr; @endcode
02235 /// or
02236 /// @code delete [] ptr; @endcode
02237 ExprResult
02238 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
02239                      bool ArrayForm, Expr *ExE) {
02240   // C++ [expr.delete]p1:
02241   //   The operand shall have a pointer type, or a class type having a single
02242   //   non-explicit conversion function to a pointer type. The result has type
02243   //   void.
02244   //
02245   // DR599 amends "pointer type" to "pointer to object type" in both cases.
02246 
02247   ExprResult Ex = ExE;
02248   FunctionDecl *OperatorDelete = nullptr;
02249   bool ArrayFormAsWritten = ArrayForm;
02250   bool UsualArrayDeleteWantsSize = false;
02251 
02252   if (!Ex.get()->isTypeDependent()) {
02253     // Perform lvalue-to-rvalue cast, if needed.
02254     Ex = DefaultLvalueConversion(Ex.get());
02255     if (Ex.isInvalid())
02256       return ExprError();
02257 
02258     QualType Type = Ex.get()->getType();
02259 
02260     class DeleteConverter : public ContextualImplicitConverter {
02261     public:
02262       DeleteConverter() : ContextualImplicitConverter(false, true) {}
02263 
02264       bool match(QualType ConvType) override {
02265         // FIXME: If we have an operator T* and an operator void*, we must pick
02266         // the operator T*.
02267         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
02268           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
02269             return true;
02270         return false;
02271       }
02272 
02273       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
02274                                             QualType T) override {
02275         return S.Diag(Loc, diag::err_delete_operand) << T;
02276       }
02277 
02278       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
02279                                                QualType T) override {
02280         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
02281       }
02282 
02283       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
02284                                                  QualType T,
02285                                                  QualType ConvTy) override {
02286         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
02287       }
02288 
02289       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
02290                                              QualType ConvTy) override {
02291         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
02292           << ConvTy;
02293       }
02294 
02295       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
02296                                               QualType T) override {
02297         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
02298       }
02299 
02300       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
02301                                           QualType ConvTy) override {
02302         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
02303           << ConvTy;
02304       }
02305 
02306       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
02307                                                QualType T,
02308                                                QualType ConvTy) override {
02309         llvm_unreachable("conversion functions are permitted");
02310       }
02311     } Converter;
02312 
02313     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
02314     if (Ex.isInvalid())
02315       return ExprError();
02316     Type = Ex.get()->getType();
02317     if (!Converter.match(Type))
02318       // FIXME: PerformContextualImplicitConversion should return ExprError
02319       //        itself in this case.
02320       return ExprError();
02321 
02322     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
02323     QualType PointeeElem = Context.getBaseElementType(Pointee);
02324 
02325     if (unsigned AddressSpace = Pointee.getAddressSpace())
02326       return Diag(Ex.get()->getLocStart(), 
02327                   diag::err_address_space_qualified_delete)
02328                << Pointee.getUnqualifiedType() << AddressSpace;
02329 
02330     CXXRecordDecl *PointeeRD = nullptr;
02331     if (Pointee->isVoidType() && !isSFINAEContext()) {
02332       // The C++ standard bans deleting a pointer to a non-object type, which
02333       // effectively bans deletion of "void*". However, most compilers support
02334       // this, so we treat it as a warning unless we're in a SFINAE context.
02335       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
02336         << Type << Ex.get()->getSourceRange();
02337     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
02338       return ExprError(Diag(StartLoc, diag::err_delete_operand)
02339         << Type << Ex.get()->getSourceRange());
02340     } else if (!Pointee->isDependentType()) {
02341       if (!RequireCompleteType(StartLoc, Pointee,
02342                                diag::warn_delete_incomplete, Ex.get())) {
02343         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
02344           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
02345       }
02346     }
02347 
02348     // C++ [expr.delete]p2:
02349     //   [Note: a pointer to a const type can be the operand of a
02350     //   delete-expression; it is not necessary to cast away the constness
02351     //   (5.2.11) of the pointer expression before it is used as the operand
02352     //   of the delete-expression. ]
02353 
02354     if (Pointee->isArrayType() && !ArrayForm) {
02355       Diag(StartLoc, diag::warn_delete_array_type)
02356           << Type << Ex.get()->getSourceRange()
02357           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
02358       ArrayForm = true;
02359     }
02360 
02361     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
02362                                       ArrayForm ? OO_Array_Delete : OO_Delete);
02363 
02364     if (PointeeRD) {
02365       if (!UseGlobal &&
02366           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
02367                                    OperatorDelete))
02368         return ExprError();
02369 
02370       // If we're allocating an array of records, check whether the
02371       // usual operator delete[] has a size_t parameter.
02372       if (ArrayForm) {
02373         // If the user specifically asked to use the global allocator,
02374         // we'll need to do the lookup into the class.
02375         if (UseGlobal)
02376           UsualArrayDeleteWantsSize =
02377             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
02378 
02379         // Otherwise, the usual operator delete[] should be the
02380         // function we just found.
02381         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
02382           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
02383       }
02384 
02385       if (!PointeeRD->hasIrrelevantDestructor())
02386         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
02387           MarkFunctionReferenced(StartLoc,
02388                                     const_cast<CXXDestructorDecl*>(Dtor));
02389           if (DiagnoseUseOfDecl(Dtor, StartLoc))
02390             return ExprError();
02391         }
02392 
02393       // C++ [expr.delete]p3:
02394       //   In the first alternative (delete object), if the static type of the
02395       //   object to be deleted is different from its dynamic type, the static
02396       //   type shall be a base class of the dynamic type of the object to be
02397       //   deleted and the static type shall have a virtual destructor or the
02398       //   behavior is undefined.
02399       //
02400       // Note: a final class cannot be derived from, no issue there
02401       if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
02402         CXXDestructorDecl *dtor = PointeeRD->getDestructor();
02403         if (dtor && !dtor->isVirtual()) {
02404           if (PointeeRD->isAbstract()) {
02405             // If the class is abstract, we warn by default, because we're
02406             // sure the code has undefined behavior.
02407             Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
02408                 << PointeeElem;
02409           } else if (!ArrayForm) {
02410             // Otherwise, if this is not an array delete, it's a bit suspect,
02411             // but not necessarily wrong.
02412             Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
02413           }
02414         }
02415       }
02416 
02417     }
02418 
02419     if (!OperatorDelete)
02420       // Look for a global declaration.
02421       OperatorDelete = FindUsualDeallocationFunction(
02422           StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
02423                     (!ArrayForm || UsualArrayDeleteWantsSize ||
02424                      Pointee.isDestructedType()),
02425           DeleteName);
02426 
02427     MarkFunctionReferenced(StartLoc, OperatorDelete);
02428     
02429     // Check access and ambiguity of operator delete and destructor.
02430     if (PointeeRD) {
02431       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
02432           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 
02433                       PDiag(diag::err_access_dtor) << PointeeElem);
02434       }
02435     }
02436   }
02437 
02438   return new (Context) CXXDeleteExpr(
02439       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
02440       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
02441 }
02442 
02443 /// \brief Check the use of the given variable as a C++ condition in an if,
02444 /// while, do-while, or switch statement.
02445 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
02446                                         SourceLocation StmtLoc,
02447                                         bool ConvertToBoolean) {
02448   if (ConditionVar->isInvalidDecl())
02449     return ExprError();
02450 
02451   QualType T = ConditionVar->getType();
02452 
02453   // C++ [stmt.select]p2:
02454   //   The declarator shall not specify a function or an array.
02455   if (T->isFunctionType())
02456     return ExprError(Diag(ConditionVar->getLocation(),
02457                           diag::err_invalid_use_of_function_type)
02458                        << ConditionVar->getSourceRange());
02459   else if (T->isArrayType())
02460     return ExprError(Diag(ConditionVar->getLocation(),
02461                           diag::err_invalid_use_of_array_type)
02462                      << ConditionVar->getSourceRange());
02463 
02464   ExprResult Condition = DeclRefExpr::Create(
02465       Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
02466       /*enclosing*/ false, ConditionVar->getLocation(),
02467       ConditionVar->getType().getNonReferenceType(), VK_LValue);
02468 
02469   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
02470 
02471   if (ConvertToBoolean) {
02472     Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
02473     if (Condition.isInvalid())
02474       return ExprError();
02475   }
02476 
02477   return Condition;
02478 }
02479 
02480 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
02481 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
02482   // C++ 6.4p4:
02483   // The value of a condition that is an initialized declaration in a statement
02484   // other than a switch statement is the value of the declared variable
02485   // implicitly converted to type bool. If that conversion is ill-formed, the
02486   // program is ill-formed.
02487   // The value of a condition that is an expression is the value of the
02488   // expression, implicitly converted to bool.
02489   //
02490   return PerformContextuallyConvertToBool(CondExpr);
02491 }
02492 
02493 /// Helper function to determine whether this is the (deprecated) C++
02494 /// conversion from a string literal to a pointer to non-const char or
02495 /// non-const wchar_t (for narrow and wide string literals,
02496 /// respectively).
02497 bool
02498 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
02499   // Look inside the implicit cast, if it exists.
02500   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
02501     From = Cast->getSubExpr();
02502 
02503   // A string literal (2.13.4) that is not a wide string literal can
02504   // be converted to an rvalue of type "pointer to char"; a wide
02505   // string literal can be converted to an rvalue of type "pointer
02506   // to wchar_t" (C++ 4.2p2).
02507   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
02508     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
02509       if (const BuiltinType *ToPointeeType
02510           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
02511         // This conversion is considered only when there is an
02512         // explicit appropriate pointer target type (C++ 4.2p2).
02513         if (!ToPtrType->getPointeeType().hasQualifiers()) {
02514           switch (StrLit->getKind()) {
02515             case StringLiteral::UTF8:
02516             case StringLiteral::UTF16:
02517             case StringLiteral::UTF32:
02518               // We don't allow UTF literals to be implicitly converted
02519               break;
02520             case StringLiteral::Ascii:
02521               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
02522                       ToPointeeType->getKind() == BuiltinType::Char_S);
02523             case StringLiteral::Wide:
02524               return ToPointeeType->isWideCharType();
02525           }
02526         }
02527       }
02528 
02529   return false;
02530 }
02531 
02532 static ExprResult BuildCXXCastArgument(Sema &S,
02533                                        SourceLocation CastLoc,
02534                                        QualType Ty,
02535                                        CastKind Kind,
02536                                        CXXMethodDecl *Method,
02537                                        DeclAccessPair FoundDecl,
02538                                        bool HadMultipleCandidates,
02539                                        Expr *From) {
02540   switch (Kind) {
02541   default: llvm_unreachable("Unhandled cast kind!");
02542   case CK_ConstructorConversion: {
02543     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
02544     SmallVector<Expr*, 8> ConstructorArgs;
02545 
02546     if (S.RequireNonAbstractType(CastLoc, Ty,
02547                                  diag::err_allocation_of_abstract_type))
02548       return ExprError();
02549 
02550     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
02551       return ExprError();
02552 
02553     S.CheckConstructorAccess(CastLoc, Constructor,
02554                              InitializedEntity::InitializeTemporary(Ty),
02555                              Constructor->getAccess());
02556 
02557     ExprResult Result = S.BuildCXXConstructExpr(
02558         CastLoc, Ty, cast<CXXConstructorDecl>(Method),
02559         ConstructorArgs, HadMultipleCandidates,
02560         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
02561         CXXConstructExpr::CK_Complete, SourceRange());
02562     if (Result.isInvalid())
02563       return ExprError();
02564 
02565     return S.MaybeBindToTemporary(Result.getAs<Expr>());
02566   }
02567 
02568   case CK_UserDefinedConversion: {
02569     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
02570 
02571     // Create an implicit call expr that calls it.
02572     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
02573     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
02574                                                  HadMultipleCandidates);
02575     if (Result.isInvalid())
02576       return ExprError();
02577     // Record usage of conversion in an implicit cast.
02578     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
02579                                       CK_UserDefinedConversion, Result.get(),
02580                                       nullptr, Result.get()->getValueKind());
02581 
02582     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
02583 
02584     return S.MaybeBindToTemporary(Result.get());
02585   }
02586   }
02587 }
02588 
02589 /// PerformImplicitConversion - Perform an implicit conversion of the
02590 /// expression From to the type ToType using the pre-computed implicit
02591 /// conversion sequence ICS. Returns the converted
02592 /// expression. Action is the kind of conversion we're performing,
02593 /// used in the error message.
02594 ExprResult
02595 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
02596                                 const ImplicitConversionSequence &ICS,
02597                                 AssignmentAction Action, 
02598                                 CheckedConversionKind CCK) {
02599   switch (ICS.getKind()) {
02600   case ImplicitConversionSequence::StandardConversion: {
02601     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
02602                                                Action, CCK);
02603     if (Res.isInvalid())
02604       return ExprError();
02605     From = Res.get();
02606     break;
02607   }
02608 
02609   case ImplicitConversionSequence::UserDefinedConversion: {
02610 
02611       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
02612       CastKind CastKind;
02613       QualType BeforeToType;
02614       assert(FD && "FIXME: aggregate initialization from init list");
02615       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
02616         CastKind = CK_UserDefinedConversion;
02617 
02618         // If the user-defined conversion is specified by a conversion function,
02619         // the initial standard conversion sequence converts the source type to
02620         // the implicit object parameter of the conversion function.
02621         BeforeToType = Context.getTagDeclType(Conv->getParent());
02622       } else {
02623         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
02624         CastKind = CK_ConstructorConversion;
02625         // Do no conversion if dealing with ... for the first conversion.
02626         if (!ICS.UserDefined.EllipsisConversion) {
02627           // If the user-defined conversion is specified by a constructor, the
02628           // initial standard conversion sequence converts the source type to the
02629           // type required by the argument of the constructor
02630           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
02631         }
02632       }
02633       // Watch out for ellipsis conversion.
02634       if (!ICS.UserDefined.EllipsisConversion) {
02635         ExprResult Res =
02636           PerformImplicitConversion(From, BeforeToType,
02637                                     ICS.UserDefined.Before, AA_Converting,
02638                                     CCK);
02639         if (Res.isInvalid())
02640           return ExprError();
02641         From = Res.get();
02642       }
02643 
02644       ExprResult CastArg
02645         = BuildCXXCastArgument(*this,
02646                                From->getLocStart(),
02647                                ToType.getNonReferenceType(),
02648                                CastKind, cast<CXXMethodDecl>(FD),
02649                                ICS.UserDefined.FoundConversionFunction,
02650                                ICS.UserDefined.HadMultipleCandidates,
02651                                From);
02652 
02653       if (CastArg.isInvalid())
02654         return ExprError();
02655 
02656       From = CastArg.get();
02657 
02658       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
02659                                        AA_Converting, CCK);
02660   }
02661 
02662   case ImplicitConversionSequence::AmbiguousConversion:
02663     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
02664                           PDiag(diag::err_typecheck_ambiguous_condition)
02665                             << From->getSourceRange());
02666      return ExprError();
02667 
02668   case ImplicitConversionSequence::EllipsisConversion:
02669     llvm_unreachable("Cannot perform an ellipsis conversion");
02670 
02671   case ImplicitConversionSequence::BadConversion:
02672     return ExprError();
02673   }
02674 
02675   // Everything went well.
02676   return From;
02677 }
02678 
02679 /// PerformImplicitConversion - Perform an implicit conversion of the
02680 /// expression From to the type ToType by following the standard
02681 /// conversion sequence SCS. Returns the converted
02682 /// expression. Flavor is the context in which we're performing this
02683 /// conversion, for use in error messages.
02684 ExprResult
02685 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
02686                                 const StandardConversionSequence& SCS,
02687                                 AssignmentAction Action, 
02688                                 CheckedConversionKind CCK) {
02689   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
02690   
02691   // Overall FIXME: we are recomputing too many types here and doing far too
02692   // much extra work. What this means is that we need to keep track of more
02693   // information that is computed when we try the implicit conversion initially,
02694   // so that we don't need to recompute anything here.
02695   QualType FromType = From->getType();
02696   
02697   if (SCS.CopyConstructor) {
02698     // FIXME: When can ToType be a reference type?
02699     assert(!ToType->isReferenceType());
02700     if (SCS.Second == ICK_Derived_To_Base) {
02701       SmallVector<Expr*, 8> ConstructorArgs;
02702       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
02703                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
02704                                   ConstructorArgs))
02705         return ExprError();
02706       return BuildCXXConstructExpr(
02707           /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
02708           ConstructorArgs, /*HadMultipleCandidates*/ false,
02709           /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
02710           CXXConstructExpr::CK_Complete, SourceRange());
02711     }
02712     return BuildCXXConstructExpr(
02713         /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
02714         From, /*HadMultipleCandidates*/ false,
02715         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
02716         CXXConstructExpr::CK_Complete, SourceRange());
02717   }
02718 
02719   // Resolve overloaded function references.
02720   if (Context.hasSameType(FromType, Context.OverloadTy)) {
02721     DeclAccessPair Found;
02722     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
02723                                                           true, Found);
02724     if (!Fn)
02725       return ExprError();
02726 
02727     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
02728       return ExprError();
02729 
02730     From = FixOverloadedFunctionReference(From, Found, Fn);
02731     FromType = From->getType();
02732   }
02733 
02734   // If we're converting to an atomic type, first convert to the corresponding
02735   // non-atomic type.
02736   QualType ToAtomicType;
02737   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
02738     ToAtomicType = ToType;
02739     ToType = ToAtomic->getValueType();
02740   }
02741 
02742   // Perform the first implicit conversion.
02743   switch (SCS.First) {
02744   case ICK_Identity:
02745     // Nothing to do.
02746     break;
02747 
02748   case ICK_Lvalue_To_Rvalue: {
02749     assert(From->getObjectKind() != OK_ObjCProperty);
02750     FromType = FromType.getUnqualifiedType();
02751     ExprResult FromRes = DefaultLvalueConversion(From);
02752     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
02753     From = FromRes.get();
02754     break;
02755   }
02756 
02757   case ICK_Array_To_Pointer:
02758     FromType = Context.getArrayDecayedType(FromType);
02759     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 
02760                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02761     break;
02762 
02763   case ICK_Function_To_Pointer:
02764     FromType = Context.getPointerType(FromType);
02765     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 
02766                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02767     break;
02768 
02769   default:
02770     llvm_unreachable("Improper first standard conversion");
02771   }
02772 
02773   // Perform the second implicit conversion
02774   switch (SCS.Second) {
02775   case ICK_Identity:
02776     // If both sides are functions (or pointers/references to them), there could
02777     // be incompatible exception declarations.
02778     if (CheckExceptionSpecCompatibility(From, ToType))
02779       return ExprError();
02780     // Nothing else to do.
02781     break;
02782 
02783   case ICK_NoReturn_Adjustment:
02784     // If both sides are functions (or pointers/references to them), there could
02785     // be incompatible exception declarations.
02786     if (CheckExceptionSpecCompatibility(From, ToType))
02787       return ExprError();
02788 
02789     From = ImpCastExprToType(From, ToType, CK_NoOp, 
02790                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02791     break;
02792 
02793   case ICK_Integral_Promotion:
02794   case ICK_Integral_Conversion:
02795     if (ToType->isBooleanType()) {
02796       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
02797              SCS.Second == ICK_Integral_Promotion &&
02798              "only enums with fixed underlying type can promote to bool");
02799       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
02800                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02801     } else {
02802       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
02803                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02804     }
02805     break;
02806 
02807   case ICK_Floating_Promotion:
02808   case ICK_Floating_Conversion:
02809     From = ImpCastExprToType(From, ToType, CK_FloatingCast, 
02810                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02811     break;
02812 
02813   case ICK_Complex_Promotion:
02814   case ICK_Complex_Conversion: {
02815     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
02816     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
02817     CastKind CK;
02818     if (FromEl->isRealFloatingType()) {
02819       if (ToEl->isRealFloatingType())
02820         CK = CK_FloatingComplexCast;
02821       else
02822         CK = CK_FloatingComplexToIntegralComplex;
02823     } else if (ToEl->isRealFloatingType()) {
02824       CK = CK_IntegralComplexToFloatingComplex;
02825     } else {
02826       CK = CK_IntegralComplexCast;
02827     }
02828     From = ImpCastExprToType(From, ToType, CK, 
02829                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02830     break;
02831   }
02832 
02833   case ICK_Floating_Integral:
02834     if (ToType->isRealFloatingType())
02835       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 
02836                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02837     else
02838       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 
02839                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02840     break;
02841 
02842   case ICK_Compatible_Conversion:
02843       From = ImpCastExprToType(From, ToType, CK_NoOp, 
02844                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02845     break;
02846 
02847   case ICK_Writeback_Conversion:
02848   case ICK_Pointer_Conversion: {
02849     if (SCS.IncompatibleObjC && Action != AA_Casting) {
02850       // Diagnose incompatible Objective-C conversions
02851       if (Action == AA_Initializing || Action == AA_Assigning)
02852         Diag(From->getLocStart(),
02853              diag::ext_typecheck_convert_incompatible_pointer)
02854           << ToType << From->getType() << Action
02855           << From->getSourceRange() << 0;
02856       else
02857         Diag(From->getLocStart(),
02858              diag::ext_typecheck_convert_incompatible_pointer)
02859           << From->getType() << ToType << Action
02860           << From->getSourceRange() << 0;
02861 
02862       if (From->getType()->isObjCObjectPointerType() &&
02863           ToType->isObjCObjectPointerType())
02864         EmitRelatedResultTypeNote(From);
02865     } 
02866     else if (getLangOpts().ObjCAutoRefCount &&
02867              !CheckObjCARCUnavailableWeakConversion(ToType, 
02868                                                     From->getType())) {
02869       if (Action == AA_Initializing)
02870         Diag(From->getLocStart(), 
02871              diag::err_arc_weak_unavailable_assign);
02872       else
02873         Diag(From->getLocStart(),
02874              diag::err_arc_convesion_of_weak_unavailable) 
02875           << (Action == AA_Casting) << From->getType() << ToType 
02876           << From->getSourceRange();
02877     }
02878              
02879     CastKind Kind = CK_Invalid;
02880     CXXCastPath BasePath;
02881     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
02882       return ExprError();
02883 
02884     // Make sure we extend blocks if necessary.
02885     // FIXME: doing this here is really ugly.
02886     if (Kind == CK_BlockPointerToObjCPointerCast) {
02887       ExprResult E = From;
02888       (void) PrepareCastToObjCObjectPointer(E);
02889       From = E.get();
02890     }
02891     if (getLangOpts().ObjCAutoRefCount)
02892       CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
02893     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
02894              .get();
02895     break;
02896   }
02897 
02898   case ICK_Pointer_Member: {
02899     CastKind Kind = CK_Invalid;
02900     CXXCastPath BasePath;
02901     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
02902       return ExprError();
02903     if (CheckExceptionSpecCompatibility(From, ToType))
02904       return ExprError();
02905 
02906     // We may not have been able to figure out what this member pointer resolved
02907     // to up until this exact point.  Attempt to lock-in it's inheritance model.
02908     QualType FromType = From->getType();
02909     if (FromType->isMemberPointerType())
02910       if (Context.getTargetInfo().getCXXABI().isMicrosoft())
02911         RequireCompleteType(From->getExprLoc(), FromType, 0);
02912 
02913     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
02914              .get();
02915     break;
02916   }
02917 
02918   case ICK_Boolean_Conversion:
02919     // Perform half-to-boolean conversion via float.
02920     if (From->getType()->isHalfType()) {
02921       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
02922       FromType = Context.FloatTy;
02923     }
02924 
02925     From = ImpCastExprToType(From, Context.BoolTy,
02926                              ScalarTypeToBooleanCastKind(FromType), 
02927                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02928     break;
02929 
02930   case ICK_Derived_To_Base: {
02931     CXXCastPath BasePath;
02932     if (CheckDerivedToBaseConversion(From->getType(),
02933                                      ToType.getNonReferenceType(),
02934                                      From->getLocStart(),
02935                                      From->getSourceRange(),
02936                                      &BasePath,
02937                                      CStyle))
02938       return ExprError();
02939 
02940     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
02941                       CK_DerivedToBase, From->getValueKind(),
02942                       &BasePath, CCK).get();
02943     break;
02944   }
02945 
02946   case ICK_Vector_Conversion:
02947     From = ImpCastExprToType(From, ToType, CK_BitCast, 
02948                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02949     break;
02950 
02951   case ICK_Vector_Splat:
02952     From = ImpCastExprToType(From, ToType, CK_VectorSplat, 
02953                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
02954     break;
02955 
02956   case ICK_Complex_Real:
02957     // Case 1.  x -> _Complex y
02958     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
02959       QualType ElType = ToComplex->getElementType();
02960       bool isFloatingComplex = ElType->isRealFloatingType();
02961 
02962       // x -> y
02963       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
02964         // do nothing
02965       } else if (From->getType()->isRealFloatingType()) {
02966         From = ImpCastExprToType(From, ElType,
02967                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
02968       } else {
02969         assert(From->getType()->isIntegerType());
02970         From = ImpCastExprToType(From, ElType,
02971                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
02972       }
02973       // y -> _Complex y
02974       From = ImpCastExprToType(From, ToType,
02975                    isFloatingComplex ? CK_FloatingRealToComplex
02976                                      : CK_IntegralRealToComplex).get();
02977 
02978     // Case 2.  _Complex x -> y
02979     } else {
02980       const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
02981       assert(FromComplex);
02982 
02983       QualType ElType = FromComplex->getElementType();
02984       bool isFloatingComplex = ElType->isRealFloatingType();
02985 
02986       // _Complex x -> x
02987       From = ImpCastExprToType(From, ElType,
02988                    isFloatingComplex ? CK_FloatingComplexToReal
02989                                      : CK_IntegralComplexToReal, 
02990                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
02991 
02992       // x -> y
02993       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
02994         // do nothing
02995       } else if (ToType->isRealFloatingType()) {
02996         From = ImpCastExprToType(From, ToType,
02997                    isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 
02998                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
02999       } else {
03000         assert(ToType->isIntegerType());
03001         From = ImpCastExprToType(From, ToType,
03002                    isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 
03003                                  VK_RValue, /*BasePath=*/nullptr, CCK).get();
03004       }
03005     }
03006     break;
03007   
03008   case ICK_Block_Pointer_Conversion: {
03009     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
03010                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
03011     break;
03012   }
03013       
03014   case ICK_TransparentUnionConversion: {
03015     ExprResult FromRes = From;
03016     Sema::AssignConvertType ConvTy =
03017       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
03018     if (FromRes.isInvalid())
03019       return ExprError();
03020     From = FromRes.get();
03021     assert ((ConvTy == Sema::Compatible) &&
03022             "Improper transparent union conversion");
03023     (void)ConvTy;
03024     break;
03025   }
03026 
03027   case ICK_Zero_Event_Conversion:
03028     From = ImpCastExprToType(From, ToType,
03029                              CK_ZeroToOCLEvent,
03030                              From->getValueKind()).get();
03031     break;
03032 
03033   case ICK_Lvalue_To_Rvalue:
03034   case ICK_Array_To_Pointer:
03035   case ICK_Function_To_Pointer:
03036   case ICK_Qualification:
03037   case ICK_Num_Conversion_Kinds:
03038     llvm_unreachable("Improper second standard conversion");
03039   }
03040 
03041   switch (SCS.Third) {
03042   case ICK_Identity:
03043     // Nothing to do.
03044     break;
03045 
03046   case ICK_Qualification: {
03047     // The qualification keeps the category of the inner expression, unless the
03048     // target type isn't a reference.
03049     ExprValueKind VK = ToType->isReferenceType() ?
03050                                   From->getValueKind() : VK_RValue;
03051     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
03052                              CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
03053 
03054     if (SCS.DeprecatedStringLiteralToCharPtr &&
03055         !getLangOpts().WritableStrings) {
03056       Diag(From->getLocStart(), getLangOpts().CPlusPlus11
03057            ? diag::ext_deprecated_string_literal_conversion
03058            : diag::warn_deprecated_string_literal_conversion)
03059         << ToType.getNonReferenceType();
03060     }
03061 
03062     break;
03063   }
03064 
03065   default:
03066     llvm_unreachable("Improper third standard conversion");
03067   }
03068 
03069   // If this conversion sequence involved a scalar -> atomic conversion, perform
03070   // that conversion now.
03071   if (!ToAtomicType.isNull()) {
03072     assert(Context.hasSameType(
03073         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
03074     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
03075                              VK_RValue, nullptr, CCK).get();
03076   }
03077 
03078   return From;
03079 }
03080 
03081 /// \brief Check the completeness of a type in a unary type trait.
03082 ///
03083 /// If the particular type trait requires a complete type, tries to complete
03084 /// it. If completing the type fails, a diagnostic is emitted and false
03085 /// returned. If completing the type succeeds or no completion was required,
03086 /// returns true.
03087 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
03088                                                 SourceLocation Loc,
03089                                                 QualType ArgTy) {
03090   // C++0x [meta.unary.prop]p3:
03091   //   For all of the class templates X declared in this Clause, instantiating
03092   //   that template with a template argument that is a class template
03093   //   specialization may result in the implicit instantiation of the template
03094   //   argument if and only if the semantics of X require that the argument
03095   //   must be a complete type.
03096   // We apply this rule to all the type trait expressions used to implement
03097   // these class templates. We also try to follow any GCC documented behavior
03098   // in these expressions to ensure portability of standard libraries.
03099   switch (UTT) {
03100   default: llvm_unreachable("not a UTT");
03101     // is_complete_type somewhat obviously cannot require a complete type.
03102   case UTT_IsCompleteType:
03103     // Fall-through
03104 
03105     // These traits are modeled on the type predicates in C++0x
03106     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
03107     // requiring a complete type, as whether or not they return true cannot be
03108     // impacted by the completeness of the type.
03109   case UTT_IsVoid:
03110   case UTT_IsIntegral:
03111   case UTT_IsFloatingPoint:
03112   case UTT_IsArray:
03113   case UTT_IsPointer:
03114   case UTT_IsLvalueReference:
03115   case UTT_IsRvalueReference:
03116   case UTT_IsMemberFunctionPointer:
03117   case UTT_IsMemberObjectPointer:
03118   case UTT_IsEnum:
03119   case UTT_IsUnion:
03120   case UTT_IsClass:
03121   case UTT_IsFunction:
03122   case UTT_IsReference:
03123   case UTT_IsArithmetic:
03124   case UTT_IsFundamental:
03125   case UTT_IsObject:
03126   case UTT_IsScalar:
03127   case UTT_IsCompound:
03128   case UTT_IsMemberPointer:
03129     // Fall-through
03130 
03131     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
03132     // which requires some of its traits to have the complete type. However,
03133     // the completeness of the type cannot impact these traits' semantics, and
03134     // so they don't require it. This matches the comments on these traits in
03135     // Table 49.
03136   case UTT_IsConst:
03137   case UTT_IsVolatile:
03138   case UTT_IsSigned:
03139   case UTT_IsUnsigned:
03140     return true;
03141 
03142     // C++0x [meta.unary.prop] Table 49 requires the following traits to be
03143     // applied to a complete type.
03144   case UTT_IsTrivial:
03145   case UTT_IsTriviallyCopyable:
03146   case UTT_IsStandardLayout:
03147   case UTT_IsPOD:
03148   case UTT_IsLiteral:
03149   case UTT_IsEmpty:
03150   case UTT_IsPolymorphic:
03151   case UTT_IsAbstract:
03152   case UTT_IsInterfaceClass:
03153   case UTT_IsDestructible:
03154   case UTT_IsNothrowDestructible:
03155     // Fall-through
03156 
03157   // These traits require a complete type.
03158   case UTT_IsFinal:
03159   case UTT_IsSealed:
03160 
03161     // These trait expressions are designed to help implement predicates in
03162     // [meta.unary.prop] despite not being named the same. They are specified
03163     // by both GCC and the Embarcadero C++ compiler, and require the complete
03164     // type due to the overarching C++0x type predicates being implemented
03165     // requiring the complete type.
03166   case UTT_HasNothrowAssign:
03167   case UTT_HasNothrowMoveAssign:
03168   case UTT_HasNothrowConstructor:
03169   case UTT_HasNothrowCopy:
03170   case UTT_HasTrivialAssign:
03171   case UTT_HasTrivialMoveAssign:
03172   case UTT_HasTrivialDefaultConstructor:
03173   case UTT_HasTrivialMoveConstructor:
03174   case UTT_HasTrivialCopy:
03175   case UTT_HasTrivialDestructor:
03176   case UTT_HasVirtualDestructor:
03177     // Arrays of unknown bound are expressly allowed.
03178     QualType ElTy = ArgTy;
03179     if (ArgTy->isIncompleteArrayType())
03180       ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
03181 
03182     // The void type is expressly allowed.
03183     if (ElTy->isVoidType())
03184       return true;
03185 
03186     return !S.RequireCompleteType(
03187       Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
03188   }
03189 }
03190 
03191 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
03192                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
03193                                bool (CXXRecordDecl::*HasTrivial)() const, 
03194                                bool (CXXRecordDecl::*HasNonTrivial)() const, 
03195                                bool (CXXMethodDecl::*IsDesiredOp)() const)
03196 {
03197   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
03198   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
03199     return true;
03200 
03201   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
03202   DeclarationNameInfo NameInfo(Name, KeyLoc);
03203   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
03204   if (Self.LookupQualifiedName(Res, RD)) {
03205     bool FoundOperator = false;
03206     Res.suppressDiagnostics();
03207     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
03208          Op != OpEnd; ++Op) {
03209       if (isa<FunctionTemplateDecl>(*Op))
03210         continue;
03211 
03212       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
03213       if((Operator->*IsDesiredOp)()) {
03214         FoundOperator = true;
03215         const FunctionProtoType *CPT =
03216           Operator->getType()->getAs<FunctionProtoType>();
03217         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
03218         if (!CPT || !CPT->isNothrow(C))
03219           return false;
03220       }
03221     }
03222     return FoundOperator;
03223   }
03224   return false;
03225 }
03226 
03227 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
03228                                    SourceLocation KeyLoc, QualType T) {
03229   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
03230 
03231   ASTContext &C = Self.Context;
03232   switch(UTT) {
03233   default: llvm_unreachable("not a UTT");
03234     // Type trait expressions corresponding to the primary type category
03235     // predicates in C++0x [meta.unary.cat].
03236   case UTT_IsVoid:
03237     return T->isVoidType();
03238   case UTT_IsIntegral:
03239     return T->isIntegralType(C);
03240   case UTT_IsFloatingPoint:
03241     return T->isFloatingType();
03242   case UTT_IsArray:
03243     return T->isArrayType();
03244   case UTT_IsPointer:
03245     return T->isPointerType();
03246   case UTT_IsLvalueReference:
03247     return T->isLValueReferenceType();
03248   case UTT_IsRvalueReference:
03249     return T->isRValueReferenceType();
03250   case UTT_IsMemberFunctionPointer:
03251     return T->isMemberFunctionPointerType();
03252   case UTT_IsMemberObjectPointer:
03253     return T->isMemberDataPointerType();
03254   case UTT_IsEnum:
03255     return T->isEnumeralType();
03256   case UTT_IsUnion:
03257     return T->isUnionType();
03258   case UTT_IsClass:
03259     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
03260   case UTT_IsFunction:
03261     return T->isFunctionType();
03262 
03263     // Type trait expressions which correspond to the convenient composition
03264     // predicates in C++0x [meta.unary.comp].
03265   case UTT_IsReference:
03266     return T->isReferenceType();
03267   case UTT_IsArithmetic:
03268     return T->isArithmeticType() && !T->isEnumeralType();
03269   case UTT_IsFundamental:
03270     return T->isFundamentalType();
03271   case UTT_IsObject:
03272     return T->isObjectType();
03273   case UTT_IsScalar:
03274     // Note: semantic analysis depends on Objective-C lifetime types to be
03275     // considered scalar types. However, such types do not actually behave
03276     // like scalar types at run time (since they may require retain/release
03277     // operations), so we report them as non-scalar.
03278     if (T->isObjCLifetimeType()) {
03279       switch (T.getObjCLifetime()) {
03280       case Qualifiers::OCL_None:
03281       case Qualifiers::OCL_ExplicitNone:
03282         return true;
03283 
03284       case Qualifiers::OCL_Strong:
03285       case Qualifiers::OCL_Weak:
03286       case Qualifiers::OCL_Autoreleasing:
03287         return false;
03288       }
03289     }
03290       
03291     return T->isScalarType();
03292   case UTT_IsCompound:
03293     return T->isCompoundType();
03294   case UTT_IsMemberPointer:
03295     return T->isMemberPointerType();
03296 
03297     // Type trait expressions which correspond to the type property predicates
03298     // in C++0x [meta.unary.prop].
03299   case UTT_IsConst:
03300     return T.isConstQualified();
03301   case UTT_IsVolatile:
03302     return T.isVolatileQualified();
03303   case UTT_IsTrivial:
03304     return T.isTrivialType(Self.Context);
03305   case UTT_IsTriviallyCopyable:
03306     return T.isTriviallyCopyableType(Self.Context);
03307   case UTT_IsStandardLayout:
03308     return T->isStandardLayoutType();
03309   case UTT_IsPOD:
03310     return T.isPODType(Self.Context);
03311   case UTT_IsLiteral:
03312     return T->isLiteralType(Self.Context);
03313   case UTT_IsEmpty:
03314     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03315       return !RD->isUnion() && RD->isEmpty();
03316     return false;
03317   case UTT_IsPolymorphic:
03318     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03319       return RD->isPolymorphic();
03320     return false;
03321   case UTT_IsAbstract:
03322     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03323       return RD->isAbstract();
03324     return false;
03325   case UTT_IsInterfaceClass:
03326     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03327       return RD->isInterface();
03328     return false;
03329   case UTT_IsFinal:
03330     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03331       return RD->hasAttr<FinalAttr>();
03332     return false;
03333   case UTT_IsSealed:
03334     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03335       if (FinalAttr *FA = RD->getAttr<FinalAttr>())
03336         return FA->isSpelledAsSealed();
03337     return false;
03338   case UTT_IsSigned:
03339     return T->isSignedIntegerType();
03340   case UTT_IsUnsigned:
03341     return T->isUnsignedIntegerType();
03342 
03343     // Type trait expressions which query classes regarding their construction,
03344     // destruction, and copying. Rather than being based directly on the
03345     // related type predicates in the standard, they are specified by both
03346     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
03347     // specifications.
03348     //
03349     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
03350     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
03351     //
03352     // Note that these builtins do not behave as documented in g++: if a class
03353     // has both a trivial and a non-trivial special member of a particular kind,
03354     // they return false! For now, we emulate this behavior.
03355     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
03356     // does not correctly compute triviality in the presence of multiple special
03357     // members of the same kind. Revisit this once the g++ bug is fixed.
03358   case UTT_HasTrivialDefaultConstructor:
03359     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03360     //   If __is_pod (type) is true then the trait is true, else if type is
03361     //   a cv class or union type (or array thereof) with a trivial default
03362     //   constructor ([class.ctor]) then the trait is true, else it is false.
03363     if (T.isPODType(Self.Context))
03364       return true;
03365     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
03366       return RD->hasTrivialDefaultConstructor() &&
03367              !RD->hasNonTrivialDefaultConstructor();
03368     return false;
03369   case UTT_HasTrivialMoveConstructor:
03370     //  This trait is implemented by MSVC 2012 and needed to parse the
03371     //  standard library headers. Specifically this is used as the logic
03372     //  behind std::is_trivially_move_constructible (20.9.4.3).
03373     if (T.isPODType(Self.Context))
03374       return true;
03375     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
03376       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
03377     return false;
03378   case UTT_HasTrivialCopy:
03379     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03380     //   If __is_pod (type) is true or type is a reference type then
03381     //   the trait is true, else if type is a cv class or union type
03382     //   with a trivial copy constructor ([class.copy]) then the trait
03383     //   is true, else it is false.
03384     if (T.isPODType(Self.Context) || T->isReferenceType())
03385       return true;
03386     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03387       return RD->hasTrivialCopyConstructor() &&
03388              !RD->hasNonTrivialCopyConstructor();
03389     return false;
03390   case UTT_HasTrivialMoveAssign:
03391     //  This trait is implemented by MSVC 2012 and needed to parse the
03392     //  standard library headers. Specifically it is used as the logic
03393     //  behind std::is_trivially_move_assignable (20.9.4.3)
03394     if (T.isPODType(Self.Context))
03395       return true;
03396     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
03397       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
03398     return false;
03399   case UTT_HasTrivialAssign:
03400     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03401     //   If type is const qualified or is a reference type then the
03402     //   trait is false. Otherwise if __is_pod (type) is true then the
03403     //   trait is true, else if type is a cv class or union type with
03404     //   a trivial copy assignment ([class.copy]) then the trait is
03405     //   true, else it is false.
03406     // Note: the const and reference restrictions are interesting,
03407     // given that const and reference members don't prevent a class
03408     // from having a trivial copy assignment operator (but do cause
03409     // errors if the copy assignment operator is actually used, q.v.
03410     // [class.copy]p12).
03411 
03412     if (T.isConstQualified())
03413       return false;
03414     if (T.isPODType(Self.Context))
03415       return true;
03416     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03417       return RD->hasTrivialCopyAssignment() &&
03418              !RD->hasNonTrivialCopyAssignment();
03419     return false;
03420   case UTT_IsDestructible:
03421   case UTT_IsNothrowDestructible:
03422     // FIXME: Implement UTT_IsDestructible and UTT_IsNothrowDestructible.
03423     // For now, let's fall through.
03424   case UTT_HasTrivialDestructor:
03425     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
03426     //   If __is_pod (type) is true or type is a reference type
03427     //   then the trait is true, else if type is a cv class or union
03428     //   type (or array thereof) with a trivial destructor
03429     //   ([class.dtor]) then the trait is true, else it is
03430     //   false.
03431     if (T.isPODType(Self.Context) || T->isReferenceType())
03432       return true;
03433       
03434     // Objective-C++ ARC: autorelease types don't require destruction.
03435     if (T->isObjCLifetimeType() && 
03436         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
03437       return true;
03438       
03439     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
03440       return RD->hasTrivialDestructor();
03441     return false;
03442   // TODO: Propagate nothrowness for implicitly declared special members.
03443   case UTT_HasNothrowAssign:
03444     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03445     //   If type is const qualified or is a reference type then the
03446     //   trait is false. Otherwise if __has_trivial_assign (type)
03447     //   is true then the trait is true, else if type is a cv class
03448     //   or union type with copy assignment operators that are known
03449     //   not to throw an exception then the trait is true, else it is
03450     //   false.
03451     if (C.getBaseElementType(T).isConstQualified())
03452       return false;
03453     if (T->isReferenceType())
03454       return false;
03455     if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
03456       return true;
03457 
03458     if (const RecordType *RT = T->getAs<RecordType>())
03459       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
03460                                 &CXXRecordDecl::hasTrivialCopyAssignment,
03461                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
03462                                 &CXXMethodDecl::isCopyAssignmentOperator);
03463     return false;
03464   case UTT_HasNothrowMoveAssign:
03465     //  This trait is implemented by MSVC 2012 and needed to parse the
03466     //  standard library headers. Specifically this is used as the logic
03467     //  behind std::is_nothrow_move_assignable (20.9.4.3).
03468     if (T.isPODType(Self.Context))
03469       return true;
03470 
03471     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
03472       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
03473                                 &CXXRecordDecl::hasTrivialMoveAssignment,
03474                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
03475                                 &CXXMethodDecl::isMoveAssignmentOperator);
03476     return false;
03477   case UTT_HasNothrowCopy:
03478     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03479     //   If __has_trivial_copy (type) is true then the trait is true, else
03480     //   if type is a cv class or union type with copy constructors that are
03481     //   known not to throw an exception then the trait is true, else it is
03482     //   false.
03483     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
03484       return true;
03485     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
03486       if (RD->hasTrivialCopyConstructor() &&
03487           !RD->hasNonTrivialCopyConstructor())
03488         return true;
03489 
03490       bool FoundConstructor = false;
03491       unsigned FoundTQs;
03492       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
03493       for (DeclContext::lookup_const_iterator Con = R.begin(),
03494            ConEnd = R.end(); Con != ConEnd; ++Con) {
03495         // A template constructor is never a copy constructor.
03496         // FIXME: However, it may actually be selected at the actual overload
03497         // resolution point.
03498         if (isa<FunctionTemplateDecl>(*Con))
03499           continue;
03500         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
03501         if (Constructor->isCopyConstructor(FoundTQs)) {
03502           FoundConstructor = true;
03503           const FunctionProtoType *CPT
03504               = Constructor->getType()->getAs<FunctionProtoType>();
03505           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
03506           if (!CPT)
03507             return false;
03508           // TODO: check whether evaluating default arguments can throw.
03509           // For now, we'll be conservative and assume that they can throw.
03510           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 1)
03511             return false;
03512         }
03513       }
03514 
03515       return FoundConstructor;
03516     }
03517     return false;
03518   case UTT_HasNothrowConstructor:
03519     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
03520     //   If __has_trivial_constructor (type) is true then the trait is
03521     //   true, else if type is a cv class or union type (or array
03522     //   thereof) with a default constructor that is known not to
03523     //   throw an exception then the trait is true, else it is false.
03524     if (T.isPODType(C) || T->isObjCLifetimeType())
03525       return true;
03526     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
03527       if (RD->hasTrivialDefaultConstructor() &&
03528           !RD->hasNonTrivialDefaultConstructor())
03529         return true;
03530 
03531       bool FoundConstructor = false;
03532       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
03533       for (DeclContext::lookup_const_iterator Con = R.begin(),
03534            ConEnd = R.end(); Con != ConEnd; ++Con) {
03535         // FIXME: In C++0x, a constructor template can be a default constructor.
03536         if (isa<FunctionTemplateDecl>(*Con))
03537           continue;
03538         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
03539         if (Constructor->isDefaultConstructor()) {
03540           FoundConstructor = true;
03541           const FunctionProtoType *CPT
03542               = Constructor->getType()->getAs<FunctionProtoType>();
03543           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
03544           if (!CPT)
03545             return false;
03546           // FIXME: check whether evaluating default arguments can throw.
03547           // For now, we'll be conservative and assume that they can throw.
03548           if (!CPT->isNothrow(Self.Context) || CPT->getNumParams() > 0)
03549             return false;
03550         }
03551       }
03552       return FoundConstructor;
03553     }
03554     return false;
03555   case UTT_HasVirtualDestructor:
03556     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
03557     //   If type is a class type with a virtual destructor ([class.dtor])
03558     //   then the trait is true, else it is false.
03559     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
03560       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
03561         return Destructor->isVirtual();
03562     return false;
03563 
03564     // These type trait expressions are modeled on the specifications for the
03565     // Embarcadero C++0x type trait functions:
03566     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
03567   case UTT_IsCompleteType:
03568     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
03569     //   Returns True if and only if T is a complete type at the point of the
03570     //   function call.
03571     return !T->isIncompleteType();
03572   }
03573 }
03574 
03575 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
03576 /// ARC mode.
03577 static bool hasNontrivialObjCLifetime(QualType T) {
03578   switch (T.getObjCLifetime()) {
03579   case Qualifiers::OCL_ExplicitNone:
03580     return false;
03581 
03582   case Qualifiers::OCL_Strong:
03583   case Qualifiers::OCL_Weak:
03584   case Qualifiers::OCL_Autoreleasing:
03585     return true;
03586 
03587   case Qualifiers::OCL_None:
03588     return T->isObjCLifetimeType();
03589   }
03590 
03591   llvm_unreachable("Unknown ObjC lifetime qualifier");
03592 }
03593 
03594 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
03595                                     QualType RhsT, SourceLocation KeyLoc);
03596 
03597 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
03598                               ArrayRef<TypeSourceInfo *> Args,
03599                               SourceLocation RParenLoc) {
03600   if (Kind <= UTT_Last)
03601     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
03602 
03603   if (Kind <= BTT_Last)
03604     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
03605                                    Args[1]->getType(), RParenLoc);
03606 
03607   switch (Kind) {
03608   case clang::TT_IsConstructible:
03609   case clang::TT_IsNothrowConstructible:
03610   case clang::TT_IsTriviallyConstructible: {
03611     // C++11 [meta.unary.prop]:
03612     //   is_trivially_constructible is defined as:
03613     //
03614     //     is_constructible<T, Args...>::value is true and the variable
03615     //     definition for is_constructible, as defined below, is known to call
03616     //     no operation that is not trivial.
03617     //
03618     //   The predicate condition for a template specialization 
03619     //   is_constructible<T, Args...> shall be satisfied if and only if the 
03620     //   following variable definition would be well-formed for some invented 
03621     //   variable t:
03622     //
03623     //     T t(create<Args>()...);
03624     assert(!Args.empty());
03625 
03626     // Precondition: T and all types in the parameter pack Args shall be
03627     // complete types, (possibly cv-qualified) void, or arrays of
03628     // unknown bound.
03629     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
03630       QualType ArgTy = Args[I]->getType();
03631       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
03632         continue;
03633 
03634       if (S.RequireCompleteType(KWLoc, ArgTy, 
03635           diag::err_incomplete_type_used_in_type_trait_expr))
03636         return false;
03637     }
03638 
03639     // Make sure the first argument is a complete type.
03640     if (Args[0]->getType()->isIncompleteType())
03641       return false;
03642 
03643     // Make sure the first argument is not an abstract type.
03644     CXXRecordDecl *RD = Args[0]->getType()->getAsCXXRecordDecl();
03645     if (RD && RD->isAbstract())
03646       return false;
03647 
03648     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
03649     SmallVector<Expr *, 2> ArgExprs;
03650     ArgExprs.reserve(Args.size() - 1);
03651     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
03652       QualType T = Args[I]->getType();
03653       if (T->isObjectType() || T->isFunctionType())
03654         T = S.Context.getRValueReferenceType(T);
03655       OpaqueArgExprs.push_back(
03656         OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
03657                         T.getNonLValueExprType(S.Context),
03658                         Expr::getValueKindForType(T)));
03659     }
03660     for (Expr &E : OpaqueArgExprs)
03661       ArgExprs.push_back(&E);
03662 
03663     // Perform the initialization in an unevaluated context within a SFINAE 
03664     // trap at translation unit scope.
03665     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
03666     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
03667     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
03668     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
03669     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
03670                                                                  RParenLoc));
03671     InitializationSequence Init(S, To, InitKind, ArgExprs);
03672     if (Init.Failed())
03673       return false;
03674 
03675     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
03676     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
03677       return false;
03678 
03679     if (Kind == clang::TT_IsConstructible)
03680       return true;
03681 
03682     if (Kind == clang::TT_IsNothrowConstructible)
03683       return S.canThrow(Result.get()) == CT_Cannot;
03684 
03685     if (Kind == clang::TT_IsTriviallyConstructible) {
03686       // Under Objective-C ARC, if the destination has non-trivial Objective-C
03687       // lifetime, this is a non-trivial construction.
03688       if (S.getLangOpts().ObjCAutoRefCount &&
03689           hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
03690         return false;
03691 
03692       // The initialization succeeded; now make sure there are no non-trivial
03693       // calls.
03694       return !Result.get()->hasNonTrivialCall(S.Context);
03695     }
03696 
03697     llvm_unreachable("unhandled type trait");
03698     return false;
03699   }
03700     default: llvm_unreachable("not a TT");
03701   }
03702   
03703   return false;
03704 }
03705 
03706 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 
03707                                 ArrayRef<TypeSourceInfo *> Args, 
03708                                 SourceLocation RParenLoc) {
03709   QualType ResultType = Context.getLogicalOperationType();
03710 
03711   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
03712                                *this, Kind, KWLoc, Args[0]->getType()))
03713     return ExprError();
03714 
03715   bool Dependent = false;
03716   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
03717     if (Args[I]->getType()->isDependentType()) {
03718       Dependent = true;
03719       break;
03720     }
03721   }
03722 
03723   bool Result = false;
03724   if (!Dependent)
03725     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
03726 
03727   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
03728                                RParenLoc, Result);
03729 }
03730 
03731 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
03732                                 ArrayRef<ParsedType> Args,
03733                                 SourceLocation RParenLoc) {
03734   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
03735   ConvertedArgs.reserve(Args.size());
03736   
03737   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
03738     TypeSourceInfo *TInfo;
03739     QualType T = GetTypeFromParser(Args[I], &TInfo);
03740     if (!TInfo)
03741       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
03742     
03743     ConvertedArgs.push_back(TInfo);    
03744   }
03745 
03746   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
03747 }
03748 
03749 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
03750                                     QualType RhsT, SourceLocation KeyLoc) {
03751   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
03752          "Cannot evaluate traits of dependent types");
03753 
03754   switch(BTT) {
03755   case BTT_IsBaseOf: {
03756     // C++0x [meta.rel]p2
03757     // Base is a base class of Derived without regard to cv-qualifiers or
03758     // Base and Derived are not unions and name the same class type without
03759     // regard to cv-qualifiers.
03760 
03761     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
03762     if (!lhsRecord) return false;
03763 
03764     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
03765     if (!rhsRecord) return false;
03766 
03767     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
03768              == (lhsRecord == rhsRecord));
03769 
03770     if (lhsRecord == rhsRecord)
03771       return !lhsRecord->getDecl()->isUnion();
03772 
03773     // C++0x [meta.rel]p2:
03774     //   If Base and Derived are class types and are different types
03775     //   (ignoring possible cv-qualifiers) then Derived shall be a
03776     //   complete type.
03777     if (Self.RequireCompleteType(KeyLoc, RhsT, 
03778                           diag::err_incomplete_type_used_in_type_trait_expr))
03779       return false;
03780 
03781     return cast<CXXRecordDecl>(rhsRecord->getDecl())
03782       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
03783   }
03784   case BTT_IsSame:
03785     return Self.Context.hasSameType(LhsT, RhsT);
03786   case BTT_TypeCompatible:
03787     return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
03788                                            RhsT.getUnqualifiedType());
03789   case BTT_IsConvertible:
03790   case BTT_IsConvertibleTo: {
03791     // C++0x [meta.rel]p4:
03792     //   Given the following function prototype:
03793     //
03794     //     template <class T> 
03795     //       typename add_rvalue_reference<T>::type create();
03796     //
03797     //   the predicate condition for a template specialization 
03798     //   is_convertible<From, To> shall be satisfied if and only if 
03799     //   the return expression in the following code would be 
03800     //   well-formed, including any implicit conversions to the return
03801     //   type of the function:
03802     //
03803     //     To test() { 
03804     //       return create<From>();
03805     //     }
03806     //
03807     //   Access checking is performed as if in a context unrelated to To and 
03808     //   From. Only the validity of the immediate context of the expression 
03809     //   of the return-statement (including conversions to the return type)
03810     //   is considered.
03811     //
03812     // We model the initialization as a copy-initialization of a temporary
03813     // of the appropriate type, which for this expression is identical to the
03814     // return statement (since NRVO doesn't apply).
03815 
03816     // Functions aren't allowed to return function or array types.
03817     if (RhsT->isFunctionType() || RhsT->isArrayType())
03818       return false;
03819 
03820     // A return statement in a void function must have void type.
03821     if (RhsT->isVoidType())
03822       return LhsT->isVoidType();
03823 
03824     // A function definition requires a complete, non-abstract return type.
03825     if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
03826         Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
03827       return false;
03828 
03829     // Compute the result of add_rvalue_reference.
03830     if (LhsT->isObjectType() || LhsT->isFunctionType())
03831       LhsT = Self.Context.getRValueReferenceType(LhsT);
03832 
03833     // Build a fake source and destination for initialization.
03834     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
03835     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
03836                          Expr::getValueKindForType(LhsT));
03837     Expr *FromPtr = &From;
03838     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 
03839                                                            SourceLocation()));
03840     
03841     // Perform the initialization in an unevaluated context within a SFINAE 
03842     // trap at translation unit scope.
03843     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
03844     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
03845     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
03846     InitializationSequence Init(Self, To, Kind, FromPtr);
03847     if (Init.Failed())
03848       return false;
03849 
03850     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
03851     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
03852   }
03853 
03854   case BTT_IsNothrowAssignable:
03855   case BTT_IsTriviallyAssignable: {
03856     // C++11 [meta.unary.prop]p3:
03857     //   is_trivially_assignable is defined as:
03858     //     is_assignable<T, U>::value is true and the assignment, as defined by
03859     //     is_assignable, is known to call no operation that is not trivial
03860     //
03861     //   is_assignable is defined as:
03862     //     The expression declval<T>() = declval<U>() is well-formed when 
03863     //     treated as an unevaluated operand (Clause 5).
03864     //
03865     //   For both, T and U shall be complete types, (possibly cv-qualified) 
03866     //   void, or arrays of unknown bound.
03867     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
03868         Self.RequireCompleteType(KeyLoc, LhsT, 
03869           diag::err_incomplete_type_used_in_type_trait_expr))
03870       return false;
03871     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
03872         Self.RequireCompleteType(KeyLoc, RhsT, 
03873           diag::err_incomplete_type_used_in_type_trait_expr))
03874       return false;
03875 
03876     // cv void is never assignable.
03877     if (LhsT->isVoidType() || RhsT->isVoidType())
03878       return false;
03879 
03880     // Build expressions that emulate the effect of declval<T>() and 
03881     // declval<U>().
03882     if (LhsT->isObjectType() || LhsT->isFunctionType())
03883       LhsT = Self.Context.getRValueReferenceType(LhsT);
03884     if (RhsT->isObjectType() || RhsT->isFunctionType())
03885       RhsT = Self.Context.getRValueReferenceType(RhsT);
03886     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
03887                         Expr::getValueKindForType(LhsT));
03888     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
03889                         Expr::getValueKindForType(RhsT));
03890     
03891     // Attempt the assignment in an unevaluated context within a SFINAE 
03892     // trap at translation unit scope.
03893     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
03894     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
03895     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
03896     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
03897                                         &Rhs);
03898     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
03899       return false;
03900 
03901     if (BTT == BTT_IsNothrowAssignable)
03902       return Self.canThrow(Result.get()) == CT_Cannot;
03903 
03904     if (BTT == BTT_IsTriviallyAssignable) {
03905       // Under Objective-C ARC, if the destination has non-trivial Objective-C
03906       // lifetime, this is a non-trivial assignment.
03907       if (Self.getLangOpts().ObjCAutoRefCount &&
03908           hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
03909         return false;
03910 
03911       return !Result.get()->hasNonTrivialCall(Self.Context);
03912     }
03913 
03914     llvm_unreachable("unhandled type trait");
03915     return false;
03916   }
03917     default: llvm_unreachable("not a BTT");
03918   }
03919   llvm_unreachable("Unknown type trait or not implemented");
03920 }
03921 
03922 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
03923                                      SourceLocation KWLoc,
03924                                      ParsedType Ty,
03925                                      Expr* DimExpr,
03926                                      SourceLocation RParen) {
03927   TypeSourceInfo *TSInfo;
03928   QualType T = GetTypeFromParser(Ty, &TSInfo);
03929   if (!TSInfo)
03930     TSInfo = Context.getTrivialTypeSourceInfo(T);
03931 
03932   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
03933 }
03934 
03935 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
03936                                            QualType T, Expr *DimExpr,
03937                                            SourceLocation KeyLoc) {
03938   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
03939 
03940   switch(ATT) {
03941   case ATT_ArrayRank:
03942     if (T->isArrayType()) {
03943       unsigned Dim = 0;
03944       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
03945         ++Dim;
03946         T = AT->getElementType();
03947       }
03948       return Dim;
03949     }
03950     return 0;
03951 
03952   case ATT_ArrayExtent: {
03953     llvm::APSInt Value;
03954     uint64_t Dim;
03955     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
03956           diag::err_dimension_expr_not_constant_integer,
03957           false).isInvalid())
03958       return 0;
03959     if (Value.isSigned() && Value.isNegative()) {
03960       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
03961         << DimExpr->getSourceRange();
03962       return 0;
03963     }
03964     Dim = Value.getLimitedValue();
03965 
03966     if (T->isArrayType()) {
03967       unsigned D = 0;
03968       bool Matched = false;
03969       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
03970         if (Dim == D) {
03971           Matched = true;
03972           break;
03973         }
03974         ++D;
03975         T = AT->getElementType();
03976       }
03977 
03978       if (Matched && T->isArrayType()) {
03979         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
03980           return CAT->getSize().getLimitedValue();
03981       }
03982     }
03983     return 0;
03984   }
03985   }
03986   llvm_unreachable("Unknown type trait or not implemented");
03987 }
03988 
03989 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
03990                                      SourceLocation KWLoc,
03991                                      TypeSourceInfo *TSInfo,
03992                                      Expr* DimExpr,
03993                                      SourceLocation RParen) {
03994   QualType T = TSInfo->getType();
03995 
03996   // FIXME: This should likely be tracked as an APInt to remove any host
03997   // assumptions about the width of size_t on the target.
03998   uint64_t Value = 0;
03999   if (!T->isDependentType())
04000     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
04001 
04002   // While the specification for these traits from the Embarcadero C++
04003   // compiler's documentation says the return type is 'unsigned int', Clang
04004   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
04005   // compiler, there is no difference. On several other platforms this is an
04006   // important distinction.
04007   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
04008                                           RParen, Context.getSizeType());
04009 }
04010 
04011 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
04012                                       SourceLocation KWLoc,
04013                                       Expr *Queried,
04014                                       SourceLocation RParen) {
04015   // If error parsing the expression, ignore.
04016   if (!Queried)
04017     return ExprError();
04018 
04019   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
04020 
04021   return Result;
04022 }
04023 
04024 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
04025   switch (ET) {
04026   case ET_IsLValueExpr: return E->isLValue();
04027   case ET_IsRValueExpr: return E->isRValue();
04028   }
04029   llvm_unreachable("Expression trait not covered by switch");
04030 }
04031 
04032 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
04033                                       SourceLocation KWLoc,
04034                                       Expr *Queried,
04035                                       SourceLocation RParen) {
04036   if (Queried->isTypeDependent()) {
04037     // Delay type-checking for type-dependent expressions.
04038   } else if (Queried->getType()->isPlaceholderType()) {
04039     ExprResult PE = CheckPlaceholderExpr(Queried);
04040     if (PE.isInvalid()) return ExprError();
04041     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
04042   }
04043 
04044   bool Value = EvaluateExpressionTrait(ET, Queried);
04045 
04046   return new (Context)
04047       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
04048 }
04049 
04050 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
04051                                             ExprValueKind &VK,
04052                                             SourceLocation Loc,
04053                                             bool isIndirect) {
04054   assert(!LHS.get()->getType()->isPlaceholderType() &&
04055          !RHS.get()->getType()->isPlaceholderType() &&
04056          "placeholders should have been weeded out by now");
04057 
04058   // The LHS undergoes lvalue conversions if this is ->*.
04059   if (isIndirect) {
04060     LHS = DefaultLvalueConversion(LHS.get());
04061     if (LHS.isInvalid()) return QualType();
04062   }
04063 
04064   // The RHS always undergoes lvalue conversions.
04065   RHS = DefaultLvalueConversion(RHS.get());
04066   if (RHS.isInvalid()) return QualType();
04067 
04068   const char *OpSpelling = isIndirect ? "->*" : ".*";
04069   // C++ 5.5p2
04070   //   The binary operator .* [p3: ->*] binds its second operand, which shall
04071   //   be of type "pointer to member of T" (where T is a completely-defined
04072   //   class type) [...]
04073   QualType RHSType = RHS.get()->getType();
04074   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
04075   if (!MemPtr) {
04076     Diag(Loc, diag::err_bad_memptr_rhs)
04077       << OpSpelling << RHSType << RHS.get()->getSourceRange();
04078     return QualType();
04079   }
04080 
04081   QualType Class(MemPtr->getClass(), 0);
04082 
04083   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
04084   // member pointer points must be completely-defined. However, there is no
04085   // reason for this semantic distinction, and the rule is not enforced by
04086   // other compilers. Therefore, we do not check this property, as it is
04087   // likely to be considered a defect.
04088 
04089   // C++ 5.5p2
04090   //   [...] to its first operand, which shall be of class T or of a class of
04091   //   which T is an unambiguous and accessible base class. [p3: a pointer to
04092   //   such a class]
04093   QualType LHSType = LHS.get()->getType();
04094   if (isIndirect) {
04095     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
04096       LHSType = Ptr->getPointeeType();
04097     else {
04098       Diag(Loc, diag::err_bad_memptr_lhs)
04099         << OpSpelling << 1 << LHSType
04100         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
04101       return QualType();
04102     }
04103   }
04104 
04105   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
04106     // If we want to check the hierarchy, we need a complete type.
04107     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
04108                             OpSpelling, (int)isIndirect)) {
04109       return QualType();
04110     }
04111 
04112     if (!IsDerivedFrom(LHSType, Class)) {
04113       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
04114         << (int)isIndirect << LHS.get()->getType();
04115       return QualType();
04116     }
04117 
04118     CXXCastPath BasePath;
04119     if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
04120                                      SourceRange(LHS.get()->getLocStart(),
04121                                                  RHS.get()->getLocEnd()),
04122                                      &BasePath))
04123       return QualType();
04124 
04125     // Cast LHS to type of use.
04126     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
04127     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
04128     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
04129                             &BasePath);
04130   }
04131 
04132   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
04133     // Diagnose use of pointer-to-member type which when used as
04134     // the functional cast in a pointer-to-member expression.
04135     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
04136      return QualType();
04137   }
04138 
04139   // C++ 5.5p2
04140   //   The result is an object or a function of the type specified by the
04141   //   second operand.
04142   // The cv qualifiers are the union of those in the pointer and the left side,
04143   // in accordance with 5.5p5 and 5.2.5.
04144   QualType Result = MemPtr->getPointeeType();
04145   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
04146 
04147   // C++0x [expr.mptr.oper]p6:
04148   //   In a .* expression whose object expression is an rvalue, the program is
04149   //   ill-formed if the second operand is a pointer to member function with
04150   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
04151   //   expression is an lvalue, the program is ill-formed if the second operand
04152   //   is a pointer to member function with ref-qualifier &&.
04153   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
04154     switch (Proto->getRefQualifier()) {
04155     case RQ_None:
04156       // Do nothing
04157       break;
04158 
04159     case RQ_LValue:
04160       if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
04161         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
04162           << RHSType << 1 << LHS.get()->getSourceRange();
04163       break;
04164 
04165     case RQ_RValue:
04166       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
04167         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
04168           << RHSType << 0 << LHS.get()->getSourceRange();
04169       break;
04170     }
04171   }
04172 
04173   // C++ [expr.mptr.oper]p6:
04174   //   The result of a .* expression whose second operand is a pointer
04175   //   to a data member is of the same value category as its
04176   //   first operand. The result of a .* expression whose second
04177   //   operand is a pointer to a member function is a prvalue. The
04178   //   result of an ->* expression is an lvalue if its second operand
04179   //   is a pointer to data member and a prvalue otherwise.
04180   if (Result->isFunctionType()) {
04181     VK = VK_RValue;
04182     return Context.BoundMemberTy;
04183   } else if (isIndirect) {
04184     VK = VK_LValue;
04185   } else {
04186     VK = LHS.get()->getValueKind();
04187   }
04188 
04189   return Result;
04190 }
04191 
04192 /// \brief Try to convert a type to another according to C++0x 5.16p3.
04193 ///
04194 /// This is part of the parameter validation for the ? operator. If either
04195 /// value operand is a class type, the two operands are attempted to be
04196 /// converted to each other. This function does the conversion in one direction.
04197 /// It returns true if the program is ill-formed and has already been diagnosed
04198 /// as such.
04199 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
04200                                 SourceLocation QuestionLoc,
04201                                 bool &HaveConversion,
04202                                 QualType &ToType) {
04203   HaveConversion = false;
04204   ToType = To->getType();
04205 
04206   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
04207                                                            SourceLocation());
04208   // C++0x 5.16p3
04209   //   The process for determining whether an operand expression E1 of type T1
04210   //   can be converted to match an operand expression E2 of type T2 is defined
04211   //   as follows:
04212   //   -- If E2 is an lvalue:
04213   bool ToIsLvalue = To->isLValue();
04214   if (ToIsLvalue) {
04215     //   E1 can be converted to match E2 if E1 can be implicitly converted to
04216     //   type "lvalue reference to T2", subject to the constraint that in the
04217     //   conversion the reference must bind directly to E1.
04218     QualType T = Self.Context.getLValueReferenceType(ToType);
04219     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
04220 
04221     InitializationSequence InitSeq(Self, Entity, Kind, From);
04222     if (InitSeq.isDirectReferenceBinding()) {
04223       ToType = T;
04224       HaveConversion = true;
04225       return false;
04226     }
04227 
04228     if (InitSeq.isAmbiguous())
04229       return InitSeq.Diagnose(Self, Entity, Kind, From);
04230   }
04231 
04232   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
04233   //      -- if E1 and E2 have class type, and the underlying class types are
04234   //         the same or one is a base class of the other:
04235   QualType FTy = From->getType();
04236   QualType TTy = To->getType();
04237   const RecordType *FRec = FTy->getAs<RecordType>();
04238   const RecordType *TRec = TTy->getAs<RecordType>();
04239   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
04240                        Self.IsDerivedFrom(FTy, TTy);
04241   if (FRec && TRec &&
04242       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
04243     //         E1 can be converted to match E2 if the class of T2 is the
04244     //         same type as, or a base class of, the class of T1, and
04245     //         [cv2 > cv1].
04246     if (FRec == TRec || FDerivedFromT) {
04247       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
04248         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
04249         InitializationSequence InitSeq(Self, Entity, Kind, From);
04250         if (InitSeq) {
04251           HaveConversion = true;
04252           return false;
04253         }
04254 
04255         if (InitSeq.isAmbiguous())
04256           return InitSeq.Diagnose(Self, Entity, Kind, From);
04257       }
04258     }
04259 
04260     return false;
04261   }
04262 
04263   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
04264   //        implicitly converted to the type that expression E2 would have
04265   //        if E2 were converted to an rvalue (or the type it has, if E2 is
04266   //        an rvalue).
04267   //
04268   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
04269   // to the array-to-pointer or function-to-pointer conversions.
04270   if (!TTy->getAs<TagType>())
04271     TTy = TTy.getUnqualifiedType();
04272 
04273   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
04274   InitializationSequence InitSeq(Self, Entity, Kind, From);
04275   HaveConversion = !InitSeq.Failed();
04276   ToType = TTy;
04277   if (InitSeq.isAmbiguous())
04278     return InitSeq.Diagnose(Self, Entity, Kind, From);
04279 
04280   return false;
04281 }
04282 
04283 /// \brief Try to find a common type for two according to C++0x 5.16p5.
04284 ///
04285 /// This is part of the parameter validation for the ? operator. If either
04286 /// value operand is a class type, overload resolution is used to find a
04287 /// conversion to a common type.
04288 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
04289                                     SourceLocation QuestionLoc) {
04290   Expr *Args[2] = { LHS.get(), RHS.get() };
04291   OverloadCandidateSet CandidateSet(QuestionLoc,
04292                                     OverloadCandidateSet::CSK_Operator);
04293   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
04294                                     CandidateSet);
04295 
04296   OverloadCandidateSet::iterator Best;
04297   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
04298     case OR_Success: {
04299       // We found a match. Perform the conversions on the arguments and move on.
04300       ExprResult LHSRes =
04301         Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
04302                                        Best->Conversions[0], Sema::AA_Converting);
04303       if (LHSRes.isInvalid())
04304         break;
04305       LHS = LHSRes;
04306 
04307       ExprResult RHSRes =
04308         Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
04309                                        Best->Conversions[1], Sema::AA_Converting);
04310       if (RHSRes.isInvalid())
04311         break;
04312       RHS = RHSRes;
04313       if (Best->Function)
04314         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
04315       return false;
04316     }
04317     
04318     case OR_No_Viable_Function:
04319 
04320       // Emit a better diagnostic if one of the expressions is a null pointer
04321       // constant and the other is a pointer type. In this case, the user most
04322       // likely forgot to take the address of the other expression.
04323       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
04324         return true;
04325 
04326       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04327         << LHS.get()->getType() << RHS.get()->getType()
04328         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04329       return true;
04330 
04331     case OR_Ambiguous:
04332       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
04333         << LHS.get()->getType() << RHS.get()->getType()
04334         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04335       // FIXME: Print the possible common types by printing the return types of
04336       // the viable candidates.
04337       break;
04338 
04339     case OR_Deleted:
04340       llvm_unreachable("Conditional operator has only built-in overloads");
04341   }
04342   return true;
04343 }
04344 
04345 /// \brief Perform an "extended" implicit conversion as returned by
04346 /// TryClassUnification.
04347 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
04348   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
04349   InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
04350                                                            SourceLocation());
04351   Expr *Arg = E.get();
04352   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
04353   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
04354   if (Result.isInvalid())
04355     return true;
04356 
04357   E = Result;
04358   return false;
04359 }
04360 
04361 /// \brief Check the operands of ?: under C++ semantics.
04362 ///
04363 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
04364 /// extension. In this case, LHS == Cond. (But they're not aliases.)
04365 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
04366                                            ExprResult &RHS, ExprValueKind &VK,
04367                                            ExprObjectKind &OK,
04368                                            SourceLocation QuestionLoc) {
04369   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
04370   // interface pointers.
04371 
04372   // C++11 [expr.cond]p1
04373   //   The first expression is contextually converted to bool.
04374   if (!Cond.get()->isTypeDependent()) {
04375     ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
04376     if (CondRes.isInvalid())
04377       return QualType();
04378     Cond = CondRes;
04379   }
04380 
04381   // Assume r-value.
04382   VK = VK_RValue;
04383   OK = OK_Ordinary;
04384 
04385   // Either of the arguments dependent?
04386   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
04387     return Context.DependentTy;
04388 
04389   // C++11 [expr.cond]p2
04390   //   If either the second or the third operand has type (cv) void, ...
04391   QualType LTy = LHS.get()->getType();
04392   QualType RTy = RHS.get()->getType();
04393   bool LVoid = LTy->isVoidType();
04394   bool RVoid = RTy->isVoidType();
04395   if (LVoid || RVoid) {
04396     //   ... one of the following shall hold:
04397     //   -- The second or the third operand (but not both) is a (possibly
04398     //      parenthesized) throw-expression; the result is of the type
04399     //      and value category of the other.
04400     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
04401     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
04402     if (LThrow != RThrow) {
04403       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
04404       VK = NonThrow->getValueKind();
04405       // DR (no number yet): the result is a bit-field if the
04406       // non-throw-expression operand is a bit-field.
04407       OK = NonThrow->getObjectKind();
04408       return NonThrow->getType();
04409     }
04410 
04411     //   -- Both the second and third operands have type void; the result is of
04412     //      type void and is a prvalue.
04413     if (LVoid && RVoid)
04414       return Context.VoidTy;
04415 
04416     // Neither holds, error.
04417     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
04418       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
04419       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04420     return QualType();
04421   }
04422 
04423   // Neither is void.
04424 
04425   // C++11 [expr.cond]p3
04426   //   Otherwise, if the second and third operand have different types, and
04427   //   either has (cv) class type [...] an attempt is made to convert each of
04428   //   those operands to the type of the other.
04429   if (!Context.hasSameType(LTy, RTy) &&
04430       (LTy->isRecordType() || RTy->isRecordType())) {
04431     // These return true if a single direction is already ambiguous.
04432     QualType L2RType, R2LType;
04433     bool HaveL2R, HaveR2L;
04434     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
04435       return QualType();
04436     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
04437       return QualType();
04438 
04439     //   If both can be converted, [...] the program is ill-formed.
04440     if (HaveL2R && HaveR2L) {
04441       Diag(QuestionLoc, diag::err_conditional_ambiguous)
04442         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04443       return QualType();
04444     }
04445 
04446     //   If exactly one conversion is possible, that conversion is applied to
04447     //   the chosen operand and the converted operands are used in place of the
04448     //   original operands for the remainder of this section.
04449     if (HaveL2R) {
04450       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
04451         return QualType();
04452       LTy = LHS.get()->getType();
04453     } else if (HaveR2L) {
04454       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
04455         return QualType();
04456       RTy = RHS.get()->getType();
04457     }
04458   }
04459 
04460   // C++11 [expr.cond]p3
04461   //   if both are glvalues of the same value category and the same type except
04462   //   for cv-qualification, an attempt is made to convert each of those
04463   //   operands to the type of the other.
04464   ExprValueKind LVK = LHS.get()->getValueKind();
04465   ExprValueKind RVK = RHS.get()->getValueKind();
04466   if (!Context.hasSameType(LTy, RTy) &&
04467       Context.hasSameUnqualifiedType(LTy, RTy) &&
04468       LVK == RVK && LVK != VK_RValue) {
04469     // Since the unqualified types are reference-related and we require the
04470     // result to be as if a reference bound directly, the only conversion
04471     // we can perform is to add cv-qualifiers.
04472     Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
04473     Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
04474     if (RCVR.isStrictSupersetOf(LCVR)) {
04475       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
04476       LTy = LHS.get()->getType();
04477     }
04478     else if (LCVR.isStrictSupersetOf(RCVR)) {
04479       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
04480       RTy = RHS.get()->getType();
04481     }
04482   }
04483 
04484   // C++11 [expr.cond]p4
04485   //   If the second and third operands are glvalues of the same value
04486   //   category and have the same type, the result is of that type and
04487   //   value category and it is a bit-field if the second or the third
04488   //   operand is a bit-field, or if both are bit-fields.
04489   // We only extend this to bitfields, not to the crazy other kinds of
04490   // l-values.
04491   bool Same = Context.hasSameType(LTy, RTy);
04492   if (Same && LVK == RVK && LVK != VK_RValue &&
04493       LHS.get()->isOrdinaryOrBitFieldObject() &&
04494       RHS.get()->isOrdinaryOrBitFieldObject()) {
04495     VK = LHS.get()->getValueKind();
04496     if (LHS.get()->getObjectKind() == OK_BitField ||
04497         RHS.get()->getObjectKind() == OK_BitField)
04498       OK = OK_BitField;
04499     return LTy;
04500   }
04501 
04502   // C++11 [expr.cond]p5
04503   //   Otherwise, the result is a prvalue. If the second and third operands
04504   //   do not have the same type, and either has (cv) class type, ...
04505   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
04506     //   ... overload resolution is used to determine the conversions (if any)
04507     //   to be applied to the operands. If the overload resolution fails, the
04508     //   program is ill-formed.
04509     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
04510       return QualType();
04511   }
04512 
04513   // C++11 [expr.cond]p6
04514   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
04515   //   conversions are performed on the second and third operands.
04516   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
04517   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
04518   if (LHS.isInvalid() || RHS.isInvalid())
04519     return QualType();
04520   LTy = LHS.get()->getType();
04521   RTy = RHS.get()->getType();
04522 
04523   //   After those conversions, one of the following shall hold:
04524   //   -- The second and third operands have the same type; the result
04525   //      is of that type. If the operands have class type, the result
04526   //      is a prvalue temporary of the result type, which is
04527   //      copy-initialized from either the second operand or the third
04528   //      operand depending on the value of the first operand.
04529   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
04530     if (LTy->isRecordType()) {
04531       // The operands have class type. Make a temporary copy.
04532       if (RequireNonAbstractType(QuestionLoc, LTy,
04533                                  diag::err_allocation_of_abstract_type))
04534         return QualType();
04535       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
04536 
04537       ExprResult LHSCopy = PerformCopyInitialization(Entity,
04538                                                      SourceLocation(),
04539                                                      LHS);
04540       if (LHSCopy.isInvalid())
04541         return QualType();
04542 
04543       ExprResult RHSCopy = PerformCopyInitialization(Entity,
04544                                                      SourceLocation(),
04545                                                      RHS);
04546       if (RHSCopy.isInvalid())
04547         return QualType();
04548 
04549       LHS = LHSCopy;
04550       RHS = RHSCopy;
04551     }
04552 
04553     return LTy;
04554   }
04555 
04556   // Extension: conditional operator involving vector types.
04557   if (LTy->isVectorType() || RTy->isVectorType())
04558     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
04559 
04560   //   -- The second and third operands have arithmetic or enumeration type;
04561   //      the usual arithmetic conversions are performed to bring them to a
04562   //      common type, and the result is of that type.
04563   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
04564     QualType ResTy = UsualArithmeticConversions(LHS, RHS);
04565     if (LHS.isInvalid() || RHS.isInvalid())
04566       return QualType();
04567 
04568     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
04569     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
04570 
04571     return ResTy;
04572   }
04573 
04574   //   -- The second and third operands have pointer type, or one has pointer
04575   //      type and the other is a null pointer constant, or both are null
04576   //      pointer constants, at least one of which is non-integral; pointer
04577   //      conversions and qualification conversions are performed to bring them
04578   //      to their composite pointer type. The result is of the composite
04579   //      pointer type.
04580   //   -- The second and third operands have pointer to member type, or one has
04581   //      pointer to member type and the other is a null pointer constant;
04582   //      pointer to member conversions and qualification conversions are
04583   //      performed to bring them to a common type, whose cv-qualification
04584   //      shall match the cv-qualification of either the second or the third
04585   //      operand. The result is of the common type.
04586   bool NonStandardCompositeType = false;
04587   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
04588                                  isSFINAEContext() ? nullptr
04589                                                    : &NonStandardCompositeType);
04590   if (!Composite.isNull()) {
04591     if (NonStandardCompositeType)
04592       Diag(QuestionLoc,
04593            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
04594         << LTy << RTy << Composite
04595         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04596 
04597     return Composite;
04598   }
04599 
04600   // Similarly, attempt to find composite type of two objective-c pointers.
04601   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
04602   if (!Composite.isNull())
04603     return Composite;
04604 
04605   // Check if we are using a null with a non-pointer type.
04606   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
04607     return QualType();
04608 
04609   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
04610     << LHS.get()->getType() << RHS.get()->getType()
04611     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
04612   return QualType();
04613 }
04614 
04615 /// \brief Find a merged pointer type and convert the two expressions to it.
04616 ///
04617 /// This finds the composite pointer type (or member pointer type) for @p E1
04618 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
04619 /// type and returns it.
04620 /// It does not emit diagnostics.
04621 ///
04622 /// \param Loc The location of the operator requiring these two expressions to
04623 /// be converted to the composite pointer type.
04624 ///
04625 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
04626 /// a non-standard (but still sane) composite type to which both expressions
04627 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
04628 /// will be set true.
04629 QualType Sema::FindCompositePointerType(SourceLocation Loc,
04630                                         Expr *&E1, Expr *&E2,
04631                                         bool *NonStandardCompositeType) {
04632   if (NonStandardCompositeType)
04633     *NonStandardCompositeType = false;
04634 
04635   assert(getLangOpts().CPlusPlus && "This function assumes C++");
04636   QualType T1 = E1->getType(), T2 = E2->getType();
04637 
04638   // C++11 5.9p2
04639   //   Pointer conversions and qualification conversions are performed on
04640   //   pointer operands to bring them to their composite pointer type. If
04641   //   one operand is a null pointer constant, the composite pointer type is
04642   //   std::nullptr_t if the other operand is also a null pointer constant or,
04643   //   if the other operand is a pointer, the type of the other operand.
04644   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
04645       !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
04646     if (T1->isNullPtrType() &&
04647         E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04648       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
04649       return T1;
04650     }
04651     if (T2->isNullPtrType() &&
04652         E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04653       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
04654       return T2;
04655     }
04656     return QualType();
04657   }
04658 
04659   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04660     if (T2->isMemberPointerType())
04661       E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
04662     else
04663       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
04664     return T2;
04665   }
04666   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
04667     if (T1->isMemberPointerType())
04668       E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
04669     else
04670       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
04671     return T1;
04672   }
04673 
04674   // Now both have to be pointers or member pointers.
04675   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
04676       (!T2->isPointerType() && !T2->isMemberPointerType()))
04677     return QualType();
04678 
04679   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
04680   //   the other has type "pointer to cv2 T" and the composite pointer type is
04681   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
04682   //   Otherwise, the composite pointer type is a pointer type similar to the
04683   //   type of one of the operands, with a cv-qualification signature that is
04684   //   the union of the cv-qualification signatures of the operand types.
04685   // In practice, the first part here is redundant; it's subsumed by the second.
04686   // What we do here is, we build the two possible composite types, and try the
04687   // conversions in both directions. If only one works, or if the two composite
04688   // types are the same, we have succeeded.
04689   // FIXME: extended qualifiers?
04690   typedef SmallVector<unsigned, 4> QualifierVector;
04691   QualifierVector QualifierUnion;
04692   typedef SmallVector<std::pair<const Type *, const Type *>, 4>
04693       ContainingClassVector;
04694   ContainingClassVector MemberOfClass;
04695   QualType Composite1 = Context.getCanonicalType(T1),
04696            Composite2 = Context.getCanonicalType(T2);
04697   unsigned NeedConstBefore = 0;
04698   do {
04699     const PointerType *Ptr1, *Ptr2;
04700     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
04701         (Ptr2 = Composite2->getAs<PointerType>())) {
04702       Composite1 = Ptr1->getPointeeType();
04703       Composite2 = Ptr2->getPointeeType();
04704 
04705       // If we're allowed to create a non-standard composite type, keep track
04706       // of where we need to fill in additional 'const' qualifiers.
04707       if (NonStandardCompositeType &&
04708           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
04709         NeedConstBefore = QualifierUnion.size();
04710 
04711       QualifierUnion.push_back(
04712                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
04713       MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
04714       continue;
04715     }
04716 
04717     const MemberPointerType *MemPtr1, *MemPtr2;
04718     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
04719         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
04720       Composite1 = MemPtr1->getPointeeType();
04721       Composite2 = MemPtr2->getPointeeType();
04722 
04723       // If we're allowed to create a non-standard composite type, keep track
04724       // of where we need to fill in additional 'const' qualifiers.
04725       if (NonStandardCompositeType &&
04726           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
04727         NeedConstBefore = QualifierUnion.size();
04728 
04729       QualifierUnion.push_back(
04730                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
04731       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
04732                                              MemPtr2->getClass()));
04733       continue;
04734     }
04735 
04736     // FIXME: block pointer types?
04737 
04738     // Cannot unwrap any more types.
04739     break;
04740   } while (true);
04741 
04742   if (NeedConstBefore && NonStandardCompositeType) {
04743     // Extension: Add 'const' to qualifiers that come before the first qualifier
04744     // mismatch, so that our (non-standard!) composite type meets the
04745     // requirements of C++ [conv.qual]p4 bullet 3.
04746     for (unsigned I = 0; I != NeedConstBefore; ++I) {
04747       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
04748         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
04749         *NonStandardCompositeType = true;
04750       }
04751     }
04752   }
04753 
04754   // Rewrap the composites as pointers or member pointers with the union CVRs.
04755   ContainingClassVector::reverse_iterator MOC
04756     = MemberOfClass.rbegin();
04757   for (QualifierVector::reverse_iterator
04758          I = QualifierUnion.rbegin(),
04759          E = QualifierUnion.rend();
04760        I != E; (void)++I, ++MOC) {
04761     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
04762     if (MOC->first && MOC->second) {
04763       // Rebuild member pointer type
04764       Composite1 = Context.getMemberPointerType(
04765                                     Context.getQualifiedType(Composite1, Quals),
04766                                     MOC->first);
04767       Composite2 = Context.getMemberPointerType(
04768                                     Context.getQualifiedType(Composite2, Quals),
04769                                     MOC->second);
04770     } else {
04771       // Rebuild pointer type
04772       Composite1
04773         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
04774       Composite2
04775         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
04776     }
04777   }
04778 
04779   // Try to convert to the first composite pointer type.
04780   InitializedEntity Entity1
04781     = InitializedEntity::InitializeTemporary(Composite1);
04782   InitializationKind Kind
04783     = InitializationKind::CreateCopy(Loc, SourceLocation());
04784   InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
04785   InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
04786 
04787   if (E1ToC1 && E2ToC1) {
04788     // Conversion to Composite1 is viable.
04789     if (!Context.hasSameType(Composite1, Composite2)) {
04790       // Composite2 is a different type from Composite1. Check whether
04791       // Composite2 is also viable.
04792       InitializedEntity Entity2
04793         = InitializedEntity::InitializeTemporary(Composite2);
04794       InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
04795       InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
04796       if (E1ToC2 && E2ToC2) {
04797         // Both Composite1 and Composite2 are viable and are different;
04798         // this is an ambiguity.
04799         return QualType();
04800       }
04801     }
04802 
04803     // Convert E1 to Composite1
04804     ExprResult E1Result
04805       = E1ToC1.Perform(*this, Entity1, Kind, E1);
04806     if (E1Result.isInvalid())
04807       return QualType();
04808     E1 = E1Result.getAs<Expr>();
04809 
04810     // Convert E2 to Composite1
04811     ExprResult E2Result
04812       = E2ToC1.Perform(*this, Entity1, Kind, E2);
04813     if (E2Result.isInvalid())
04814       return QualType();
04815     E2 = E2Result.getAs<Expr>();
04816 
04817     return Composite1;
04818   }
04819 
04820   // Check whether Composite2 is viable.
04821   InitializedEntity Entity2
04822     = InitializedEntity::InitializeTemporary(Composite2);
04823   InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
04824   InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
04825   if (!E1ToC2 || !E2ToC2)
04826     return QualType();
04827 
04828   // Convert E1 to Composite2
04829   ExprResult E1Result
04830     = E1ToC2.Perform(*this, Entity2, Kind, E1);
04831   if (E1Result.isInvalid())
04832     return QualType();
04833   E1 = E1Result.getAs<Expr>();
04834 
04835   // Convert E2 to Composite2
04836   ExprResult E2Result
04837     = E2ToC2.Perform(*this, Entity2, Kind, E2);
04838   if (E2Result.isInvalid())
04839     return QualType();
04840   E2 = E2Result.getAs<Expr>();
04841 
04842   return Composite2;
04843 }
04844 
04845 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
04846   if (!E)
04847     return ExprError();
04848 
04849   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
04850 
04851   // If the result is a glvalue, we shouldn't bind it.
04852   if (!E->isRValue())
04853     return E;
04854 
04855   // In ARC, calls that return a retainable type can return retained,
04856   // in which case we have to insert a consuming cast.
04857   if (getLangOpts().ObjCAutoRefCount &&
04858       E->getType()->isObjCRetainableType()) {
04859 
04860     bool ReturnsRetained;
04861 
04862     // For actual calls, we compute this by examining the type of the
04863     // called value.
04864     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
04865       Expr *Callee = Call->getCallee()->IgnoreParens();
04866       QualType T = Callee->getType();
04867 
04868       if (T == Context.BoundMemberTy) {
04869         // Handle pointer-to-members.
04870         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
04871           T = BinOp->getRHS()->getType();
04872         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
04873           T = Mem->getMemberDecl()->getType();
04874       }
04875       
04876       if (const PointerType *Ptr = T->getAs<PointerType>())
04877         T = Ptr->getPointeeType();
04878       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
04879         T = Ptr->getPointeeType();
04880       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
04881         T = MemPtr->getPointeeType();
04882       
04883       const FunctionType *FTy = T->getAs<FunctionType>();
04884       assert(FTy && "call to value not of function type?");
04885       ReturnsRetained = FTy->getExtInfo().getProducesResult();
04886 
04887     // ActOnStmtExpr arranges things so that StmtExprs of retainable
04888     // type always produce a +1 object.
04889     } else if (isa<StmtExpr>(E)) {
04890       ReturnsRetained = true;
04891 
04892     // We hit this case with the lambda conversion-to-block optimization;
04893     // we don't want any extra casts here.
04894     } else if (isa<CastExpr>(E) &&
04895                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
04896       return E;
04897 
04898     // For message sends and property references, we try to find an
04899     // actual method.  FIXME: we should infer retention by selector in
04900     // cases where we don't have an actual method.
04901     } else {
04902       ObjCMethodDecl *D = nullptr;
04903       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
04904         D = Send->getMethodDecl();
04905       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
04906         D = BoxedExpr->getBoxingMethod();
04907       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
04908         D = ArrayLit->getArrayWithObjectsMethod();
04909       } else if (ObjCDictionaryLiteral *DictLit
04910                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
04911         D = DictLit->getDictWithObjectsMethod();
04912       }
04913 
04914       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
04915 
04916       // Don't do reclaims on performSelector calls; despite their
04917       // return type, the invoked method doesn't necessarily actually
04918       // return an object.
04919       if (!ReturnsRetained &&
04920           D && D->getMethodFamily() == OMF_performSelector)
04921         return E;
04922     }
04923 
04924     // Don't reclaim an object of Class type.
04925     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
04926       return E;
04927 
04928     ExprNeedsCleanups = true;
04929 
04930     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
04931                                    : CK_ARCReclaimReturnedObject);
04932     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
04933                                     VK_RValue);
04934   }
04935 
04936   if (!getLangOpts().CPlusPlus)
04937     return E;
04938 
04939   // Search for the base element type (cf. ASTContext::getBaseElementType) with
04940   // a fast path for the common case that the type is directly a RecordType.
04941   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
04942   const RecordType *RT = nullptr;
04943   while (!RT) {
04944     switch (T->getTypeClass()) {
04945     case Type::Record:
04946       RT = cast<RecordType>(T);
04947       break;
04948     case Type::ConstantArray:
04949     case Type::IncompleteArray:
04950     case Type::VariableArray:
04951     case Type::DependentSizedArray:
04952       T = cast<ArrayType>(T)->getElementType().getTypePtr();
04953       break;
04954     default:
04955       return E;
04956     }
04957   }
04958 
04959   // That should be enough to guarantee that this type is complete, if we're
04960   // not processing a decltype expression.
04961   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
04962   if (RD->isInvalidDecl() || RD->isDependentContext())
04963     return E;
04964 
04965   bool IsDecltype = ExprEvalContexts.back().IsDecltype;
04966   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
04967 
04968   if (Destructor) {
04969     MarkFunctionReferenced(E->getExprLoc(), Destructor);
04970     CheckDestructorAccess(E->getExprLoc(), Destructor,
04971                           PDiag(diag::err_access_dtor_temp)
04972                             << E->getType());
04973     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
04974       return ExprError();
04975 
04976     // If destructor is trivial, we can avoid the extra copy.
04977     if (Destructor->isTrivial())
04978       return E;
04979 
04980     // We need a cleanup, but we don't need to remember the temporary.
04981     ExprNeedsCleanups = true;
04982   }
04983 
04984   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
04985   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
04986 
04987   if (IsDecltype)
04988     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
04989 
04990   return Bind;
04991 }
04992 
04993 ExprResult
04994 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
04995   if (SubExpr.isInvalid())
04996     return ExprError();
04997 
04998   return MaybeCreateExprWithCleanups(SubExpr.get());
04999 }
05000 
05001 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
05002   assert(SubExpr && "subexpression can't be null!");
05003 
05004   CleanupVarDeclMarking();
05005 
05006   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
05007   assert(ExprCleanupObjects.size() >= FirstCleanup);
05008   assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
05009   if (!ExprNeedsCleanups)
05010     return SubExpr;
05011 
05012   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
05013                                      ExprCleanupObjects.size() - FirstCleanup);
05014 
05015   Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
05016   DiscardCleanupsInEvaluationContext();
05017 
05018   return E;
05019 }
05020 
05021 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
05022   assert(SubStmt && "sub-statement can't be null!");
05023 
05024   CleanupVarDeclMarking();
05025 
05026   if (!ExprNeedsCleanups)
05027     return SubStmt;
05028 
05029   // FIXME: In order to attach the temporaries, wrap the statement into
05030   // a StmtExpr; currently this is only used for asm statements.
05031   // This is hacky, either create a new CXXStmtWithTemporaries statement or
05032   // a new AsmStmtWithTemporaries.
05033   CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
05034                                                       SourceLocation(),
05035                                                       SourceLocation());
05036   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
05037                                    SourceLocation());
05038   return MaybeCreateExprWithCleanups(E);
05039 }
05040 
05041 /// Process the expression contained within a decltype. For such expressions,
05042 /// certain semantic checks on temporaries are delayed until this point, and
05043 /// are omitted for the 'topmost' call in the decltype expression. If the
05044 /// topmost call bound a temporary, strip that temporary off the expression.
05045 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
05046   assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
05047 
05048   // C++11 [expr.call]p11:
05049   //   If a function call is a prvalue of object type,
05050   // -- if the function call is either
05051   //   -- the operand of a decltype-specifier, or
05052   //   -- the right operand of a comma operator that is the operand of a
05053   //      decltype-specifier,
05054   //   a temporary object is not introduced for the prvalue.
05055 
05056   // Recursively rebuild ParenExprs and comma expressions to strip out the
05057   // outermost CXXBindTemporaryExpr, if any.
05058   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
05059     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
05060     if (SubExpr.isInvalid())
05061       return ExprError();
05062     if (SubExpr.get() == PE->getSubExpr())
05063       return E;
05064     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
05065   }
05066   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
05067     if (BO->getOpcode() == BO_Comma) {
05068       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
05069       if (RHS.isInvalid())
05070         return ExprError();
05071       if (RHS.get() == BO->getRHS())
05072         return E;
05073       return new (Context) BinaryOperator(
05074           BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
05075           BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
05076     }
05077   }
05078 
05079   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
05080   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
05081                               : nullptr;
05082   if (TopCall)
05083     E = TopCall;
05084   else
05085     TopBind = nullptr;
05086 
05087   // Disable the special decltype handling now.
05088   ExprEvalContexts.back().IsDecltype = false;
05089 
05090   // In MS mode, don't perform any extra checking of call return types within a
05091   // decltype expression.
05092   if (getLangOpts().MSVCCompat)
05093     return E;
05094 
05095   // Perform the semantic checks we delayed until this point.
05096   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
05097        I != N; ++I) {
05098     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
05099     if (Call == TopCall)
05100       continue;
05101 
05102     if (CheckCallReturnType(Call->getCallReturnType(),
05103                             Call->getLocStart(),
05104                             Call, Call->getDirectCallee()))
05105       return ExprError();
05106   }
05107 
05108   // Now all relevant types are complete, check the destructors are accessible
05109   // and non-deleted, and annotate them on the temporaries.
05110   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
05111        I != N; ++I) {
05112     CXXBindTemporaryExpr *Bind =
05113       ExprEvalContexts.back().DelayedDecltypeBinds[I];
05114     if (Bind == TopBind)
05115       continue;
05116 
05117     CXXTemporary *Temp = Bind->getTemporary();
05118 
05119     CXXRecordDecl *RD =
05120       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
05121     CXXDestructorDecl *Destructor = LookupDestructor(RD);
05122     Temp->setDestructor(Destructor);
05123 
05124     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
05125     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
05126                           PDiag(diag::err_access_dtor_temp)
05127                             << Bind->getType());
05128     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
05129       return ExprError();
05130 
05131     // We need a cleanup, but we don't need to remember the temporary.
05132     ExprNeedsCleanups = true;
05133   }
05134 
05135   // Possibly strip off the top CXXBindTemporaryExpr.
05136   return E;
05137 }
05138 
05139 /// Note a set of 'operator->' functions that were used for a member access.
05140 static void noteOperatorArrows(Sema &S,
05141                                ArrayRef<FunctionDecl *> OperatorArrows) {
05142   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
05143   // FIXME: Make this configurable?
05144   unsigned Limit = 9;
05145   if (OperatorArrows.size() > Limit) {
05146     // Produce Limit-1 normal notes and one 'skipping' note.
05147     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
05148     SkipCount = OperatorArrows.size() - (Limit - 1);
05149   }
05150 
05151   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
05152     if (I == SkipStart) {
05153       S.Diag(OperatorArrows[I]->getLocation(),
05154              diag::note_operator_arrows_suppressed)
05155           << SkipCount;
05156       I += SkipCount;
05157     } else {
05158       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
05159           << OperatorArrows[I]->getCallResultType();
05160       ++I;
05161     }
05162   }
05163 }
05164 
05165 ExprResult
05166 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
05167                                    tok::TokenKind OpKind, ParsedType &ObjectType,
05168                                    bool &MayBePseudoDestructor) {
05169   // Since this might be a postfix expression, get rid of ParenListExprs.
05170   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
05171   if (Result.isInvalid()) return ExprError();
05172   Base = Result.get();
05173 
05174   Result = CheckPlaceholderExpr(Base);
05175   if (Result.isInvalid()) return ExprError();
05176   Base = Result.get();
05177 
05178   QualType BaseType = Base->getType();
05179   MayBePseudoDestructor = false;
05180   if (BaseType->isDependentType()) {
05181     // If we have a pointer to a dependent type and are using the -> operator,
05182     // the object type is the type that the pointer points to. We might still
05183     // have enough information about that type to do something useful.
05184     if (OpKind == tok::arrow)
05185       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
05186         BaseType = Ptr->getPointeeType();
05187 
05188     ObjectType = ParsedType::make(BaseType);
05189     MayBePseudoDestructor = true;
05190     return Base;
05191   }
05192 
05193   // C++ [over.match.oper]p8:
05194   //   [...] When operator->returns, the operator-> is applied  to the value
05195   //   returned, with the original second operand.
05196   if (OpKind == tok::arrow) {
05197     QualType StartingType = BaseType;
05198     bool NoArrowOperatorFound = false;
05199     bool FirstIteration = true;
05200     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
05201     // The set of types we've considered so far.
05202     llvm::SmallPtrSet<CanQualType,8> CTypes;
05203     SmallVector<FunctionDecl*, 8> OperatorArrows;
05204     CTypes.insert(Context.getCanonicalType(BaseType));
05205 
05206     while (BaseType->isRecordType()) {
05207       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
05208         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
05209           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
05210         noteOperatorArrows(*this, OperatorArrows);
05211         Diag(OpLoc, diag::note_operator_arrow_depth)
05212           << getLangOpts().ArrowDepth;
05213         return ExprError();
05214       }
05215 
05216       Result = BuildOverloadedArrowExpr(
05217           S, Base, OpLoc,
05218           // When in a template specialization and on the first loop iteration,
05219           // potentially give the default diagnostic (with the fixit in a
05220           // separate note) instead of having the error reported back to here
05221           // and giving a diagnostic with a fixit attached to the error itself.
05222           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
05223               ? nullptr
05224               : &NoArrowOperatorFound);
05225       if (Result.isInvalid()) {
05226         if (NoArrowOperatorFound) {
05227           if (FirstIteration) {
05228             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
05229               << BaseType << 1 << Base->getSourceRange()
05230               << FixItHint::CreateReplacement(OpLoc, ".");
05231             OpKind = tok::period;
05232             break;
05233           }
05234           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
05235             << BaseType << Base->getSourceRange();
05236           CallExpr *CE = dyn_cast<CallExpr>(Base);
05237           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
05238             Diag(CD->getLocStart(),
05239                  diag::note_member_reference_arrow_from_operator_arrow);
05240           }
05241         }
05242         return ExprError();
05243       }
05244       Base = Result.get();
05245       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
05246         OperatorArrows.push_back(OpCall->getDirectCallee());
05247       BaseType = Base->getType();
05248       CanQualType CBaseType = Context.getCanonicalType(BaseType);
05249       if (!CTypes.insert(CBaseType)) {
05250         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
05251         noteOperatorArrows(*this, OperatorArrows);
05252         return ExprError();
05253       }
05254       FirstIteration = false;
05255     }
05256 
05257     if (OpKind == tok::arrow &&
05258         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
05259       BaseType = BaseType->getPointeeType();
05260   }
05261 
05262   // Objective-C properties allow "." access on Objective-C pointer types,
05263   // so adjust the base type to the object type itself.
05264   if (BaseType->isObjCObjectPointerType())
05265     BaseType = BaseType->getPointeeType();
05266   
05267   // C++ [basic.lookup.classref]p2:
05268   //   [...] If the type of the object expression is of pointer to scalar
05269   //   type, the unqualified-id is looked up in the context of the complete
05270   //   postfix-expression.
05271   //
05272   // This also indicates that we could be parsing a pseudo-destructor-name.
05273   // Note that Objective-C class and object types can be pseudo-destructor
05274   // expressions or normal member (ivar or property) access expressions.
05275   if (BaseType->isObjCObjectOrInterfaceType()) {
05276     MayBePseudoDestructor = true;
05277   } else if (!BaseType->isRecordType()) {
05278     ObjectType = ParsedType();
05279     MayBePseudoDestructor = true;
05280     return Base;
05281   }
05282 
05283   // The object type must be complete (or dependent), or
05284   // C++11 [expr.prim.general]p3:
05285   //   Unlike the object expression in other contexts, *this is not required to
05286   //   be of complete type for purposes of class member access (5.2.5) outside 
05287   //   the member function body.
05288   if (!BaseType->isDependentType() &&
05289       !isThisOutsideMemberFunctionBody(BaseType) &&
05290       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
05291     return ExprError();
05292 
05293   // C++ [basic.lookup.classref]p2:
05294   //   If the id-expression in a class member access (5.2.5) is an
05295   //   unqualified-id, and the type of the object expression is of a class
05296   //   type C (or of pointer to a class type C), the unqualified-id is looked
05297   //   up in the scope of class C. [...]
05298   ObjectType = ParsedType::make(BaseType);
05299   return Base;
05300 }
05301 
05302 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
05303                                                    Expr *MemExpr) {
05304   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
05305   Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
05306     << isa<CXXPseudoDestructorExpr>(MemExpr)
05307     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
05308 
05309   return ActOnCallExpr(/*Scope*/ nullptr,
05310                        MemExpr,
05311                        /*LPLoc*/ ExpectedLParenLoc,
05312                        None,
05313                        /*RPLoc*/ ExpectedLParenLoc);
05314 }
05315 
05316 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 
05317                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
05318   if (Base->hasPlaceholderType()) {
05319     ExprResult result = S.CheckPlaceholderExpr(Base);
05320     if (result.isInvalid()) return true;
05321     Base = result.get();
05322   }
05323   ObjectType = Base->getType();
05324 
05325   // C++ [expr.pseudo]p2:
05326   //   The left-hand side of the dot operator shall be of scalar type. The
05327   //   left-hand side of the arrow operator shall be of pointer to scalar type.
05328   //   This scalar type is the object type.
05329   // Note that this is rather different from the normal handling for the
05330   // arrow operator.
05331   if (OpKind == tok::arrow) {
05332     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
05333       ObjectType = Ptr->getPointeeType();
05334     } else if (!Base->isTypeDependent()) {
05335       // The user wrote "p->" when she probably meant "p."; fix it.
05336       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
05337         << ObjectType << true
05338         << FixItHint::CreateReplacement(OpLoc, ".");
05339       if (S.isSFINAEContext())
05340         return true;
05341 
05342       OpKind = tok::period;
05343     }
05344   }
05345 
05346   return false;
05347 }
05348 
05349 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
05350                                            SourceLocation OpLoc,
05351                                            tok::TokenKind OpKind,
05352                                            const CXXScopeSpec &SS,
05353                                            TypeSourceInfo *ScopeTypeInfo,
05354                                            SourceLocation CCLoc,
05355                                            SourceLocation TildeLoc,
05356                                          PseudoDestructorTypeStorage Destructed,
05357                                            bool HasTrailingLParen) {
05358   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
05359 
05360   QualType ObjectType;
05361   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
05362     return ExprError();
05363 
05364   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
05365       !ObjectType->isVectorType()) {
05366     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
05367       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
05368     else {
05369       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
05370         << ObjectType << Base->getSourceRange();
05371       return ExprError();
05372     }
05373   }
05374 
05375   // C++ [expr.pseudo]p2:
05376   //   [...] The cv-unqualified versions of the object type and of the type
05377   //   designated by the pseudo-destructor-name shall be the same type.
05378   if (DestructedTypeInfo) {
05379     QualType DestructedType = DestructedTypeInfo->getType();
05380     SourceLocation DestructedTypeStart
05381       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
05382     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
05383       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
05384         Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
05385           << ObjectType << DestructedType << Base->getSourceRange()
05386           << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
05387 
05388         // Recover by setting the destructed type to the object type.
05389         DestructedType = ObjectType;
05390         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
05391                                                            DestructedTypeStart);
05392         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
05393       } else if (DestructedType.getObjCLifetime() != 
05394                                                 ObjectType.getObjCLifetime()) {
05395         
05396         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
05397           // Okay: just pretend that the user provided the correctly-qualified
05398           // type.
05399         } else {
05400           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
05401             << ObjectType << DestructedType << Base->getSourceRange()
05402             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
05403         }
05404         
05405         // Recover by setting the destructed type to the object type.
05406         DestructedType = ObjectType;
05407         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
05408                                                            DestructedTypeStart);
05409         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
05410       }
05411     }
05412   }
05413 
05414   // C++ [expr.pseudo]p2:
05415   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
05416   //   form
05417   //
05418   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
05419   //
05420   //   shall designate the same scalar type.
05421   if (ScopeTypeInfo) {
05422     QualType ScopeType = ScopeTypeInfo->getType();
05423     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
05424         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
05425 
05426       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
05427            diag::err_pseudo_dtor_type_mismatch)
05428         << ObjectType << ScopeType << Base->getSourceRange()
05429         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
05430 
05431       ScopeType = QualType();
05432       ScopeTypeInfo = nullptr;
05433     }
05434   }
05435 
05436   Expr *Result
05437     = new (Context) CXXPseudoDestructorExpr(Context, Base,
05438                                             OpKind == tok::arrow, OpLoc,
05439                                             SS.getWithLocInContext(Context),
05440                                             ScopeTypeInfo,
05441                                             CCLoc,
05442                                             TildeLoc,
05443                                             Destructed);
05444 
05445   if (HasTrailingLParen)
05446     return Result;
05447 
05448   return DiagnoseDtorReference(Destructed.getLocation(), Result);
05449 }
05450 
05451 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
05452                                            SourceLocation OpLoc,
05453                                            tok::TokenKind OpKind,
05454                                            CXXScopeSpec &SS,
05455                                            UnqualifiedId &FirstTypeName,
05456                                            SourceLocation CCLoc,
05457                                            SourceLocation TildeLoc,
05458                                            UnqualifiedId &SecondTypeName,
05459                                            bool HasTrailingLParen) {
05460   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
05461           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
05462          "Invalid first type name in pseudo-destructor");
05463   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
05464           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
05465          "Invalid second type name in pseudo-destructor");
05466 
05467   QualType ObjectType;
05468   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
05469     return ExprError();
05470 
05471   // Compute the object type that we should use for name lookup purposes. Only
05472   // record types and dependent types matter.
05473   ParsedType ObjectTypePtrForLookup;
05474   if (!SS.isSet()) {
05475     if (ObjectType->isRecordType())
05476       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
05477     else if (ObjectType->isDependentType())
05478       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
05479   }
05480 
05481   // Convert the name of the type being destructed (following the ~) into a
05482   // type (with source-location information).
05483   QualType DestructedType;
05484   TypeSourceInfo *DestructedTypeInfo = nullptr;
05485   PseudoDestructorTypeStorage Destructed;
05486   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
05487     ParsedType T = getTypeName(*SecondTypeName.Identifier,
05488                                SecondTypeName.StartLocation,
05489                                S, &SS, true, false, ObjectTypePtrForLookup);
05490     if (!T &&
05491         ((SS.isSet() && !computeDeclContext(SS, false)) ||
05492          (!SS.isSet() && ObjectType->isDependentType()))) {
05493       // The name of the type being destroyed is a dependent name, and we
05494       // couldn't find anything useful in scope. Just store the identifier and
05495       // it's location, and we'll perform (qualified) name lookup again at
05496       // template instantiation time.
05497       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
05498                                                SecondTypeName.StartLocation);
05499     } else if (!T) {
05500       Diag(SecondTypeName.StartLocation,
05501            diag::err_pseudo_dtor_destructor_non_type)
05502         << SecondTypeName.Identifier << ObjectType;
05503       if (isSFINAEContext())
05504         return ExprError();
05505 
05506       // Recover by assuming we had the right type all along.
05507       DestructedType = ObjectType;
05508     } else
05509       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
05510   } else {
05511     // Resolve the template-id to a type.
05512     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
05513     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
05514                                        TemplateId->NumArgs);
05515     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
05516                                        TemplateId->TemplateKWLoc,
05517                                        TemplateId->Template,
05518                                        TemplateId->TemplateNameLoc,
05519                                        TemplateId->LAngleLoc,
05520                                        TemplateArgsPtr,
05521                                        TemplateId->RAngleLoc);
05522     if (T.isInvalid() || !T.get()) {
05523       // Recover by assuming we had the right type all along.
05524       DestructedType = ObjectType;
05525     } else
05526       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
05527   }
05528 
05529   // If we've performed some kind of recovery, (re-)build the type source
05530   // information.
05531   if (!DestructedType.isNull()) {
05532     if (!DestructedTypeInfo)
05533       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
05534                                                   SecondTypeName.StartLocation);
05535     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
05536   }
05537 
05538   // Convert the name of the scope type (the type prior to '::') into a type.
05539   TypeSourceInfo *ScopeTypeInfo = nullptr;
05540   QualType ScopeType;
05541   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
05542       FirstTypeName.Identifier) {
05543     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
05544       ParsedType T = getTypeName(*FirstTypeName.Identifier,
05545                                  FirstTypeName.StartLocation,
05546                                  S, &SS, true, false, ObjectTypePtrForLookup);
05547       if (!T) {
05548         Diag(FirstTypeName.StartLocation,
05549              diag::err_pseudo_dtor_destructor_non_type)
05550           << FirstTypeName.Identifier << ObjectType;
05551 
05552         if (isSFINAEContext())
05553           return ExprError();
05554 
05555         // Just drop this type. It's unnecessary anyway.
05556         ScopeType = QualType();
05557       } else
05558         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
05559     } else {
05560       // Resolve the template-id to a type.
05561       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
05562       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
05563                                          TemplateId->NumArgs);
05564       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
05565                                          TemplateId->TemplateKWLoc,
05566                                          TemplateId->Template,
05567                                          TemplateId->TemplateNameLoc,
05568                                          TemplateId->LAngleLoc,
05569                                          TemplateArgsPtr,
05570                                          TemplateId->RAngleLoc);
05571       if (T.isInvalid() || !T.get()) {
05572         // Recover by dropping this type.
05573         ScopeType = QualType();
05574       } else
05575         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
05576     }
05577   }
05578 
05579   if (!ScopeType.isNull() && !ScopeTypeInfo)
05580     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
05581                                                   FirstTypeName.StartLocation);
05582 
05583 
05584   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
05585                                    ScopeTypeInfo, CCLoc, TildeLoc,
05586                                    Destructed, HasTrailingLParen);
05587 }
05588 
05589 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
05590                                            SourceLocation OpLoc,
05591                                            tok::TokenKind OpKind,
05592                                            SourceLocation TildeLoc, 
05593                                            const DeclSpec& DS,
05594                                            bool HasTrailingLParen) {
05595   QualType ObjectType;
05596   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
05597     return ExprError();
05598 
05599   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
05600 
05601   TypeLocBuilder TLB;
05602   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
05603   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
05604   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
05605   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
05606 
05607   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
05608                                    nullptr, SourceLocation(), TildeLoc,
05609                                    Destructed, HasTrailingLParen);
05610 }
05611 
05612 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
05613                                         CXXConversionDecl *Method,
05614                                         bool HadMultipleCandidates) {
05615   if (Method->getParent()->isLambda() &&
05616       Method->getConversionType()->isBlockPointerType()) {
05617     // This is a lambda coversion to block pointer; check if the argument
05618     // is a LambdaExpr.
05619     Expr *SubE = E;
05620     CastExpr *CE = dyn_cast<CastExpr>(SubE);
05621     if (CE && CE->getCastKind() == CK_NoOp)
05622       SubE = CE->getSubExpr();
05623     SubE = SubE->IgnoreParens();
05624     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
05625       SubE = BE->getSubExpr();
05626     if (isa<LambdaExpr>(SubE)) {
05627       // For the conversion to block pointer on a lambda expression, we
05628       // construct a special BlockLiteral instead; this doesn't really make
05629       // a difference in ARC, but outside of ARC the resulting block literal
05630       // follows the normal lifetime rules for block literals instead of being
05631       // autoreleased.
05632       DiagnosticErrorTrap Trap(Diags);
05633       ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
05634                                                      E->getExprLoc(),
05635                                                      Method, E);
05636       if (Exp.isInvalid())
05637         Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
05638       return Exp;
05639     }
05640   }
05641 
05642   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
05643                                           FoundDecl, Method);
05644   if (Exp.isInvalid())
05645     return true;
05646 
05647   MemberExpr *ME =
05648       new (Context) MemberExpr(Exp.get(), /*IsArrow=*/false, Method,
05649                                SourceLocation(), Context.BoundMemberTy,
05650                                VK_RValue, OK_Ordinary);
05651   if (HadMultipleCandidates)
05652     ME->setHadMultipleCandidates(true);
05653   MarkMemberReferenced(ME);
05654 
05655   QualType ResultType = Method->getReturnType();
05656   ExprValueKind VK = Expr::getValueKindForType(ResultType);
05657   ResultType = ResultType.getNonLValueExprType(Context);
05658 
05659   CXXMemberCallExpr *CE =
05660     new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
05661                                     Exp.get()->getLocEnd());
05662   return CE;
05663 }
05664 
05665 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
05666                                       SourceLocation RParen) {
05667   CanThrowResult CanThrow = canThrow(Operand);
05668   return new (Context)
05669       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
05670 }
05671 
05672 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
05673                                    Expr *Operand, SourceLocation RParen) {
05674   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
05675 }
05676 
05677 static bool IsSpecialDiscardedValue(Expr *E) {
05678   // In C++11, discarded-value expressions of a certain form are special,
05679   // according to [expr]p10:
05680   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
05681   //   expression is an lvalue of volatile-qualified type and it has
05682   //   one of the following forms:
05683   E = E->IgnoreParens();
05684 
05685   //   - id-expression (5.1.1),
05686   if (isa<DeclRefExpr>(E))
05687     return true;
05688 
05689   //   - subscripting (5.2.1),
05690   if (isa<ArraySubscriptExpr>(E))
05691     return true;
05692 
05693   //   - class member access (5.2.5),
05694   if (isa<MemberExpr>(E))
05695     return true;
05696 
05697   //   - indirection (5.3.1),
05698   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
05699     if (UO->getOpcode() == UO_Deref)
05700       return true;
05701 
05702   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
05703     //   - pointer-to-member operation (5.5),
05704     if (BO->isPtrMemOp())
05705       return true;
05706 
05707     //   - comma expression (5.18) where the right operand is one of the above.
05708     if (BO->getOpcode() == BO_Comma)
05709       return IsSpecialDiscardedValue(BO->getRHS());
05710   }
05711 
05712   //   - conditional expression (5.16) where both the second and the third
05713   //     operands are one of the above, or
05714   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
05715     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
05716            IsSpecialDiscardedValue(CO->getFalseExpr());
05717   // The related edge case of "*x ?: *x".
05718   if (BinaryConditionalOperator *BCO =
05719           dyn_cast<BinaryConditionalOperator>(E)) {
05720     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
05721       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
05722              IsSpecialDiscardedValue(BCO->getFalseExpr());
05723   }
05724 
05725   // Objective-C++ extensions to the rule.
05726   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
05727     return true;
05728 
05729   return false;
05730 }
05731 
05732 /// Perform the conversions required for an expression used in a
05733 /// context that ignores the result.
05734 ExprResult Sema::IgnoredValueConversions(Expr *E) {
05735   if (E->hasPlaceholderType()) {
05736     ExprResult result = CheckPlaceholderExpr(E);
05737     if (result.isInvalid()) return E;
05738     E = result.get();
05739   }
05740 
05741   // C99 6.3.2.1:
05742   //   [Except in specific positions,] an lvalue that does not have
05743   //   array type is converted to the value stored in the
05744   //   designated object (and is no longer an lvalue).
05745   if (E->isRValue()) {
05746     // In C, function designators (i.e. expressions of function type)
05747     // are r-values, but we still want to do function-to-pointer decay
05748     // on them.  This is both technically correct and convenient for
05749     // some clients.
05750     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
05751       return DefaultFunctionArrayConversion(E);
05752 
05753     return E;
05754   }
05755 
05756   if (getLangOpts().CPlusPlus)  {
05757     // The C++11 standard defines the notion of a discarded-value expression;
05758     // normally, we don't need to do anything to handle it, but if it is a
05759     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
05760     // conversion.
05761     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
05762         E->getType().isVolatileQualified() &&
05763         IsSpecialDiscardedValue(E)) {
05764       ExprResult Res = DefaultLvalueConversion(E);
05765       if (Res.isInvalid())
05766         return E;
05767       E = Res.get();
05768     } 
05769     return E;
05770   }
05771 
05772   // GCC seems to also exclude expressions of incomplete enum type.
05773   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
05774     if (!T->getDecl()->isComplete()) {
05775       // FIXME: stupid workaround for a codegen bug!
05776       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
05777       return E;
05778     }
05779   }
05780 
05781   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
05782   if (Res.isInvalid())
05783     return E;
05784   E = Res.get();
05785 
05786   if (!E->getType()->isVoidType())
05787     RequireCompleteType(E->getExprLoc(), E->getType(),
05788                         diag::err_incomplete_type);
05789   return E;
05790 }
05791 
05792 // If we can unambiguously determine whether Var can never be used
05793 // in a constant expression, return true.
05794 //  - if the variable and its initializer are non-dependent, then
05795 //    we can unambiguously check if the variable is a constant expression.
05796 //  - if the initializer is not value dependent - we can determine whether
05797 //    it can be used to initialize a constant expression.  If Init can not
05798 //    be used to initialize a constant expression we conclude that Var can 
05799 //    never be a constant expression.
05800 //  - FXIME: if the initializer is dependent, we can still do some analysis and
05801 //    identify certain cases unambiguously as non-const by using a Visitor:
05802 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
05803 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
05804 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 
05805     ASTContext &Context) {
05806   if (isa<ParmVarDecl>(Var)) return true;
05807   const VarDecl *DefVD = nullptr;
05808 
05809   // If there is no initializer - this can not be a constant expression.
05810   if (!Var->getAnyInitializer(DefVD)) return true;
05811   assert(DefVD);
05812   if (DefVD->isWeak()) return false;
05813   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
05814 
05815   Expr *Init = cast<Expr>(Eval->Value);
05816 
05817   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
05818     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
05819     // of value-dependent expressions, and use it here to determine whether the
05820     // initializer is a potential constant expression.
05821     return false;
05822   }
05823 
05824   return !IsVariableAConstantExpression(Var, Context); 
05825 }
05826 
05827 /// \brief Check if the current lambda has any potential captures 
05828 /// that must be captured by any of its enclosing lambdas that are ready to 
05829 /// capture. If there is a lambda that can capture a nested 
05830 /// potential-capture, go ahead and do so.  Also, check to see if any 
05831 /// variables are uncaptureable or do not involve an odr-use so do not 
05832 /// need to be captured.
05833 
05834 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
05835     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
05836 
05837   assert(!S.isUnevaluatedContext());  
05838   assert(S.CurContext->isDependentContext()); 
05839   assert(CurrentLSI->CallOperator == S.CurContext && 
05840       "The current call operator must be synchronized with Sema's CurContext");
05841 
05842   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
05843 
05844   ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
05845       S.FunctionScopes.data(), S.FunctionScopes.size());
05846   
05847   // All the potentially captureable variables in the current nested
05848   // lambda (within a generic outer lambda), must be captured by an
05849   // outer lambda that is enclosed within a non-dependent context.
05850   const unsigned NumPotentialCaptures =
05851       CurrentLSI->getNumPotentialVariableCaptures();
05852   for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
05853     Expr *VarExpr = nullptr;
05854     VarDecl *Var = nullptr;
05855     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
05856     // If the variable is clearly identified as non-odr-used and the full
05857     // expression is not instantiation dependent, only then do we not 
05858     // need to check enclosing lambda's for speculative captures.
05859     // For e.g.:
05860     // Even though 'x' is not odr-used, it should be captured.
05861     // int test() {
05862     //   const int x = 10;
05863     //   auto L = [=](auto a) {
05864     //     (void) +x + a;
05865     //   };
05866     // }
05867     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
05868         !IsFullExprInstantiationDependent)
05869       continue;
05870 
05871     // If we have a capture-capable lambda for the variable, go ahead and
05872     // capture the variable in that lambda (and all its enclosing lambdas).
05873     if (const Optional<unsigned> Index =
05874             getStackIndexOfNearestEnclosingCaptureCapableLambda(
05875                 FunctionScopesArrayRef, Var, S)) {
05876       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
05877       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
05878                          &FunctionScopeIndexOfCapturableLambda);
05879     } 
05880     const bool IsVarNeverAConstantExpression = 
05881         VariableCanNeverBeAConstantExpression(Var, S.Context);
05882     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
05883       // This full expression is not instantiation dependent or the variable
05884       // can not be used in a constant expression - which means 
05885       // this variable must be odr-used here, so diagnose a 
05886       // capture violation early, if the variable is un-captureable.
05887       // This is purely for diagnosing errors early.  Otherwise, this
05888       // error would get diagnosed when the lambda becomes capture ready.
05889       QualType CaptureType, DeclRefType;
05890       SourceLocation ExprLoc = VarExpr->getExprLoc();
05891       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
05892                           /*EllipsisLoc*/ SourceLocation(), 
05893                           /*BuildAndDiagnose*/false, CaptureType, 
05894                           DeclRefType, nullptr)) {
05895         // We will never be able to capture this variable, and we need
05896         // to be able to in any and all instantiations, so diagnose it.
05897         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
05898                           /*EllipsisLoc*/ SourceLocation(), 
05899                           /*BuildAndDiagnose*/true, CaptureType, 
05900                           DeclRefType, nullptr);
05901       }
05902     }
05903   }
05904 
05905   // Check if 'this' needs to be captured.
05906   if (CurrentLSI->hasPotentialThisCapture()) {
05907     // If we have a capture-capable lambda for 'this', go ahead and capture
05908     // 'this' in that lambda (and all its enclosing lambdas).
05909     if (const Optional<unsigned> Index =
05910             getStackIndexOfNearestEnclosingCaptureCapableLambda(
05911                 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
05912       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
05913       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
05914                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
05915                             &FunctionScopeIndexOfCapturableLambda);
05916     }
05917   }
05918 
05919   // Reset all the potential captures at the end of each full-expression.
05920   CurrentLSI->clearPotentialCaptures();
05921 }
05922 
05923 namespace {
05924 class TransformTypos : public TreeTransform<TransformTypos> {
05925   typedef TreeTransform<TransformTypos> BaseTransform;
05926 
05927   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
05928   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs;
05929   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
05930   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
05931 
05932   /// \brief Emit diagnostics for all of the TypoExprs encountered.
05933   /// If the TypoExprs were successfully corrected, then the diagnostics should
05934   /// suggest the corrections. Otherwise the diagnostics will not suggest
05935   /// anything (having been passed an empty TypoCorrection).
05936   void EmitAllDiagnostics() {
05937     for (auto E : TypoExprs) {
05938       TypoExpr *TE = cast<TypoExpr>(E);
05939       auto &State = SemaRef.getTypoExprState(TE);
05940       if (State.DiagHandler) {
05941         TypoCorrection TC = State.Consumer->getCurrentCorrection();
05942         ExprResult Replacement = TransformCache[TE];
05943 
05944         // Extract the NamedDecl from the transformed TypoExpr and add it to the
05945         // TypoCorrection, replacing the existing decls. This ensures the right
05946         // NamedDecl is used in diagnostics e.g. in the case where overload
05947         // resolution was used to select one from several possible decls that
05948         // had been stored in the TypoCorrection.
05949         if (auto *ND = getDeclFromExpr(
05950                 Replacement.isInvalid() ? nullptr : Replacement.get()))
05951           TC.setCorrectionDecl(ND);
05952 
05953         State.DiagHandler(TC);
05954       }
05955       SemaRef.clearDelayedTypo(TE);
05956     }
05957   }
05958 
05959   /// \brief If corrections for the first TypoExpr have been exhausted for a
05960   /// given combination of the other TypoExprs, retry those corrections against
05961   /// the next combination of substitutions for the other TypoExprs by advancing
05962   /// to the next potential correction of the second TypoExpr. For the second
05963   /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
05964   /// the stream is reset and the next TypoExpr's stream is advanced by one (a
05965   /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
05966   /// TransformCache). Returns true if there is still any untried combinations
05967   /// of corrections.
05968   bool CheckAndAdvanceTypoExprCorrectionStreams() {
05969     for (auto TE : TypoExprs) {
05970       auto &State = SemaRef.getTypoExprState(TE);
05971       TransformCache.erase(TE);
05972       if (!State.Consumer->finished())
05973         return true;
05974       State.Consumer->resetCorrectionStream();
05975     }
05976     return false;
05977   }
05978 
05979   NamedDecl *getDeclFromExpr(Expr *E) {
05980     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
05981       E = OverloadResolution[OE];
05982 
05983     if (!E)
05984       return nullptr;
05985     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
05986       return DRE->getDecl();
05987     if (auto *ME = dyn_cast<MemberExpr>(E))
05988       return ME->getMemberDecl();
05989     // FIXME: Add any other expr types that could be be seen by the delayed typo
05990     // correction TreeTransform for which the corresponding TypoCorrection could
05991     // contain multple decls.
05992     return nullptr;
05993   }
05994 
05995 public:
05996   TransformTypos(Sema &SemaRef, llvm::function_ref<ExprResult(Expr *)> Filter)
05997       : BaseTransform(SemaRef), ExprFilter(Filter) {}
05998 
05999   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
06000                                    MultiExprArg Args,
06001                                    SourceLocation RParenLoc,
06002                                    Expr *ExecConfig = nullptr) {
06003     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
06004                                                  RParenLoc, ExecConfig);
06005     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
06006       if (!Result.isInvalid() && Result.get())
06007         OverloadResolution[OE] = cast<CallExpr>(Result.get())->getCallee();
06008     }
06009     return Result;
06010   }
06011 
06012   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
06013 
06014   ExprResult Transform(Expr *E) {
06015     ExprResult res;
06016     bool error = false;
06017     while (true) {
06018       Sema::SFINAETrap Trap(SemaRef);
06019       res = TransformExpr(E);
06020       error = Trap.hasErrorOccurred();
06021 
06022       if (!(error || res.isInvalid()))
06023         res = ExprFilter(res.get());
06024 
06025       // Exit if either the transform was valid or if there were no TypoExprs
06026       // to transform that still have any untried correction candidates..
06027       if (!(error || res.isInvalid()) ||
06028           !CheckAndAdvanceTypoExprCorrectionStreams())
06029         break;
06030     }
06031 
06032     EmitAllDiagnostics();
06033 
06034     return res;
06035   }
06036 
06037   ExprResult TransformTypoExpr(TypoExpr *E) {
06038     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
06039     // cached transformation result if there is one and the TypoExpr isn't the
06040     // first one that was encountered.
06041     auto &CacheEntry = TransformCache[E];
06042     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
06043       return CacheEntry;
06044     }
06045 
06046     auto &State = SemaRef.getTypoExprState(E);
06047     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
06048 
06049     // For the first TypoExpr and an uncached TypoExpr, find the next likely
06050     // typo correction and return it.
06051     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
06052       ExprResult NE;
06053       if (State.RecoveryHandler) {
06054         NE = State.RecoveryHandler(SemaRef, E, TC);
06055       } else {
06056         LookupResult R(SemaRef,
06057                        State.Consumer->getLookupResult().getLookupNameInfo(),
06058                        State.Consumer->getLookupResult().getLookupKind());
06059         if (!TC.isKeyword())
06060           R.addDecl(TC.getCorrectionDecl());
06061         NE = SemaRef.BuildDeclarationNameExpr(CXXScopeSpec(), R, false);
06062       }
06063       assert(!NE.isUnset() &&
06064              "Typo was transformed into a valid-but-null ExprResult");
06065       if (!NE.isInvalid())
06066         return CacheEntry = NE;
06067     }
06068     return CacheEntry = ExprError();
06069   }
06070 };
06071 }
06072 
06073 ExprResult Sema::CorrectDelayedTyposInExpr(
06074     Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) {
06075   // If the current evaluation context indicates there are uncorrected typos
06076   // and the current expression isn't guaranteed to not have typos, try to
06077   // resolve any TypoExpr nodes that might be in the expression.
06078   if (!ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
06079       (E->isTypeDependent() || E->isValueDependent() ||
06080        E->isInstantiationDependent())) {
06081     auto TyposResolved = DelayedTypos.size();
06082     auto Result = TransformTypos(*this, Filter).Transform(E);
06083     TyposResolved -= DelayedTypos.size();
06084     if (TyposResolved) {
06085       ExprEvalContexts.back().NumTypos -= TyposResolved;
06086       return Result;
06087     }
06088   }
06089   return E;
06090 }
06091 
06092 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
06093                                      bool DiscardedValue,
06094                                      bool IsConstexpr, 
06095                                      bool IsLambdaInitCaptureInitializer) {
06096   ExprResult FullExpr = FE;
06097 
06098   if (!FullExpr.get())
06099     return ExprError();
06100  
06101   // If we are an init-expression in a lambdas init-capture, we should not 
06102   // diagnose an unexpanded pack now (will be diagnosed once lambda-expr 
06103   // containing full-expression is done).
06104   // template<class ... Ts> void test(Ts ... t) {
06105   //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
06106   //     return a;
06107   //   }() ...);
06108   // }
06109   // FIXME: This is a hack. It would be better if we pushed the lambda scope
06110   // when we parse the lambda introducer, and teach capturing (but not
06111   // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
06112   // corresponding class yet (that is, have LambdaScopeInfo either represent a
06113   // lambda where we've entered the introducer but not the body, or represent a
06114   // lambda where we've entered the body, depending on where the
06115   // parser/instantiation has got to).
06116   if (!IsLambdaInitCaptureInitializer && 
06117       DiagnoseUnexpandedParameterPack(FullExpr.get()))
06118     return ExprError();
06119 
06120   // Top-level expressions default to 'id' when we're in a debugger.
06121   if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
06122       FullExpr.get()->getType() == Context.UnknownAnyTy) {
06123     FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
06124     if (FullExpr.isInvalid())
06125       return ExprError();
06126   }
06127 
06128   if (DiscardedValue) {
06129     FullExpr = CheckPlaceholderExpr(FullExpr.get());
06130     if (FullExpr.isInvalid())
06131       return ExprError();
06132 
06133     FullExpr = IgnoredValueConversions(FullExpr.get());
06134     if (FullExpr.isInvalid())
06135       return ExprError();
06136   }
06137 
06138   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
06139   if (FullExpr.isInvalid())
06140     return ExprError();
06141 
06142   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
06143 
06144   // At the end of this full expression (which could be a deeply nested 
06145   // lambda), if there is a potential capture within the nested lambda, 
06146   // have the outer capture-able lambda try and capture it.
06147   // Consider the following code:
06148   // void f(int, int);
06149   // void f(const int&, double);
06150   // void foo() {   
06151   //  const int x = 10, y = 20;
06152   //  auto L = [=](auto a) {
06153   //      auto M = [=](auto b) {
06154   //         f(x, b); <-- requires x to be captured by L and M
06155   //         f(y, a); <-- requires y to be captured by L, but not all Ms
06156   //      };
06157   //   };
06158   // }
06159 
06160   // FIXME: Also consider what happens for something like this that involves 
06161   // the gnu-extension statement-expressions or even lambda-init-captures:   
06162   //   void f() {
06163   //     const int n = 0;
06164   //     auto L =  [&](auto a) {
06165   //       +n + ({ 0; a; });
06166   //     };
06167   //   }
06168   // 
06169   // Here, we see +n, and then the full-expression 0; ends, so we don't 
06170   // capture n (and instead remove it from our list of potential captures), 
06171   // and then the full-expression +n + ({ 0; }); ends, but it's too late 
06172   // for us to see that we need to capture n after all.
06173 
06174   LambdaScopeInfo *const CurrentLSI = getCurLambda();
06175   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 
06176   // even if CurContext is not a lambda call operator. Refer to that Bug Report
06177   // for an example of the code that might cause this asynchrony.  
06178   // By ensuring we are in the context of a lambda's call operator
06179   // we can fix the bug (we only need to check whether we need to capture
06180   // if we are within a lambda's body); but per the comments in that 
06181   // PR, a proper fix would entail :
06182   //   "Alternative suggestion:
06183   //   - Add to Sema an integer holding the smallest (outermost) scope 
06184   //     index that we are *lexically* within, and save/restore/set to 
06185   //     FunctionScopes.size() in InstantiatingTemplate's 
06186   //     constructor/destructor.
06187   //  - Teach the handful of places that iterate over FunctionScopes to 
06188   //    stop at the outermost enclosing lexical scope."
06189   const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
06190   if (IsInLambdaDeclContext && CurrentLSI &&
06191       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
06192     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
06193                                                               *this);
06194   return MaybeCreateExprWithCleanups(FullExpr);
06195 }
06196 
06197 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
06198   if (!FullStmt) return StmtError();
06199 
06200   return MaybeCreateStmtWithCleanups(FullStmt);
06201 }
06202 
06203 Sema::IfExistsResult 
06204 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
06205                                    CXXScopeSpec &SS,
06206                                    const DeclarationNameInfo &TargetNameInfo) {
06207   DeclarationName TargetName = TargetNameInfo.getName();
06208   if (!TargetName)
06209     return IER_DoesNotExist;
06210   
06211   // If the name itself is dependent, then the result is dependent.
06212   if (TargetName.isDependentName())
06213     return IER_Dependent;
06214   
06215   // Do the redeclaration lookup in the current scope.
06216   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
06217                  Sema::NotForRedeclaration);
06218   LookupParsedName(R, S, &SS);
06219   R.suppressDiagnostics();
06220   
06221   switch (R.getResultKind()) {
06222   case LookupResult::Found:
06223   case LookupResult::FoundOverloaded:
06224   case LookupResult::FoundUnresolvedValue:
06225   case LookupResult::Ambiguous:
06226     return IER_Exists;
06227     
06228   case LookupResult::NotFound:
06229     return IER_DoesNotExist;
06230     
06231   case LookupResult::NotFoundInCurrentInstantiation:
06232     return IER_Dependent;
06233   }
06234 
06235   llvm_unreachable("Invalid LookupResult Kind!");
06236 }
06237 
06238 Sema::IfExistsResult 
06239 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
06240                                    bool IsIfExists, CXXScopeSpec &SS,
06241                                    UnqualifiedId &Name) {
06242   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
06243   
06244   // Check for unexpanded parameter packs.
06245   SmallVector<UnexpandedParameterPack, 4> Unexpanded;
06246   collectUnexpandedParameterPacks(SS, Unexpanded);
06247   collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
06248   if (!Unexpanded.empty()) {
06249     DiagnoseUnexpandedParameterPacks(KeywordLoc,
06250                                      IsIfExists? UPPC_IfExists 
06251                                                : UPPC_IfNotExists, 
06252                                      Unexpanded);
06253     return IER_Error;
06254   }
06255   
06256   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
06257 }