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