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