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