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