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