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